题意为给定一个有向图,删掉一条边的代价为边权,要求以尽可能少的总代价删掉一些 边,使得最短路增加。 先求出最短路,然后保留所有满足 dey −dex = ew 的边,对于新的图求 1 到 n 的最小 割即为答案。
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<cstdlib>
#include<cmath>
#include<stack>
#include<map>
#include<string>
#include<vector>
#include<set>
#include<bitset>
#include<algorithm>
using namespace std;
#define ll long long
#define INF 0x3f3f3f3f
#define LINF 0x3f3f3f3f3f3f3f3f
#define ull unsigned long long
#define endl '\n'
#define clr_0(a) memset(a, 0, sizeof(a))
#define clr_INF(a) memset(a, INF, sizeof(a))
#define lowbit(x) x & -x
#define lson rt << 1, l, mid
#define rson rt << 1 | 1, mid + 1, r
#define PB push_back
#define POP pop_back
const double pi = acos(-1);
const int maxn = 10001;
const int maxm = 10001;
const ll mod = 998244353;
const int hash_mod = 19260817;
int n, m, s, t, cnt, maxflow;
int head[maxn], dep[maxn], cur[maxn], inq[maxn];
struct ed{
int to, next, quan;
}edge[maxm << 1];
int book[maxn], u[maxn], v[maxn], w[maxn];
ll dis[maxn];
struct node{
int v, w;
};
vector<node> g[maxn];
struct nod{
int u; ll d;
bool operator< (const nod& xgd) const{
return d > xgd.d;
}
};
struct dyf{
void add(int u, int v, ll w){
edge[cnt].to = v;
edge[cnt].quan = w;
edge[cnt].next = head[u];
head[u] = cnt ++;
}
bool bfs(){
//puts("4574");
for(int i = 1 ; i <= n ; ++ i) cur[i] = head[i], dep[i] = INF, inq[i] = 0;
queue<int> que;
que.push(s);
inq[s] = 1;
dep[s] = 0;
while(!que.empty()){
int u = que.front();
que.pop();
inq[u] = 0;
for(int i = head[u] ; ~ i ; i = edge[i].next){
int v = edge[i].to;
if(edge[i].quan && dep[v] > dep[u] + 1){
dep[v] = dep[u] + 1;
if(!inq[v]){
inq[v] = 1;
que.push(v);
}
}
}
}
return dep[t] == INF ? 0 : 1;
}
int dfs(int u, int flow){
int rlow = 0;
if(u == t){
maxflow += flow;
return flow;
}
int used = 0;
for(int i = cur[u] ; ~ i ; i = edge[i].next){
cur[u] = i;
int v = edge[i].to;
if(edge[i].quan && dep[v] == dep[u] + 1){
if(rlow = dfs(v, min(flow - used, edge[i].quan))){
used += rlow;
edge[i].quan -= rlow;
edge[i^1].quan += rlow;
if(used == flow) break;
}
}
}
return used;
}
void dinic(){
while(bfs()){
dfs(s, INF);
}
}
void Dijkstra(int s){
dis[s] = 0;
priority_queue<nod> que;
que.push(nod{s, 0});
while(!que.empty()){
nod cur = que.top();
que.pop();
int u = cur.u;
if(book[u]) continue;
book[u] = 1;
for(int i = 0 ; i < g[u].size() ; ++ i){
int v = g[u][i].v;
if(dis[v] >= dis[u] + g[u][i].w){
dis[v] = dis[u] + g[u][i].w;
que.push(nod{v, dis[v]});
}
}
}
for(int i = 1 ; i <= m ; ++ i)
if(dis[u[i]] + w[i] == dis[v[i]])
add(u[i], v[i], w[i]), add(v[i], u[i], 0);
}
void init(){
scanf("%d %d", &n, &m);
s = 1, t = n; maxflow = 0; cnt = 0;
for(int i = 1 ; i <= n ; ++ i) g[i].clear(), book[i] = 0, dis[i] = LINF, head[i] = -1;
for(int i = 1 ; i <= m ; ++ i){
scanf("%d %d %d", &u[i], &v[i], &w[i]);
g[u[i]].PB(node{v[i], w[i]});
}
}
}solve;
int main()
{
int T;
scanf("%d", &T);
while(T--){
solve.init();
solve.Dijkstra(1);
solve.dinic();
cout << maxflow << endl;
}
return 0;
}