关闭

poj 1149 PIGS 最大流

标签: 算法
376人阅读 评论(0) 收藏 举报
分类:
#include "stdio.h"   //poj 1149 最大流
#include "string.h"
#include "queue"
using namespace std;

#define N 2250
#define INF 0x3fffffff

struct node
{
	int u,v,w;
	int next;
}edge[8*N];

int n,idx;
int start,end;
int route[N],maxf[N],head[N],last[N];

int EK();
int BFS();
void init();
void adde(int u,int v,int w);
void addedge(int u,int v,int w);
int MIN(int x,int y){ return x<y?x:y;}

int main()
{
	int m,k;
	int i,j;
	int u,v,w,Case;

	while(scanf("%d %d",&m,&k)!=-1)
	{
		init();
		start = 0;  //超级源点
		end = m+k+1;  //超级汇点
		for(n=1;n<=m;n++)
		{
			scanf("%d",&w);
			adde(start,n,w);
			last[n] = n;
		}
		n=m;
		for(i=1;i<=k;i++)
		{
			n++;
			scanf("%d",&Case);
			while(Case--)
			{
				scanf("%d",&v);
				adde(last[v],n,INF);
				last[v] = n;
			}
			scanf("%d",&w);
			adde(n,end,w);
		}
		int ans = EK();
		printf("%d\n",ans);
	}
	return 0;
}

void init()
{
	idx = 0;
	memset(head,-1,sizeof(head));
}

void adde(int u,int v,int w)
{
	addedge(u,v,w);
	addedge(v,u,0);
}

void addedge(int u,int v,int w)
{
	edge[idx].u = u;
	edge[idx].v = v;
	edge[idx].w = w;
	edge[idx].next = head[u];
	head[u] = idx;
	idx++;
}

int EK()
{
	int ans=0,kejia;
	int x,y;
	while(kejia = BFS())
	{
		ans += kejia;
		y = route[end];
		while(y!=-1)
		{
			x = y^1;
			edge[y].w -= kejia;
			edge[x].w += kejia;
			y = route[edge[y].u];
		}
	}
	return ans;
}

int BFS()
{
	int i;
	int x,y;
	memset(route,-1,sizeof(route));
	for(i=0;i<N;i++)	maxf[i] = INF;
	route[0] = 0;
	queue<int> q;
	q.push(start);
	while(!q.empty())
	{
		x = q.front();
		q.pop();
		for(i=head[x];i!=-1;i=edge[i].next)
		{
			y = edge[i].v;
			if(route[y]==-1 && edge[i].w>0)
			{
				maxf[y] = MIN(maxf[x],edge[i].w);
				route[y] = i;
				q.push(y);
			}
		}
	}
	route[0] = -1;
	if(route[end]==-1) return 0;
	return maxf[end];
}


//http://www.cnblogs.com/rainydays/archive/2011/08/27/2155710.html

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:32311次
    • 积分:821
    • 等级:
    • 排名:千里之外
    • 原创:50篇
    • 转载:20篇
    • 译文:0篇
    • 评论:0条