题目链接:https://vjudge.net/contest/299467#problem/J
这个题目是一个裸的最小割问题,就不多赘述了。
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <queue>
#include <vector>
#include <algorithm>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long ll;
const int maxn = 1e5 + 10;
const int INF = 0x3f3f3f3f;
struct edge
{
int u, v, c, f;
edge(int u, int v, int c, int f) :u(u), v(v), c(c), f(f) {}
};
vector<edge>e;
vector<int>G[maxn];
int level[maxn];//BFS分层,表示每个点的层数
int iter[maxn];//当前弧优化
int m;
void init(int n)
{
for (int i = 0; i <= n; i++)G[i].clear();
e.clear();
}
void add(int u, int v, int c)
{
e.push_back(edge(u, v, c, 0));
e.push_back(edge(v, u, c, 0));
m = e.size();
G[u].push_back(m - 2);
G[v].push_back(m - 1);
}
void BFS(int s)//预处理出level数组
//直接BFS到每个点
{
memset(level, -1, sizeof(level));
queue<int>q;
level[s] = 0;
q.push(s);
while (!q.empty())
{
int u = q.front();
q.pop();
for (int v = 0; v < G[u].size(); v++)
{
edge& now = e[G[u][v]];
if (now.c > now.f && level[now.v] < 0)
{
level[now.v] = level[u] + 1;
q.push(now.v);
}
}
}
}
ll dfs(int u, int t, int f)//DFS寻找增广路
{
if (u == t)return f;//已经到达源点,返回流量f
for (int &v = iter[u]; v < G[u].size(); v++)
//这里用iter数组表示每个点目前的弧,这是为了防止在一次寻找增广路的时候,对一些边多次遍历
//在每次找增广路的时候,数组要清空
{
edge &now = e[G[u][v]];
if (now.c - now.f > 0 && level[u] < level[now.v])
//now.c - now.f > 0表示这条路还未满
//level[u] < level[now.v]表示这条路是最短路,一定到达下一层,这就是Dinic算法的思想
{
ll d = dfs(now.v, t, min(f, now.c - now.f));
if (d > 0)
{
now.f += d;//正向边流量加d
e[G[u][v] ^ 1].f -= d;
//反向边减d,此处在存储边的时候两条反向边可以通过^操作直接找到
return d;
}
}
}
return 0;
}
ll Maxflow(int s, int t)
{
ll flow = 0;
for (;;)
{
BFS(s);
if (level[t] < 0)return flow;//残余网络中到达不了t,增广路不存在
memset(iter, 0, sizeof(iter));//清空当前弧数组
int f;//记录增广路的可增加的流量
while ((f = dfs(s, t, INF)) > 0)
{
flow += f;
}
}
return flow;
}
vector<pair<int, int>>vec;
void solve(int u)
{
printf("u=%d
", u);
for(int i=0;i<G[u].size();i++)
{
edge now = e[G[u][i]];
edge non = e[G[u][i] ^ 1];
if(now.c==now.f)
{
printf("now.u=%d now.v=%d
", now.u, now.v);
vec.push_back(make_pair(now.u, now.v));
solve(now.v);
}
}
}
int cx[maxn], cy[maxn];
int main()
{
int n, m;
while (scanf("%d%d",&n,&m)!=EOF&&(m+n))
{
init(n);
int s = 1, t = 2;
for(int i=1;i<=m;i++)
{
int x, y, z;
scanf("%d%d%d", &x, &y, &z);
add(x, y, z);
cx[i] = x;
cy[i] = y;
}
ll ans = Maxflow(s, t);
for(int i=1;i<=m;i++)
{
if((level[cx[i]]!=-1&&level[cy[i]]==-1)||(level[cx[i]]==-1&&level[cy[i]]!=-1))
{
printf("%d %d
", cx[i], cy[i]);
}
}
printf("
");
}
return 0;
}