2018 ACM/ICPC 南京 I题 Magic Potion
题解:最大流板题;增加两个源点,一个汇点。第一个源点到第二个源点连边,权为K,然后第一个源点再连其他点(英雄点)边权各为1,然后英雄和怪物之间按照所给连边(边权为1)。
每个怪物连终点,边权为1;
参考代码:
1 #include<bits/stdc++.h> 2 using namespace std; 3 #define INF 0x3f3f3f3f 4 const int maxn = 2100; 5 int n,m,k,s,t,u,v,w,num,num1; 6 struct Edge { 7 int from, to, cap, flow; 8 }; 9 vector<Edge> edges; 10 vector<int> G[maxn]; 11 bool vis[maxn]; 12 int d[maxn], cur[maxn]; 13 void Init() 14 { 15 memset(d,0,sizeof d); 16 for(int i=0;i<=n+m+4;i++) G[i].clear(); 17 } 18 void addedge(int from, int to, int cap) 19 { 20 edges.push_back((Edge){from, to, cap, 0}); 21 edges.push_back((Edge){to, from, 0, 0}); 22 int m = edges.size(); 23 G[from].push_back(m-2); G[to].push_back(m-1); 24 } 25 bool bfs() 26 { 27 memset(vis,0,sizeof vis); 28 queue<int> q; 29 q.push(s); 30 d[s] = 0; vis[s] = 1; 31 while (!q.empty()) 32 { 33 int x = q.front(); q.pop(); 34 for(int i = 0; i < G[x].size(); ++i) 35 { 36 Edge &e = edges[G[x][i]]; 37 if (!vis[e.to] && e.cap > e.flow) 38 { 39 vis[e.to] = 1; 40 d[e.to] = d[x] + 1; 41 q.push(e.to); 42 } 43 } 44 } 45 return vis[t]; 46 } 47 48 int dfs(int x,int a) 49 { 50 if(x == t || a == 0) return a; 51 int flow = 0, f; 52 for(int &i = cur[x]; i < G[x].size(); ++i) 53 { 54 Edge &e = edges[G[x][i]]; 55 if (d[e.to] == d[x] + 1 && (f=dfs(e.to, min(a, e.cap-e.flow))) > 0) 56 { 57 e.flow += f; 58 edges[G[x][i]^1].flow -= f; 59 flow += f; a -= f; 60 if (a == 0) break; 61 } 62 } 63 return flow; 64 } 65 66 int Maxflow(int s, int t) 67 { 68 int flow = 0; 69 while (bfs()) 70 { 71 memset(cur,0,sizeof cur); 72 flow += dfs(s, INF); 73 } 74 return flow; 75 } 76 int main() 77 { 78 scanf("%d%d%d",&n,&m,&k); 79 Init();s=1;t=n+m+3;addedge(s,2,k); 80 for(int i=1;i<=n;++i) addedge(s,i+2,1),addedge(2,i+2,1); 81 for(int i=1;i<=n;++i) 82 { 83 scanf("%d",&num); 84 while(num--) 85 { 86 scanf("%d",&num1); 87 addedge(i+2,num1+n+2,1); 88 } 89 } 90 for(int i=1;i<=m;++i) addedge(i+n+2,t,1); 91 printf("%d\n",Maxflow(s,t)); 92 return 0; 93 }