1. 程式人生 > >HDU-4370 '0 or 1' 最短路 要考慮連通性

HDU-4370 '0 or 1' 最短路 要考慮連通性

names ref tps i++ typedef ont 最小 eve length

題目鏈接:https://cn.vjudge.net/problem/HDU-4370

題意

給一個矩陣C(nn),要我們找到一個矩陣X(nn),滿足以下條件:

X_{12}+X_{13}+...X_{1n}=1
X_{1n}+X_{2n}+...X_{n-1n}=1
for each i (1<i<n), satisfies ∑X_{ki} (1<=k<=n)=∑X_{ij} (1<=j<=n).
min ∑C ij*X ij

思路

如果把X當成一個鄰接矩陣,可以發現本題就是要找一個圖,滿足以下條件:

  1. 節點1有一個出度(註意不要1->1,因為要最小化邊權),節點n有一個入度(同理不要n->n)
  2. 其他節點出度等於入度
  3. 最小化邊權

很容易發現最短路是一種可能的情況(每個節點僅有一個出度入度)
另外還有一種情況需要考慮,就是起點和終點可以不連通,意思就是節點1節點n各參與一個互不連通的環

這還是要考慮連通問題啊
又沒考慮,可煩,考慮開一個最短路專題總結一下

提交過程

WA1 沒考慮連通性
WA2 int換long long
WA3 腦抽加上了1->1和n->n情況

代碼

#include <queue>
#include <cstdio>
#include <cstring>
using namespace std;
const
int maxn=320; const long long INF=1LL<<60; typedef pair<long long, int> Node; struct Cmp{ bool operator () (const Node &a, const Node &b){ return a.first>b.first; } }; int G[maxn+5][maxn+5]; long long Dij(int n){ long long dist[maxn+5], ans=0, circle1=INF, circle2=INF; priority_queue<Node, vector<Node>, Cmp> que; for
(int i=0;i<=n; i++) dist[i]=INF; dist[1]=0; que.push(Node(dist[1], 1)); while (que.size()){ Node x=que.top(); que.pop(); if (x.first!=dist[x.second]) continue; int &from=x.second; for (int to=1; to<=n; to++) if (to!=from){ int &dis=G[from][to]; if (to==1) circle1=min(circle1, dist[from]+dis); if (dist[to]<=dist[from]+(long long)dis) continue; dist[to]=dist[from]+(long long)dis; que.push(Node(dist[to], to)); } }//return dist[n]; ans=dist[n]; for (int i=0;i<=n; i++) dist[i]=INF; dist[n]=0; que.push(Node(dist[n], n)); while (que.size()){ Node x=que.top(); que.pop(); if (x.first!=dist[x.second]) continue; int &from=x.second; for (int to=1; to<=n; to++) if (to!=from){ int &dis=G[from][to]; if (to==n) circle2=min(circle2, dist[from]+dis); if (dist[to]<=dist[from]+(long long)dis) continue; dist[to]=dist[from]+(long long)dis; que.push(Node(dist[to], to)); } }return min(ans, circle1+circle2); } int main(void){ int n; while (scanf("%d", &n)==1 && n){ for (int y=1; y<=n; y++) for (int x=1; x<=n; x++) scanf("%d", &G[y][x]); printf("%lld\n", Dij(n)); } return 0; }
Time Memory Length Lang Submitted
1107ms 2012kB 1790 G++ 2018-06-02 11:28:23

HDU-4370 '0 or 1' 最短路 要考慮連通性