跳到正文

题解

题解:P2917 [USACO08NOV] Toys G

wanganze约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年12月21日
收录
2026年9月30日
更新
2026年11月11日
篇幅
约 4 分钟
获赞
4
题目
P2917

版本

  1. v1当前

题意

即 P1251 餐巾计划问题。本题数据范围大一些。

分析

费用流板子。

建图方式:把每天拆成早上和晚上。

  1. 源点向每天晚上连边,流量为当天的玩具数量,费用为 00,含义为晚上得到派对使用过的玩具;
  2. 每天早上向汇点连边,流量为当天的玩具数量,费用为 00,含义为早上提供消毒过的玩具,满流时表示的玩具够用;
  3. 源点向每天早上连边,流量为 ∞\infin,费用为 TcTc,含义为可以从玩具店购买玩具;
  4. 然后对于两种服务,如果能在第 nn 天早上之前完成才有用,从每天晚上向完成的那天早上连边,流量为 ∞\infin,费用为服务费用;
  5. 每天晚上向第二天晚上连边,流量为 ∞\infin,费用为 00,含义为可以先不消毒用过的玩具,留到第二天。

然后图就建完了。

注意:因为边的流量差很多,所以可以分段加边。

实现

用的 SPFA + Dinic。

C++
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 200010;
const LL INF = 0x3f3f3f3f3f3f3f3fll;
struct edge
{
	LL x,cap,cost,rev;
};
vector<edge> e[N];
int n,m,s,t;
bool st[N];
LL d[N];
int it[N];
void add(int a,int b,LL c,LL d)
{
	e[a].push_back({b,c,d,(LL)e[b].size()});
	e[b].push_back({a,0,-d,(LL)e[a].size() - 1});
}
void spfa()
{
	memset(d,0x3f,sizeof d);
	queue<int> q;
	d[s] = 0;
	q.push(s);
	st[s] = 1;
	while(!q.empty())
	{
		int u = q.front();
		q.pop();
		st[u] = 0;
		for(auto t : e[u])
			if(t.cap > 0 && d[t.x] > d[u] + t.cost)
			{
				d[t.x] = d[u] + t.cost;
				if(!st[t.x]) q.push(t.x),st[t.x] = 1;
			}
	}
}
LL res;
LL dfs(int u,LL f)
{
	if(u == t) return f;
	st[u] = 1;
	for(int &i = it[u]; i < e[u].size(); i ++)
	{
		edge &t = e[u][i]; 
		if(!st[t.x] && d[u] + t.cost == d[t.x] && t.cap > 0)
		{
			LL d = dfs(t.x,min(f,t.cap));
			if(d > 0)
			{
				t.cap -= d;
				e[t.x][t.rev].cap += d;
				res += d * t.cost;
				st[u] = 0; 
				return d;
			}
		}
	}
	st[u] = 0; 
	return 0;
}
LL dinic() 
{
	LL flow = 0;
	while(1)
	{
		spfa();
		if(d[t] == INF) break;
		memset(it,0,sizeof it);
		LL d = dfs(s,1e18);
		while(d > 0)
		{
			flow += d;
			d = dfs(s,1e18);
		}
	}
	return flow;
}
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	int a,b,c,d;
	cin>>n>>a>>c>>b>>d>>m;
	s = 0,t = 2 * n + 1;
	for(int i = 1; i <= n; i ++)
	{
		add(s,i + n,1e9,m);
		if(i + a <= n) add(i,i + n + a,1e9,b);
		if(i + c <= n) add(i,i + n + c,1e9,d);
		if(i < n) add(i,i + 1,1e9,0);
	}
	dinic();
	for(int i = 1,x; i <= n; i ++)
	{
		cin>>x;
		add(s,i,x,0);
		add(i + n,t,x,0);
	}
	LL f = dinic();
	cout<<res<<endl;
	return 0;
}
原文