LuoguP2763 试题库问题(最大流)
建图同_____
代码:
1 #include<queue> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 const int oo=0x3f3f3f3f; 6 struct pnt{ 7 int hd; 8 int lyr; 9 int now; 10 }p[10000]; 11 struct ent{ 12 int twd; 13 int lst; 14 int vls; 15 }e[100000]; 16 int k,n; 17 int s,t; 18 int cnt; 19 int sum; 20 std::queue<int>Q; 21 void ade(int f,int t,int v) 22 { 23 cnt++; 24 e[cnt].twd=t; 25 e[cnt].vls=v; 26 e[cnt].lst=p[f].hd; 27 p[f].hd=cnt; 28 return ; 29 } 30 bool Bfs(void) 31 { 32 while(!Q.empty()) 33 Q.pop(); 34 for(int i=1;i<=t;i++) 35 p[i].lyr=0; 36 p[s].lyr=1; 37 Q.push(s); 38 while(!Q.empty()) 39 { 40 int x=Q.front(); 41 Q.pop(); 42 for(int i=p[x].hd;i;i=e[i].lst) 43 { 44 int to=e[i].twd; 45 if(p[to].lyr==0&&e[i].vls>0) 46 { 47 p[to].lyr=p[x].lyr+1; 48 if(to==t) 49 return true; 50 Q.push(to); 51 } 52 } 53 } 54 return false; 55 } 56 int Dfs(int x,int fll) 57 { 58 if(x==t) 59 return fll; 60 for(int& i=p[x].now;i;i=e[i].lst) 61 { 62 int to=e[i].twd; 63 if(p[to].lyr==p[x].lyr+1&&e[i].vls>0) 64 { 65 int ans=Dfs(to,std::min(fll,e[i].vls)); 66 if(ans>0) 67 { 68 e[i].vls-=ans; 69 e[((i-1)^1)+1].vls+=ans; 70 return ans; 71 } 72 } 73 } 74 return 0; 75 } 76 int Dinic(void) 77 { 78 int ans=0; 79 while(Bfs()) 80 { 81 int dlt; 82 for(int i=1;i<=t;i++) 83 p[i].now=p[i].hd; 84 while(dlt=Dfs(s,oo)) 85 ans+=dlt; 86 } 87 return ans; 88 } 89 int main() 90 { 91 //freopen("a.in","r",stdin); 92 scanf("%d%d",&k,&n); 93 s=k+n+1; 94 t=s+1; 95 for(int i=1;i<=k;i++) 96 { 97 int v; 98 scanf("%d",&v); 99 sum+=v; 100 ade(i,t,v); 101 ade(t,i,0); 102 } 103 for(int i=1;i<=n;i++) 104 { 105 int p; 106 scanf("%d",&p); 107 ade(s,i+k,1); 108 ade(i+k,s,0); 109 for(int j=1;j<=p;j++) 110 { 111 int tp; 112 scanf("%d",&tp); 113 ade(i+k,tp,1); 114 ade(tp,i+k,0); 115 } 116 } 117 int tot=Dinic(); 118 if(tot!=sum) 119 { 120 printf("No Solution!\n"); 121 return 0; 122 } 123 for(int i=1;i<=k;i++) 124 { 125 printf("%d:",i); 126 for(int j=p[i].hd;j;j=e[j].lst) 127 { 128 int to=e[j].twd; 129 if(to!=t&&e[j].vls>0) 130 printf(" %d",to-k); 131 } 132 puts(""); 133 } 134 return 0; 135 }