ZOJ 2760 How Many Shortest Path (floyd+dinic)

题目大意:

题目即题解。


解题思路:

floyd求出最短路,对于能在最短路上的边 u->v 建流量为1的边。

s-t的最大流即为答案。


#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<set>
#include<queue>
#define LL long long
#define db double
#define maxn 10000000
#define EPS 1e-15

#define inf 1000000000

using namespace std;
int n,cnt,s,t;
int last[105],h[105],q[105],cur[105];
int mp[105][105],dis[105][105];
struct edge{
	int to,next,w;
}e[100005];
void insert(int u,int v,int w){
	e[++cnt].to=v; e[cnt].w=w; e[cnt].next=last[u]; last[u]=cnt;
	e[++cnt].to=u; e[cnt].w=0; e[cnt].next=last[v]; last[v]=cnt;
}
void floyd(){
	for (int k=1;k<=n;k++)
		for (int i=1;i<=n;i++)
			for (int j=1;j<=n;j++)
			dis[i][j]=min(dis[i][j],dis[i][k]+dis[k][j]);
}
void build(){
	for (int i=1;i<=n;i++)
		for (int j=1;j<=n;j++)
		if (mp[i][j]!=-1
			&& dis[s][i]+dis[j][t]+mp[i][j]==dis[s][t])
			insert(i,j,1);
}
bool bfs(){
	int head=0,tail=1;
	memset(h,-1,sizeof(h));
	q[0]=s; h[s]=0;
	while (head!=tail) {
		int now=q[head]; head++;
		for (int i=last[now];i;i=e[i].next)
			if (e[i].w && h[e[i].to]==-1){
				h[e[i].to]=h[now]+1;
				q[tail++]=e[i].to;
			}
	}
	return h[t]!=-1;
}
int dfs(int x,int f){
	if (x==t) return f;
	int w,used=0;
	for (int i=cur[x];i;i=e[i].next)
		if (h[e[i].to]==h[x]+1){
			w=dfs(e[i].to,min(f-used,e[i].w));
			e[i].w-=w; e[i^1].w+=w;
			if (e[i].w) cur[x]=i;
			used+=w;
			if (used==f) return f;
		}
	if (!used) h[x]=-1;
	return used;
}
int dinic_flow(){
	int tmp=0;
	while (bfs()){
		for (int i=1;i<=n;i++) cur[i]=last[i];
		tmp+=dfs(s,inf);
	}
	return tmp;
}
int main(){
	while(scanf("%d",&n)!=EOF){
		cnt=1;
		memset(last,0,sizeof(last));
		memset(dis,127/3,sizeof(dis));
		for (int i=1;i<=n;i++)
			for (int j=1;j<=n;j++){
				scanf("%d",&mp[i][j]);
				if (mp[i][j]!=-1) dis[i][j]=mp[i][j];
			}
		for (int i=1;i<=n;i++)
			dis[i][i]=0;
		scanf("%d%d",&s,&t);
		s++; t++;
		if (s==t) {puts("inf");continue;}
		floyd();
		build();
		printf("%d\n",dinic_flow());
	}
	return 0;
}



你可能感兴趣的:(ZOJ 2760 How Many Shortest Path (floyd+dinic))