题意:n点m条边的图,每条边长度都为1,堵住第i条边需要代价w[i],敌人每次从n走到1都走最短路.
n为源点,1为汇点,把n-1最短路上的边加到网络流的图中,容量为堵住这条边的代价,则求s-t的最小割 等价于求最大流
d[u]<=d[v]+w 若d[v]+w==d[u] 则说明边(v,u)在s出发到某点最短路上,
n为源点,1为汇点,把n-1最短路上的边加到网络流的图中,容量为堵住这条边的代价,则求s-t的最小割 等价于求最大流
d[u]<=d[v]+w 若d[v]+w==d[u] 则说明边(v,u)在s出发到某点最短路上,
有些不在s-t最短路上的边可能也会被加入(但不影响,因为沿着该边最后一定无法到t)
#include <bits/stdc++.h>
using namespace std;
const int N=2e3+20,inf=0x3f3f3f3f;
struct node
{
int v,w;
node(int vv,int ww):v(vv),w(ww){};
};
vector<node>e[N];
int s,t,n,m,vs,vt;
int d[N];
int vis[N];
void SPFA()
{
memset(vis,0,sizeof(vis));
for(int i = 1;i<=n;i++)
d[i]=inf;
d[s]=0;
queue<int>q;
q.push(s);
while(!q.empty())
{
int u = q.front();
q.pop();
vis[u]=0;
for(int i = 0;i<e[u].size();i++)
{
int v = e[u][i].v;
if(d[v]>d[u]+1)
{
d[v]=d[u]+1;
if(!vis[v])
q.push(v);
vis[v]=1;
}
}
}
}
struct Edge
{
int from,to,cap,flow;
Edge(int u,int v,int c,int f):from(u),to(v),cap(c),flow(f){}
};
struct Dinic
{
int s,t;
vector<Edge>edges;
vector<int> G[N];
bool vis[N];
int d[N];
int cur[N];
void init()
{
for (int i=0;i<=n+1;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));
int mm=edges.size();
G[from].push_back(mm-2);
G[to].push_back(mm-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];
}
int DFS(int x,int a)
{
if (x==t || a==0)
return a;
int 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;
}
int Maxflow(int s,int t)
{
this->s=s;
this->t=t;
int flow = 0;
while (BFS())
{
memset(cur,0,sizeof(cur));
flow+=DFS(s,inf);
}
return flow;
}
}DC;
int main()
{
int T,u,v,w;
cin>>T;
while(T--)
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
e[i].clear();
for(int i=1;i<=m;i++)
{
scanf("%d%d%d",&u,&v,&w);
e[u].push_back(node(v,w));
e[v].push_back(node(u,w));
}
s=n,t=1;
SPFA();
DC.init();
for(int i=1;i<=n;i++)
for(int j=0;j<e[i].size();j++)
if(d[e[i][j].v]==d[i]+1)
DC.AddEdge(i,e[i][j].v,e[i][j].w);
printf("%d\n",DC.Maxflow(s,t));
}
return 0;
}