码迷,mamicode.com
首页 > 其他好文 > 详细

51Nod 1649 齐头并进

时间:2018-03-31 21:33:36      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:syn   eof   pre   AC   cin   div   false   cst   body   

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstring>
 4 //两遍迪杰斯特拉
 5 #define INF 0xfffffff
 6 using namespace std;
 7 const int maxn = 400 + 5;
 8 int rail[maxn][maxn];
 9 int dis[maxn];
10 int vis[maxn];
11 
12 void dij(int n, int u){
13     int i, j, p, Min;
14     memset(vis, 0, sizeof(vis));
15     for (int i = 1; i <= n; i++)
16         dis[i] = rail[u][i];
17     vis[u] = 1;
18     dis[u] = 0;
19 
20     for (i = 1; i < n; i++){
21         Min = INF;
22         for (j = 1; j <= n; j++){
23             if (!vis[j] && dis[j] < Min){
24                 p = j;
25                 Min = dis[j];
26             }
27         }
28         if (Min == INF) return;
29         vis[p] = 1;
30         for (j = 1; j <= n; j++){
31             if (!vis[j] && dis[p] + rail[p][j] < dis[j]){
32                 dis[j] = dis[p] + rail[p][j];
33             }
34         }
35     }
36 }
37 
38 int main(){
39     ios::sync_with_stdio(false);
40     fill(rail[0], rail[0] + maxn*maxn, INF);
41     int n, m;
42     cin >> n >> m;
43     if (m == 0){
44         //没有铁路
45         cout << "-1" << endl;
46         return 0;
47     }
48     for (int i = 0; i < m; i++){
49         int x, y;
50         cin >> x >> y;
51         rail[x][y] = 1;
52         rail[y][x] = 1;
53     }
54     dij(n, 1);
55     int ans1 = dis[n];
56     if (ans1 == INF || m == (n*(n - 1) / 2)){
57         //铁路没有答案,或者没有公路
58         cout << "-1" << endl;
59         return 0;
60     }
61 
62     for (int i = 1; i <= n; i++){
63         for (int j = 1 + i; j <= n; j++){
64             if (rail[i][j] == 1){
65                 rail[i][j] = INF;
66                 rail[j][i] = INF;
67             }
68             else{
69                 rail[i][j] = 1;
70                 rail[j][i] = 1;
71             }
72         }
73     }
74     dij(n, 1);
75     int ans2 = dis[n];
76     int ans = ans1 > ans2 ? ans1 : ans2;
77     cout << ans << endl;
78 
79 
80     system("pause");
81     return 0;
82 }

 

51Nod 1649 齐头并进

标签:syn   eof   pre   AC   cin   div   false   cst   body   

原文地址:https://www.cnblogs.com/jaydenouyang/p/8683999.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!