链接:点击打开链接
题意:求有多少条不相交的最短路
代码:
#include <queue>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <algorithm>
const int INF=0x3f3f3f3f;
using namespace std;
struct edge{
int to,cost;
};
typedef pair<int,int> P;
int V;
vector<edge> G[3005];
int d[3005];
void dijkstra(int s){
int i,v;
priority_queue<P,vector<P>,greater<P> >que;
fill(d,d+V+1,INF);
d[s]=0;
que.push(P(0,s));
while(!que.empty()){
P p=que.top(); que.pop();
v=p.second;
if(d[v]<p.first)
continue;
for(i=0;i<G[v].size();i++){
edge e=G[v][i];
if(d[e.to]>d[v]+e.cost){
d[e.to]=d[v]+e.cost;
que.push(P(d[e.to],e.to));
}
}
}
}
struct node{
int u,v,cap;
node(){}
node(int u,int v,int cap):u(u),v(v),cap(cap){}
}es[1000005];
int R,S,T;
int dis[3005],vis[3005],iter[3005];
vector<int> tab[3005];
void addedge(int u, int v, int cap){
tab[u].push_back(R);
es[R++]=node(u,v,cap);
tab[v].push_back(R);
es[R++]=node(v,u,0);
}
int bfs(){
int i,h;
queue<int> q;
q.push(S);
memset(dis,INF,sizeof(dis));
dis[S]=0;
while(q.size()){
h=q.front();
q.pop();
for(i=0;i<tab[h].size();i++){
node &e=es[tab[h][i]];
if(e.cap>0&&dis[e.v]==INF){
dis[e.v]=dis[h]+1;
q.push(e.v);
}
}
}
return dis[T]<INF;
}
int dfs(int x,int maxflow){
int flow;
if(x==T)
return maxflow;
for(int &i=iter[x];i<tab[x].size();i++){
node &e=es[tab[x][i]];
if(dis[e.v]==dis[x]+1&&e.cap>0){
flow=dfs(e.v,min(maxflow,e.cap));
if(flow){
e.cap-=flow;
es[tab[x][i]^1].cap+=flow;
return flow;
}
}
}
return 0;
}
int dinic(){
int ans,flow;
ans=0;
while(bfs()){
memset(iter,0,sizeof(iter));
while(flow=dfs(S,INF))
ans+=flow;
}
return ans;
}
int x[1000005],y[1000005],z[1000005];
int main(){ //在最短路上跑网络流
int i,j,t,m,ans;
scanf("%d",&t);
while(t--){
scanf("%d",&V);
R=0,S=1,T=V;
for(i=0;i<=V;i++){
G[i].clear();
tab[i].clear();
}
i=0;
while(scanf("%d%d%d",&x[i],&y[i],&z[i])&&(x[i]||y[i]||z[i])){
G[x[i]].push_back((edge){y[i],z[i]});
G[y[i]].push_back((edge){x[i],z[i]});
i++;
}
m=i;
dijkstra(1);
if(d[V]==INF||V==1){
puts("0");
continue;
}
for(i=0;i<m;i++){ //判断是不是最短路上的边,是就建图跑网络流
if(d[y[i]]-d[x[i]]==z[i])
addedge(x[i],y[i],1);
else if(d[x[i]]-d[y[i]]==z[i])
addedge(y[i],x[i],1);
}
ans=dinic();
printf("%d\n",ans);
}
return 0;
}