aaplloo

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

G

最大流(待修)

#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define MAXN 2005
#define INF 0x3f3f3f3f3f3f3f3f
#define LL long long
#define Int register int
using namespace std;
inline void read(LL &x)
{
	x = 0;
	LL f = 1;
	char s = getchar();
	while (s < '0' || s > '9')
	{
		if (s == '-')
			f = -1;
		s = getchar();
	}
	while (s >= '0' && s <= '9')
	{
		x = (x << 3) + (x << 1) + (s ^ 48);
		s = getchar();
	}
	x *= f;
}
struct node
{
	LL v, w, Id;
	node(){}
	node(LL V,LL W,LL ID)
	{
		v = V;
		w = W;
		Id = ID;
	}
};
inline LL Min(LL x,LL y)
{
	return x < y ? x : y;
}
LL n, m, s, t, MaxFlow;
vector<node> G[MAXN];
LL Dep[MAXN], Cur[MAXN];
bool Bfs()
{
	memset(Dep, -1, sizeof Dep);
	queue<LL> Q;
	Q.push( s );
	Dep[s] = 0;
	while (! Q.empty())
	{
		LL x = Q.front();
		Q.pop();
		for (Int i = 0; i < G[x].size(); ++ i)
		{
			LL to = G[x][i].v;
			if (Dep[to] == -1 && G[x][i].w > 0)
			{
				Dep[to] = Dep[x] + 1;
				Q.push( to );
			}
		}
	}
	memset(Cur, 0, sizeof Cur);
	return (Dep[t] != -1);
}
LL Dfs(LL x,LL Limit)
{
	if (x == t)
		return Limit;
	for (Int i = Cur[x]; i < G[x].size(); ++ i)
	{
		Cur[x] = i;
		LL to = G[x][i].v;
		if (Dep[to] == Dep[x] + 1 && G[x][i].w > 0)
		{
			LL Next = Dfs(to, Min(Limit, G[x][i].w));
			if ( Next )
			{
				G[x][i].w -= Next;
				G[to][G[x][i].Id].w += Next;
				return Next;
			}
			else Dep[to] = -1;
		}
	}
	return 0;
}
void Dinic()
{
	LL Flow;
	while ( Bfs() )
		while(Flow = Dfs(s, INF))
			MaxFlow += Flow;	
}
LL a[MAXN], V[MAXN], x[MAXN], y[MAXN], W[MAXN];
int main()
{
	LL n, m;
	read( n ); read( m );
	for (Int i = 1; i <= n; ++ i)
	{
		read( a[i] );
		read( V[i] );
	}
	LL Sum_1 = 0, Sum = 0;
	for (Int i = 1; i <= m; ++ i)
	{
		read( x[i] );
		read( y[i] );
		read( W[i] );
		if (x[i] == 1 || y[i] == 1)
			Sum_1 += W[i];
		Sum += W[i];
	}
	G[s].push_back(node(1, Min(Sum_1, a[1] - V[1]), 0));
	G[1].push_back(node(s, 0, 0));
	for (Int i = 2; i <= n; ++ i)
	{
		G[s].push_back(node(i, Min(a[i], Min(a[1], Sum_1 + V[1]) - 1) - V[i], 0));
		G[i].push_back(node(s, 0, i - 1));
	}
	for (Int i = 1; i <= m; ++ i)
	{
		LL Cuis = n + i;
		if (x[i] == y[i])
		{
			int InvCuis = G[x[i]].size();
			G[x[i]].push_back(node(Cuis, INF, 0));
			G[Cuis].push_back(node(x[i], 0, InvCuis));
			continue;
		}
		int InvCuis_x = G[x[i]].size(), InvCuis_y = G[y[i]].size();
		G[x[i]].push_back(node(Cuis, INF, 0));
		G[Cuis].push_back(node(x[i], 0, InvCuis_x));
		G[y[i]].push_back(node(Cuis, INF, 1));
		G[Cuis].push_back(node(y[i], 0, InvCuis_y));
	}
	t = n + m + 1;
	for (Int i = 1; i <= m; ++ i)
	{
		int Invx = i - 1, Invt = G[n + i].size();
		G[n + i].push_back(node(t, W[i], Invx));
		G[t].push_back(node(n + i, 0, Invt));
	}
	Dinic();
	// printf("%lld", MaxFlow);
	if (MaxFlow == Sum)
		printf("YES");
	else printf("NO");
	return 0;
}
posted on 2024-09-18 12:35  Thousanded  阅读(15)  评论(0编辑  收藏  举报