题意:给你n个点 m条边 现在你能够堵住一些路 问怎样能让花费最少且让1~n走的路比最短路的长度要长
思路:先跑一边最短路 建一个最短路图 然后我们跑一边最大流求一下最小割即可
#include <bits/stdc++.h> using namespace std; const double pi = acos(-1.0); const int maxn = 1e4+7; const int inf = 0x3f3f3f3f; const double eps = 1e-6; typedef long long ll; const ll mod = 1e9+7; struct edge{ int next,to; ll w; }; edge e[maxn<<1]; int head[maxn],cnt; int vis[maxn]; ll d[maxn]; void init(){ cnt=0; memset(head,0,sizeof(head)); memset(vis,0,sizeof(vis)); memset(d,inf,sizeof(d)); } void add(int u, int v, int w){ e[++cnt]={head[u],v,w}; head[u] = cnt; } void dij(int s){ priority_queue<pair<ll,int> > q; d[s]=0; q.push(make_pair(0,s)); while(!q.empty()){ int u=q.top().second; q.pop(); if(vis[u]) continue; vis[u]=1; for(int i=head[u];i;i=e[i].next){ int v=e[i].to; int w=e[i].w; if(d[v]>d[u]+w){ d[v]=d[u]+w; q.push(make_pair(-d[v],v)); } } } } struct Edge { ll from, to, cap, flow; Edge(int u, int v, int c, int f) : from(u), to(v), cap(c), flow(f) {} }; struct Dinic { int n, m, s, t; vector<Edge> edges; vector<int> G[maxn]; int d[maxn], cur[maxn]; bool vis[maxn]; void init(int n) { for (int i = 0; i < n; i++) G[i].clear(); edges.clear(); } 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(s); d[s] = 0; vis[s] = 1; while (!Q.empty()) { int x = Q.front(); Q.pop(); for (int i = 0; i < G[x].size(); i++) { Edge& e = edges[G[x][i]]; if (!vis[e.to] && e.cap > e.flow) { vis[e.to] = 1; d[e.to] = d[x] + 1; Q.push(e.to); } } } return vis[t]; } ll DFS(int x, ll a) { if (x == t || a == 0) return a; ll flow = 0, f; for (int& i = cur[x]; i < G[x].size(); i++) { Edge& e = edges[G[x][i]]; if (d[x] + 1 == d[e.to] && (f = DFS(e.to, min(a, e.cap - e.flow))) > 0) { e.flow += f; edges[G[x][i] ^ 1].flow -= f; flow += f; a -= f; if (a == 0) break; } } return flow; } ll Maxflow(int s, int t) { this->s = s; this->t = t; ll flow = 0; while (BFS()) { memset(cur, 0, sizeof(cur)); flow += DFS(s, inf); } return flow; } } dinic; int bian[maxn][3]; int main(){ int t; scanf("%d",&t); while(t--){ init(); int n,m; scanf("%d%d",&n,&m); for(int i=1;i<=m;i++){ int x,y,c; scanf("%d%d%d",&x,&y,&c); bian[i][0]=x; bian[i][1]=y; bian[i][2]=c; add(x,y,c); } dij(1); dinic.init(n); for(int i=1;i<=m;i++){ if(d[bian[i][1]]==d[bian[i][0]]+bian[i][2]){ dinic.AddEdge(bian[i][0],bian[i][1],bian[i][2]); } } printf("%lld ",dinic.Maxflow(1,n)); } }