题目描述
给定\(n\)个点\(m\)条边的有向图,删掉第\(i\)条边的代价为\(c[i]\)。
请删掉代价之和最少的边,使得从\(1\)号点出发到达不了\(n\)号点。
输入
第一行包含一个正整数\(T(1\leq T\leq 10)\),表示测试数据的组数。
每组数据第一行包含两个正整数\(n,m(1\leq n\leq 50,1\leq m\leq 1000)\)。
接下来\(m\)行,每行三个正整数\(a[i],b[i],c[i](1\leq a[i],b[i]\leq n,a[i]\neq b[i],1\leq c[i]\leq 10000)\),表示一条起点是\(a[i]\),终点是\(b[i]\)的边,删掉它的代价是\(c[i]\)。
输出
对于每组数据输出一行一个整数,即最小代价。
#include<bits/stdc++.h>
using namespace std;
typedef vector<string> VS;
const int N = 110,INF = 1e9;
struct Edge {
int from, to, cap, flow;
Edge(int u, int v, int c, int f) : from(u), to(v), cap(c), flow(f) {}
};
bool operator < (const Edge& a, const Edge& b) {
return a.from < b.from || (a.from == b.from && a.to < b.to);
}
struct ISAP {
int n, m, s, t;
vector<Edge> edges;
vector<int> G[N];
bool vis[N];
int d[N],cur[N],p[N],num[N];
void AddEdge(int from, int to, int cap) {
edges.push_back(Edge(from, to, cap, 0));
edges.push_back(Edge(to, from, 0, 0));
m = edges.size();
G[from].push_back(m - 2);
G[to].push_back(m - 1);
}
bool BFS() {
memset(vis, 0, sizeof(vis));
queue<int> Q;
Q.push(t);
vis[t] = 1;
d[t] = 0;
while (!Q.empty()) {
int x = Q.front();
Q.pop();
for (int i = 0; i < G[x].size(); i++) {
Edge& e = edges[G[x][i] ^ 1];
if (!vis[e.from] && e.cap > e.flow) {
vis[e.from] = 1;
d[e.from] = d[x] + 1;
Q.push(e.from);
}
}
}
return vis[s];
}
void init(int n) {
this->n = n;
for (int i = 0; i < n; i++) G[i].clear();
edges.clear();
}
int Augment() {
int x = t, a = INF;
while (x != s) {
Edge& e = edges[p[x]];
a = min(a, e.cap - e.flow);
x = edges[p[x]].from;
}
x = t;
while (x != s) {
edges[p[x]].flow += a;
edges[p[x] ^ 1].flow -= a;
x = edges[p[x]].from;
}
return a;
}
int Maxflow(int s, int t) {
this->s = s;
this->t = t;
int flow = 0;
BFS();
memset(num, 0, sizeof(num));
for (int i = 0; i < n; i++) num[d[i]]++;
int x = s;
memset(cur, 0, sizeof(cur));
while (d[s] < n) {
if (x == t) {
flow += Augment();
x = s;
}
int ok = 0;
for (int i = cur[x]; i < G[x].size(); i++) {
Edge& e = edges[G[x][i]];
if (e.cap > e.flow && d[x] == d[e.to] + 1) {
ok = 1;
p[e.to] = G[x][i];
cur[x] = i;
x = e.to;
break;
}
}
if (!ok) {
int m = n - 1;
for (int i = 0; i < G[x].size(); i++) {
Edge& e = edges[G[x][i]];
if (e.cap > e.flow) m = min(m, d[e.to]);
}
if (--num[d[x]] == 0) break;
num[d[x] = m + 1]++;
cur[x] = 0;
if (x != s) x = edges[p[x]].from;
}
}
return flow;
}
};
ISAP FG;
void solve()
{
int n,m;
cin>>n>>m;
//最小割的源点和汇点直接选用图里的点即可
int s = 1,t = n;
FG.init(n+1);
for(int i=0;i<m;++i)
{
int u,v,w;
cin>>u>>v>>w;
FG.AddEdge(u,v,w);
}
cout<<FG.Maxflow(s,t)<<'\n';
}
int main()
{
int T;
cin>>T;
while(T--)
{
solve();
}
}
标签:int,cap,flow,最小,edges,leq,Edge
From: https://www.cnblogs.com/ruoye123456/p/18370516