zoj 2760 How Many Shortest Path 最大流
題目鏈接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1760
Given a weighted directed graph, we define the shortest path as the path who has the smallest length among all the path connecting the source vertex to the target vertex. And if two path is said to be non-overlapping, it means that the two path has no common edge. So, given a weighted directed graph, a source vertex and a target vertex, we are interested in how many non-overlapping shortest path could we find out at most.
題目描述:求一個有向圖起點到終點的邊不相交的最短路徑的條數。
算法分析:floyd+最大流。針對網絡流算法而建的模型中,s-t對應于實際中每一種方案,所以此題中的s-t就對應于題目中的一條源點到匯點的最短路徑,最大流就是最短路徑條數。
接下來就是怎么建模的問題:既然s-t對應于一條最短路徑,那么s-t路徑上的每一條邊都是路徑中的最短邊。所以首先用floyd求出點到點的最短路徑,然后枚舉每條邊判斷是否是最短路徑上的邊,若是,則加入到新建的圖中,權值為1。
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<cstdlib> 5 #include<cmath> 6 #include<algorithm> 7 #include<queue> 8 #define inf 0x7fffffff 9 using namespace std; 10 const int maxn=100+10; 11 12 int n,from,to; 13 int dist[maxn][maxn],an[maxn][maxn]; 14 int d[maxn],graph[maxn][maxn]; 15 16 int bfs() 17 { 18 memset(d,0,sizeof(d)); 19 d[from]=1; 20 queue<int> Q; 21 Q.push(from); 22 while (!Q.empty()) 23 { 24 int u=Q.front() ;Q.pop() ; 25 for (int v=0 ;v<n ;v++) 26 { 27 if (!d[v] && graph[u][v]>0) 28 { 29 d[v]=d[u]+1; 30 Q.push(v); 31 if (v==to) return 1; 32 } 33 } 34 } 35 return 0; 36 } 37 38 int dfs(int u,int flow) 39 { 40 if (u==to || flow==0) return flow; 41 int cap=flow; 42 for (int v=0 ;v<n ;v++) 43 { 44 if (d[v]==d[u]+1 && graph[u][v]>0) 45 { 46 int x=dfs(v,min(cap,graph[u][v])); 47 cap -= x; 48 graph[u][v] -= x; 49 graph[v][u] += x; 50 if (cap==0) return flow; 51 } 52 } 53 return flow-cap; 54 } 55 56 int dinic() 57 { 58 int sum=0; 59 while (bfs()) sum += dfs(from,inf); 60 return sum; 61 } 62 63 int main() 64 { 65 while (scanf("%d",&n)!=EOF) 66 { 67 for (int i=0 ;i<n ;i++) 68 { 69 for (int j=0 ;j<n ;j++) 70 { 71 scanf("%d",&an[i][j]); 72 dist[i][j]=an[i][j]; 73 } 74 dist[i][i]=an[i][i]=0; 75 } 76 scanf("%d%d",&from,&to); 77 if (from==to) {printf("inf\n");continue; } 78 for (int k=0 ;k<n ;k++) 79 { 80 for (int i=0 ;i<n ;i++) if (i!=k) 81 { 82 for (int j=0 ;j<n ;j++) if (j!=k && j!=i) 83 { 84 if (dist[i][k]!=-1 && dist[k][j]!=-1 && 85 (dist[i][j]==-1 || dist[i][j]>dist[i][k]+dist[k][j])) 86 dist[i][j]=dist[i][k]+dist[k][j]; 87 } 88 } 89 } 90 //cout<<"dist[from][to]= "<<dist[from][to]<<endl; 91 if (dist[from][to]==-1) {printf("0\n");continue; } 92 memset(graph,0,sizeof(graph)); 93 for (int i=0 ;i<n ;i++) 94 { 95 for (int j=0 ;j<n ;j++) 96 { 97 if (i!=j && dist[from][to]!=-1 && dist[from][i]!=-1 && dist[j][to]!=-1 && an[i][j]!=-1 && 98 dist[from][to]==dist[from][i]+an[i][j]+dist[j][to]) 99 graph[i][j]=1; 100 } 101 } 102 printf("%d\n",dinic()); 103 } 104 return 0; 105 }?
轉載于:https://www.cnblogs.com/huangxf/p/4299733.html
總結
以上是生活随笔為你收集整理的zoj 2760 How Many Shortest Path 最大流的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android - 广播机制和Servi
- 下一篇: Java从零开始学二十三(集合Map接口