POJ 1149 PIGS | 最大流问题

参考了这个PDF

第一道网络流啊!感动

 1 #include<cstdio>
 2 #include<algorithm>
 3 #include<cstring>
 4 #include<vector>
 5 #include<queue>
 6 #define INF 100000000
 7 #define N 500
 8 #define M 1100
 9 using namespace std;
10 struct adj
11 {
12     int u,v,w;
13 }e[M*M];
14 int head[N],n,m,S,T,a[M],k,ecnt=1,x,flw[N],tmp,lev[N],ans,last[M];
15 vector <int> buy[M];
16 queue <int> q;
17 void add(int u,int v,int w)
18 {
19     e[++ecnt].v=v;
20     e[ecnt].w=w;
21     e[ecnt].u=head[u];
22     head[u]=ecnt;
23 }
24 int bfs()
25 {
26     memset(lev,-1,sizeof(lev));
27     lev[S]=0;
28     q.push(S);
29     while (!q.empty())
30     {
31         int x=q.front();
32         for (int i=head[x];i;i=e[i].u)
33         {
34              int v=e[i].v;
35              if (lev[v]==-1 && e[i].w>0)
36          lev[v]=lev[x]+1,q.push(v);
37         }
38         q.pop();
39     }
40     return lev[T]!=-1;
41 }
42 int dfs(int x,int flw)
43 {
44     if (x==T) return flw;
45     for (int i=head[x];i;i=e[i].u)
46     {
47     int v=e[i].v,tmp;
48         if (lev[v]==lev[x]+1 && e[i].w>0 && (tmp=dfs(v,min(flw,e[i].w)))>0)
49         {
50             e[i].w-=tmp;
51             e[i^1].w+=tmp;
52             return tmp;
53         }
54     }
55     return 0;
56 }
57 int main()
58 {
59     scanf("%d%d",&m,&n);
60     S=n+1,T=n+2;
61     for (int i=1;i<=m;i++)
62     scanf("%d",&a[i]);
63     for (int i=1;i<=n;i++)
64     {
65     scanf("%d",&k);
66     for (int j=1;j<=k;j++)
67     {
68         scanf("%d",&x);
69         buy[i].push_back(x);
70     }
71     scanf("%d",&x);
72     add(i,T,x),add(T,i,0);
73     }
74     for (int i=1;i<=n;i++)
75     for (int j=0;j<buy[i].size();j++)
76     {
77         int v=buy[i][j];
78         if (!last[v])
79         last[v]=i,add(S,i,a[v]),add(i,S,0);
80         else
81         add(last[v],i,INF),add(i,last[v],0),last[v]=i;
82     }
83     while (bfs())
84     while ((tmp=dfs(S,INF))>0) ans+=tmp;
85     printf("%d",ans);
86     return 0;
87 }

 

posted @ 2017-11-30 16:55  MSPqwq  阅读(114)  评论(0编辑  收藏  举报