A Za, A Za, Fighting...

坚信:勤能补拙

PKU 1273 Drainage Ditches

问题:
http://acm.pku.edu.cn/JudgeOnline/problem?id=1273

思路:
第一道最大流,Edmonds-Karp算法
参考了别人的代码,其实自己也能写出来,不过肯定没有这么精致(*^__^*) 嘻嘻……
从别人的代码里学到很多,例如:
一条路径只需要pre[]数组进行保存即可,路径的残留容量也可以边扩展(BFS)边记录,还有代码居然就只需要一个残留网络的二维数组

代码:
 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<string.h>
 4 #define MAX_M 201
 5 #define INF 0x7FFFFFFF
 6 #define Min(a,b) ((a)<(b) ? (a) : (b))
 7 int n, m, source, sink;
 8 int pre[MAX_M]; /* excellent for path recording */
 9 int flow[MAX_M];
10 int residual[MAX_M][MAX_M]; /* only need this matrix */
11 int queue[MAX_M];
12 
13 int
14 bfs() /* operation on the residual network */
15 {
16     int i, head, tail, cur;
17     head = -1;
18     tail = 0;
19     memset(pre, -1sizeof(pre));
20     for(i=1; i<=m; i++)
21         flow[i] = INF;
22     queue[tail] = source;
23     pre[source] = 0;
24     while(head < tail) {
25         ++head;
26         cur = queue[head];
27         if(cur == sink)
28             return flow[sink];
29         for(i=1; i<=m; i++) {
30             if(pre[i]!=-1 || !residual[cur][i])
31                 continue;
32             pre[i] = cur;
33             flow[i] = Min(flow[cur], residual[cur][i]);
34             ++tail;
35             queue[tail] = i;
36         }
37     }
38     return -1;
39 }
40 
41 int
42 edmonds_karp()
43 {
44     int tmp, next, cur, rt = 0;
45     while(1) {
46         tmp = bfs();
47         if(tmp == -1/* there's no argment path */
48             return rt;
49         rt += tmp;
50         cur = sink;
51         while(cur != source) {
52             next = cur;
53             cur = pre[cur];
54             residual[cur][next] -= tmp;
55             residual[next][cur] += tmp;
56         }
57     }
58 }
59 
60 int
61 main(int argc, char **argv)
62 {
63     int i, f, t, c, ans;
64     while(scanf("%d %d"&n, &m) != EOF) {
65         memset(residual, 0sizeof(residual));
66         for(i=1; i<=n; i++) {
67             scanf("%d %d %d"&f, &t, &c);
68             residual[f][t] += c; /* Attention: multiple lines */
69         }
70         source = 1;
71         sink = m;
72         ans = edmonds_karp();
73         printf("%d\n", ans);
74     }
75 }

posted on 2010-09-16 21:10 simplyzhao 阅读(173) 评论(0)  编辑 收藏 引用 所属分类: F_图算法


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

<2010年9月>
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789

统计

常用链接

留言簿(1)

随笔分类

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜