题意:给你一幅有向图,给你A点和B点,从A走到B的长度要等于AB之间的最短路的长度,每条边只能走一次,问你最多可以从A走到B几次?
分析:首先求出AB之间的最短路,d[i]表示从S走到i点的最短路,针对边<i,j>,如果d[i]+value<i,j>==d[j],则建边add(i,j,1),跑一遍最大流即可。
代码:
#pragma comment(linker,"/STACK:102400000,102400000")
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <algorithm>
#include <vector>
#include <string>
#include <math.h>
#include <queue>
#include <stack>
#include <map>
#include <set>
using namespace std;
typedef long long ll; //记得必要的时候改成无符号
const int maxn=5005; //点数
const int maxm=1000005; //边数
const int INF=1000000000;
struct EdgeNode
{
int to;
int w;
int next;
}edg[maxm];
int head[maxn],cnt;
void add(int x,int y,int z)
{
edg[cnt].to=y;
edg[cnt].w=z;
edg[cnt].next=head[x];
head[x]=cnt++;
}
void init()
{
cnt=0;
memset(head,-1,sizeof(head));
}
int n,m,d[maxn];
void DJ(int st)
{
int x,y,z;
typedef pair<int,int>p;
priority_queue<p,vector<p>,greater<p> >Q;
fill(d,d+n+2,INF);
d[st]=0;
Q.push(p(0,st));
while(!Q.empty())
{
p t=Q.top();
Q.pop();
x=t.second;
if(d[x]<t.first)
continue;
for(int i=head[x];i!=-1;i=edg[i].next)
{
y=edg[i].to; z=edg[i].w;
if(d[x]+z<d[y])
{
d[y]=d[x]+z;
Q.push(p(d[y],y));
}
}
}
}
struct Node
{
int from;
int to;
int cost;
int next;
}edge[maxm];
void add1(int x,int y,int z)
{
edge[cnt].from=x;edge[cnt].to=y;edge[cnt].cost=z;edge[cnt].next=head[x];head[x]=cnt++;
edge[cnt].from=y;edge[cnt].to=x;edge[cnt].cost=0;edge[cnt].next=head[y];head[y]=cnt++;
}
int S,T;
int gap[maxn],curedge[maxn],pre[maxn];
//curedge[]为当前弧数组,pre为前驱数组
int sap(int S,int T,int n) //n为点数
{
int cur_flow,flow_ans=0,u,tmp,neck,i;
memset(d,0,sizeof(d));
memset(gap,0,sizeof(gap));
memset(pre,-1,sizeof(pre));
for(i=0;i<=n;i++)curedge[i]=head[i]; //初始化当前弧为第一条邻接表
gap[0]=n;
u=S;
while(d[S]<n) //当d[S]>=n时,网络中肯定出现了断层
{
if(u==T)
{
cur_flow=INF;
for(i=S;i!=T;i=edge[curedge[i]].to)
{ //增广成功,寻找瓶颈边
if(cur_flow>edge[curedge[i]].cost)
{
neck=i;
cur_flow=edge[curedge[i]].cost;
}
}
for(i=S;i!=T;i=edge[curedge[i]].to)
{ //修改路径上的边容量
tmp=curedge[i];
edge[tmp].cost-=cur_flow;
edge[tmp^1].cost+=cur_flow;
}
flow_ans+=cur_flow;
u=neck; //下次增广从瓶颈边开始
}
for(i=curedge[u];i!=-1;i=edge[i].next)
if(edge[i].cost&&d[u]==d[edge[i].to]+1)
break;
if(i!=-1)
{
curedge[u]=i;
pre[edge[i].to]=u;
u=edge[i].to;
}
else
{
if(0==--gap[d[u]])break; //gap优化
curedge[u]=head[u];
for(tmp=n,i=head[u];i!=-1;i=edge[i].next)
if(edge[i].cost)
tmp=min(tmp,d[edge[i].to]);
d[u]=tmp+1;
++gap[d[u]];
if(u!=S)u=pre[u]; //重标号并且从当前点前驱重新增广
}
}
return flow_ans;
}
struct p
{
int x,y,z;
}bian[maxm];
int main()
{
int t,i,x,y,z,ans;
scanf("%d",&t);
while(t--){
init(); ans=0;
scanf("%d%d",&n,&m);
for(i=1;i<=m;i++){
scanf("%d%d%d",&x,&y,&z);
if(x==y)continue;
bian[++ans].x=x; bian[ans].y=y; bian[ans].z=z;
add(x,y,z);
}
scanf("%d%d",&S,&T);
DJ(S);
init();
for(i=1;i<=ans;i++){
x=bian[i].x; y=bian[i].y; z=bian[i].z;
if(d[x]+z==d[y])add1(x,y,1);
}
printf("%d\n",sap(S,T,n));
}
return 0;
}
版权声明:本文为zcw1993912原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。