hdu 3549 Flow Problem (Dinic)

时间:2023-11-28 11:48:56
Flow Problem
Time Limit: 5000/5000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others)
Total Submission(s): 21438    Accepted Submission(s): 10081
Problem Description
Network flow is a well-known difficult problem for ACMers. Given a graph, your task is to find out the maximum flow for the weighted directed graph.
 
Input
The first line of input contains an integer T, denoting the number of test cases.
For each test case, the first line contains two integers N and M, denoting the number of vertexes and edges in the graph. (2 <= N <= 15, 0 <= M <= 1000)
Next M lines, each line contains three integers X, Y and C, there is an edge from X to Y and the capacity of it is C. (1 <= X, Y <= N, 1 <= C <= 1000)
 
Output
For each test cases, you should output the maximum flow from source 1 to sink N.
 
Sample Input
2
3 2
1 2 1
2 3 1
3 3
1 2 1
2 3 1
1 3 1
 
Sample Output
Case 1: 1
Case 2: 2

C/C++:

 #include <map>
#include <queue>
#include <cmath>
#include <vector>
#include <string>
#include <cstdio>
#include <cstring>
#include <climits>
#include <iostream>
#include <algorithm>
#define INF 0x3f3f3f3f
using namespace std;
const int my_max = ; int N, M, my_map[my_max][my_max], my_source, my_sink
, my_dis[my_max]; int my_dfs(int my_step, int my_ans)
{
if (my_step == my_sink) return my_ans; int my_temp = my_ans;
for (int i = ; i <= N && my_ans; ++ i)
{
if (my_dis[my_step] == my_dis[i] + && my_map[my_step][i])
{
int t = my_dfs(i, min(my_ans, my_map[my_step][i]));
my_map[my_step][i] -= t;
my_map[i][my_step] += t;
my_ans -= t;
}
}
return my_temp - my_ans;
} bool my_bfs()
{
memset(my_dis, -, sizeof(my_dis));
queue <int> Q;
my_dis[my_sink] = ;
Q.push(my_sink);
while (!Q.empty())
{
int now = Q.front();
for (int i = ; i <= N; ++ i)
{
if (my_map[i][now] > && my_dis[i] == -)
{
my_dis[i] = my_dis[now] + ;
Q.push(i);
}
}
if (now == my_source) return true;
Q.pop();
}
return false;
} int my_dinic()
{
int my_ans = ;
while (my_bfs())
my_ans += my_dfs(my_source, INF); return my_ans;
} int main()
{
int t;
scanf("%d", &t);
for (int i = ; i <= t; ++ i)
{
memset(my_map, , sizeof(my_map));
scanf("%d%d", &N, &M);
my_source = , my_sink = N; while (M --)
{
int x, y, x_y;
scanf("%d%d%d", &x, &y, &x_y);
my_map[x][y] += x_y;
}
printf("Case %d: %d\n", i, my_dinic());
}
return ;
}