可恶的感冒终于好了。 调试了一下,发现在DFS中,原先走过的路径一直重复,没有办法优化,所以改用BFS算法找增广路径,顺利通过了。过两天学习一下压入重置算法。 #include <iostream> #include <fstream> #define SIZE 201 #define LARGER 0X7FFFFFFF #define min(a,b) (a)<(b)?(a):(b) using namespace std; 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("ditch.in"); ofstream fout("ditch.out"); int BFSDitch() { for (int i=0; i <pl; i ++) { int cur = path[i][0]; for (int j =1; j <=m; 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 == m) { 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[m][1]; map[e][s] += isuse[m][1]; e = s; pre = path[pre][1]; }//end while return isuse[m][1]; }//end if j==m }//end if } }//end for return -1; } int main() { //输入数据 fin >> n >> m; for (int i=0; i < n; i ++) { int row =0; int col = 0; int c = 0; fin >> row >> col >> c; map[row][col] += c; } isuse[1][0] = 1; isuse[1][1] = LARGER; path[pl][0] = 1; path[pl][1] = -1; pl ++; int temp = BFSDitch(); while (temp != -1) { result += temp; for (int i=2; i<=m; 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, 3172 KB] Test 2: TEST OK [0.011 secs, 3172 KB] Test 3: TEST OK [0.000 secs, 3172 KB] Test 4: TEST OK [0.000 secs, 3172 KB] Test 5: TEST OK [0.000 secs, 3172 KB] Test 6: TEST OK [0.011 secs, 3172 KB] Test 7: TEST OK [0.011 secs, 3172 KB] Test 8: TEST OK [0.000 secs, 3172 KB] Test 9: TEST OK [0.011 secs, 3172 KB] Test 10: TEST OK [0.000 secs, 3172 KB] Test 11: TEST OK [0.022 secs, 3172 KB] Test 12: TEST OK [0.011 secs, 3172 KB] All tests OK.