标签:
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 19575 | Accepted: 8948 |
Description
Input
Output
Sample Input
3 3
3 1 10
2 1 2 2
2 1 3 3
1 2 6
Sample Output
7
Source
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <queue>
#include <map>
#include <algorithm>
#include <set>
using namespace std;
#define MM(a,b) memset(a,b,sizeof(a))
typedef long long ll;
typedef unsigned long long ULL;
const int mod = 1000000007;
const double eps = 1e-10;
const int inf = 0x3f3f3f3f;
const int big=50000;
int max(int a,int b) {return a>b?a:b;};
int min(int a,int b) {return a<b?a:b;};
struct edge{
int to,cap,rev;
};
vector<edge> G[105];
vector<int> topig[1005];
int n,m,want[105],pignum[1005],cap[105],level[105],iter[105];
void add_edge(int u,int v,int cap)
{
G[u].push_back(edge{v,cap,G[v].size()});
G[v].push_back(edge{u,0,G[u].size()-1});
}
void bfs(int s)
{
queue<int> q;
q.push(s);
level[s]=1;
while(q.size())
{
int now=q.front();q.pop();
for(int i=0;i<G[now].size();i++)
if(G[now][i].cap>0)
{
edge e=G[now][i];
if(level[e.to]<0)
{
level[e.to]=level[now]+1;
q.push(e.to);
}
}
}
}
int dfs(int s,int t,int minn)
{
if(s==t)
return minn;
for(int &i=iter[s];i<G[s].size();i++)
{
edge &e=G[s][i];
if(level[e.to]>level[s]&&e.cap>0)
{
int k=dfs(e.to,t,min(minn,e.cap));
if(k>0)
{
e.cap-=k;
G[e.to][e.rev].cap+=k;
return k;
}
}
}
return 0;
}
int max_flow(int s,int t)
{
int ans=0,temp;
for(;;)
{
memset(level,-1,sizeof(level));
bfs(s);
if(level[t]<0)
return ans;
memset(iter,0,sizeof(iter));
while((temp=dfs(s,t,inf))>0)
ans+=temp;
}
return ans;
}
void buildgraph()
{
for(int i=1;i<=m;i++)
if(topig[i].size())
{
int man=topig[i][0];
cap[man]+=pignum[i];
for(int j=1;j<topig[i].size();j++)
add_edge(topig[i][j-1],topig[i][j],inf);
}
for(int i=1;i<=n;i++)
{
add_edge(0,i,cap[i]);
add_edge(i,n+1,want[i]);
}
}
void init()
{
MM(cap,0);
for(int i=0;i<n+1;i++) G[i].clear();
for(int i=1;i<=m;i++) topig[i].clear();
}
int main()
{
while(~scanf("%d %d",&m,&n))
{
init();
for(int i=1;i<=m;i++)
scanf("%d",&pignum[i]);
for(int i=1;i<=n;i++)
{
int num,pig;
scanf("%d",&num);
for(int j=1;j<=num;j++)
{
scanf("%d",&pig);
topig[pig].push_back(i);
}
scanf("%d",&want[i]);
}
buildgraph();
printf("%d\n",max_flow(0,n+1));
}
return 0;
}
POJ 1149 猪圈买猪 建图太强大!! 没有透彻领悟 慢慢消化
标签:
原文地址:http://www.cnblogs.com/smilesundream/p/5507055.html