题目地址:ZOJ 1760
利用这篇博客里提到的判断最短路边的方法,标记最短路的边,然后跑一次最大流就行了。不多说了。
#include <iostream> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <ctype.h> #include <queue> #include <map> #include<algorithm> using namespace std; const int INF=0x3f3f3f3f; int head[200], source, sink, nv, cnt; int cur[200], num[200], d[200], pre[200]; struct node { int u, v, cap, next; } edge[1000000]; void add(int u, int v, int cap) { edge[cnt].v=v; edge[cnt].cap=cap; edge[cnt].next=head[u]; head[u]=cnt++; edge[cnt].v=u; edge[cnt].cap=0; edge[cnt].next=head[v]; head[v]=cnt++; } void bfs() { memset(d,-1,sizeof(d)); memset(num,0,sizeof(num)); queue<int>q; q.push(sink); d[sink]=0; num[0]=1; while(!q.empty()) { int u=q.front(); q.pop(); for(int i=head[u];i!=-1;i=edge[i].next) { int v=edge[i].v; if(d[v]==-1) { d[v]=d[u]+1; num[d[v]]++; q.push(v); } } } } void isap() { memcpy(cur,head,sizeof(cur)); bfs(); int flow=0, u=pre[source]=source, i; while(d[source]<nv) { if(u==sink) { int f=INF, pos; for(i=source;i!=sink;i=edge[cur[i]].v) { if(f>edge[cur[i]].cap) { f=edge[cur[i]].cap; pos=i; } } for(i=source;i!=sink;i=edge[cur[i]].v) { edge[cur[i]].cap-=f; edge[cur[i]^1].cap+=f; } flow+=f; u=pos; } for(i=cur[u];i!=-1;i=edge[i].next) { if(d[edge[i].v]+1==d[u]&&edge[i].cap) { break; } } if(i!=-1) { cur[u]=i; pre[edge[i].v]=u; u=edge[i].v; } else { if(--num[d[u]]==0) break; int mind=nv; for(i=head[u];i!=-1;i=edge[i].next) { if(mind>d[edge[i].v]&&edge[i].cap) { mind=d[edge[i].v]; cur[u]=i; } } d[u]=mind+1; num[d[u]]++; u=pre[u]; } } printf("%d\n",flow); } int d1[200], vis[200], cnt1, head1[200]; struct node1 { int u, v, w, next; } path[1000000]; void add1(int u, int v, int w) { path[cnt1].v=v; path[cnt1].w=w; path[cnt1].next=head1[u]; head1[u]=cnt1++; } void spfa() { int i; deque<int>q; q.push_front(source); memset(d1,INF,sizeof(d1)); memset(vis,0,sizeof(vis)); d1[source]=0; while(!q.empty()) { int u=q.front(); q.pop_front(); vis[u]=0; for(i=head1[u]; i!=-1; i=path[i].next) { int v=path[i].v; if(d1[v]>d1[u]+path[i].w) { d1[v]=d1[u]+path[i].w; if(!vis[v]) { vis[v]=1; if(!q.empty()&&d1[v]<d1[q.front()]) { q.push_front(v); } else q.push_back(v); } } } } } int main() { int n, i, j, x; while(scanf("%d",&n)!=EOF) { memset(head1,-1,sizeof(head1)); cnt1=0; for(i=0; i<n; i++) { for(j=0; j<n; j++) { scanf("%d",&x); if(x>=0&&i!=j) { add1(i,j,x); } } } scanf("%d%d",&source,&sink); if(source==sink) { printf("inf\n"); continue ; } nv=n; spfa(); memset(head,-1,sizeof(head)); cnt=0; for(i=0;i<n;i++) { for(j=head1[i];j!=-1;j=path[j].next) { if(d1[path[j].v]==d1[i]+path[j].w) { add(i,path[j].v,1); } } } isap(); } return 0; }