还是不是很懂算法
先存一个模板先吧~~~
看的这篇学的--
http://www.renfei.org/blog/isap.html
1 #include<cstdio> 2 #include<cstring> 3 #include<iostream> 4 #include<algorithm> 5 #include<vector> 6 #include<queue> 7 using namespace std; 8 9 const int maxn = 1005; 10 const int INF = (1 << 30) - 1; 11 12 struct Edge{ 13 int from,to,cap,flow; 14 }; 15 16 vector<Edge> edges; 17 18 int source; // 源点 19 int sink; // 汇点 20 int p[maxn]; // 可增广路上的上一条弧的编号 21 int num[maxn]; // 和 t 的最短距离等于 i 的节点数量 22 int cur[maxn]; // 当前弧下标 23 int d[maxn]; // 残量网络中节点 i 到汇点 t 的最短距离 24 bool visited[maxn]; 25 26 int num_nodes; 27 28 vector<int> G[maxn]; 29 30 // 预处理, 反向 BFS 构造 d 数组 31 bool bfs() 32 { 33 memset(visited, 0, sizeof(visited)); 34 queue<int> Q; 35 Q.push(sink); 36 visited[sink] = 1; 37 d[sink] = 0; 38 while (!Q.empty()) { 39 int u = Q.front(); 40 Q.pop(); 41 for ( int i = 0;i < G[u].size();i++) { 42 Edge &e = edges[G[u][i]^1]; 43 if (!visited[e.from] && e.cap> e.flow) { 44 visited[e.from] = true; 45 d[e.from] = d[u] + 1; 46 Q.push(e.from); 47 } 48 } 49 } 50 return visited[source]; 51 } 52 53 // 增广 54 int augment() 55 { 56 int u = sink, df = INF; 57 // 从汇点到源点通过 p 追踪增广路径, df 为一路上最小的残量 58 while (u != source) { 59 Edge &e = edges[p[u]]; 60 df = min(df, e.cap - e.flow); 61 u = edges[p[u]].from; 62 } 63 u = sink; 64 // 从汇点到源点更新流量 65 while (u != source) { 66 edges[p[u]].flow += df; 67 edges[p[u]^1].flow -= df; 68 u = edges[p[u]].from; 69 } 70 return df; 71 } 72 73 int max_flow() 74 { 75 int flow = 0; 76 bfs(); 77 memset(num, 0, sizeof(num)); 78 for (int i = 0; i < num_nodes; i++) num[d[i]]++; 79 int u = source; 80 memset(cur, 0, sizeof(cur)); 81 while (d[source] < num_nodes) { 82 if (u == sink) { 83 flow += augment(); 84 u = source; 85 } 86 bool advanced = false; 87 for (int i = cur[u]; i < G[u].size(); i++) { 88 Edge& e = edges[G[u][i]]; 89 if (e.cap > e.flow && d[u] == d[e.to] + 1) { 90 advanced = true; 91 p[e.to] = G[u][i]; 92 cur[u] = i; 93 u = e.to; 94 break; 95 } 96 } 97 if (!advanced) { // retreat 98 int m = num_nodes - 1; 99 for ( int i = 0;i < G[u].size();i++) 100 if (edges[G[u][i]].cap > edges[G[u][i]].flow) 101 m = min(m, d[edges[G[u][i]].to]); 102 if (--num[d[u]] == 0) break; // gap 优化 103 num[d[u] = m+1]++; 104 cur[u] = 0; 105 if (u != source) 106 u = edges[p[u]].from; 107 } 108 } 109 return flow; 110 } 111 112 void addedges(int from,int to,int cap){ 113 edges.push_back((Edge){from,to,cap,0}); 114 edges.push_back((Edge){to,from,0,0}); 115 int m = edges.size(); 116 G[from].push_back(m-2); 117 G[to].push_back(m-1); 118 } 119 120 void init(){ 121 edges.clear(); 122 for(int i = 0;i < num_nodes;i++) G[i].clear(); 123 } 124 125 int main(){ 126 int m; 127 while(scanf("%d %d ",&m,&num_nodes) != EOF){ 128 init(); 129 source = 0; sink = num_nodes-1; 130 for(int i = 0;i < m;i++){ 131 int u,v,c; 132 scanf("%d %d %d",&u,&v,&c);u--;v--; 133 addedges(u,v,c); 134 } 135 int res = max_flow(); 136 printf("%d\n",res); 137 } 138 return 0; 139 }
时间: 2024-11-10 19:31:27