解题思路
敌人走的是最短路,所以先把最短路建图,可以用bfs,也可以用dijkstra求,找满足dis[i]=dis[j]+1的边,最后跑一边最大流算法。
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include <queue>
#include <vector>
#include <set >
#include<algorithm>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
const int maxn=1005;
const int INF=1e9;
struct edge
{
int to,cap,rev;
};
vector<edge>G[maxn];
int level[maxn];
int iter[maxn];
void add_edge(int from,int to,int cap)
{
G[from].push_back((edge)
{
to,cap,G[to].size()
});
G[to].push_back((edge)
{
from,0,G[from].size()-1
});
}
void bfs(int s)
{
memset(level,-1,sizeof(level));
queue<int>que;
level[s]=0;
que.push(s);
while(!que.empty())
{
int v=que.front();
que.pop();
for(int i=0; i<G[v].size(); ++i)
{
edge &e=G[v][i];
if(e.cap>0&&level[e.to]<0)
{
level[e.to]=level[v]+1;
que.push(e.to);
}
}
}
}
int dfs(int v,int t,int f)
{
if(v==t) return f;
for(int &i=iter[v]; i<G[v].size(); ++i)
{
edge &e=G[v][i];
if(e.cap>0&&level[v]<level[e.to])
{
int d=dfs(e.to,t,min(f,e.cap));
if(d>0)
{
e.cap-=d;
G[e.to][e.rev].cap+=d;
return d;
}
}
}
return 0;
}
int Dinic(int s,int t)
{
int maxflow=0;
while(1)
{
bfs(s);
if(level[t]<0) return maxflow;
memset(iter,0,sizeof(iter));
int f;
while((f=dfs(s,t,INF))>0)
maxflow+=f;
}
}
struct Edge {
int v, w;
Edge(int v, int w): v(v), w(w) {}
};
const int N=1005;
vector<Edge> g[N];
int dis[N];
bool vis[N];
int n,m;
void Dijkstra(int s, int dist[]) {
priority_queue<pair<int, int> > Q;
for(int i = 0; i < n; i++)
dist[i] = INF;
memset(vis, 0, sizeof(vis));
Q.push(make_pair(0, s));
dist[s] = 0;
while(!Q.empty()) {
int u = Q.top().second;
Q.pop();
if(vis[u]) continue ;
vis[u] = 1;
int len= g[u].size();
for(int i = 0; i < len; i++) {
Edge& e = g[u][i];
if(dist[u] + e.w < dist[e.v]) {
dist[e.v] = dist[u] + e.w;
Q.push(make_pair(-dist[e.v], e.v));
}
}
}
}
int val[1005][1005];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
n--;
for(int i=0; i<=n+1; i++)
{
g[i].clear();
G[i].clear();
}
memset(val,0,sizeof(val));
for(int i=0; i<m; i++)
{
int u,v,c;
scanf("%d%d%d",&u,&v,&c);
u--;v--;
g[u].push_back(Edge (v,1));
g[v].push_back(Edge (u,1));
val[u][v]=c;
val[v][u]=c;
}
Dijkstra(n,dis);
for(int i=n; i>=0; i--)
{
int len=g[i].size();
for(int j=0; j<len; j++)
{
Edge e=g[i][j];
if(dis[i]+1==dis[e.v])
{
add_edge(i,e.v,val[i][e.v]);
}
}
}
printf("%d\n",Dinic(n,0));
}
return 0;
}