USACO算法系列三十一——stall4(续)

       早上实现了第一个想法,使用DFS遍历搜索的算法。在TEST6的时候就挂掉了。

       第二个想法是采用最大流算法。在n和m之间多加了两个节点,作为起点和汇点。如下图所示:

USACO算法系列三十一——stall4(续)_第1张图片

      然后使用最大流算法就可以了。

#include <iostream> #include <fstream> #define SIZE 402 #define LARGER 0X7FFFFFFF using namespace std; //n:奶牛数量 m: 牛棚数量 int n, m; int map[SIZE][SIZE] = {0}; int path[SIZE][2] = {0}; int pl =0; int result = 0; int isuse[SIZE][2]; ifstream fin("stall4.in"); ofstream fout("stall4.out"); int BFSDitch() { for (int i=0; i <pl; i ++) { int cur = path[i][0]; for (int j = 0; j <= n+m+1; j ++) { if (map[cur][j] > 0) { if (isuse[j][0] == 0) { path[pl][0] = j; path[pl][1] = i; pl ++; isuse[j][0] =1; isuse[j][1] = min(isuse[cur][1], map[cur][j]); }//end if j if (j == n+m+1) { int pre = path[pl-1][1]; int s = 0; int e = path[pl-1][0]; while (pre != -1) { s = path[pre][0]; map[s][e] -= isuse[n+m+1][1]; map[e][s] += isuse[n+m+1][1]; e = s; pre = path[pre][1]; }//end while return isuse[n+m+1][1]; }//end if j==m }//end if } }//end for return -1; } int main() { //输入数据 fin >> n >> m; for (int i=1; i <= n; i ++) { int temp =0; fin >> temp; for (int j = 1; j <= temp; j ++) { int index = 0; fin >> index; map[i][n+index] = 1; }//end for j }//end for i //初始化 for (int i = 1; i <= n; i ++) { map[0][i] = 1; } for (int j=1; j <= m; j ++) { map[n+j][n+m+1] = 1; } isuse[0][0] = 1; isuse[0][1] = LARGER; path[pl][0] = 0; path[pl][1] = -1; pl ++; int temp = BFSDitch(); while (temp != -1) { result += temp; for (int i=1; i<=n+m+1; i ++) { isuse[i][0] = 0; isuse[i][1] = LARGER; }//end for pl = 1; temp = BFSDitch(); }//end while fout << result << endl; return 0; }

     结果如下:

Executing... Test 1: TEST OK [0.000 secs, 3648 KB] Test 2: TEST OK [0.000 secs, 3648 KB] Test 3: TEST OK [0.000 secs, 3648 KB] Test 4: TEST OK [0.000 secs, 3648 KB] Test 5: TEST OK [0.000 secs, 3648 KB] Test 6: TEST OK [0.000 secs, 3648 KB] Test 7: TEST OK [0.022 secs, 3648 KB] Test 8: TEST OK [0.054 secs, 3648 KB] Test 9: TEST OK [0.032 secs, 3648 KB] All tests OK.

     看了参考答案以后,发现有一种最大流算法的简化方法,匈牙利算法。参考资料:

     http://www.byvoid.com/blog/hungary/zh-hans/

     http://baike.baidu.com/view/501092.htm

     有空实现一下。

你可能感兴趣的:(USACO算法系列三十一——stall4(续))