HUD-2112 HDU Today(最短路map标记)

题目链接:HUD-2112 HDU Today

HUD-2112 HDU Today(最短路map标记)

 


 

 

思路:

1.最短路spfa模板.

2.map标记建图.

3.考虑距离为0或者-1的情况.

总结:下次map记得清空orz。

AC代码:

 1 #include<cstdio>
 2 #include<map>
 3 #include<iostream>
 4 #include<queue>
 5 using namespace std;
 6 const int INF = 0x3f3f3f3f;
 7 const int maxn = 155;
 8 int Map[maxn][maxn];
 9 int n;
10 int d[maxn];
11 int vis[maxn];
12 void spfa(int s,int n)
13 {
14     queue<int> q;
15     for(int i = 1;i <= n;i++)
16     {
17         d[i] = INF;
18         vis[i] = 0;
19     }
20     d[s] = 0;
21     vis[s] = 1;
22     q.push(s);
23     while(!q.empty())
24     {
25         int k = q.front();q.pop();
26         vis[k] = 0;
27         for(int j = 1;j <= n;j++)
28         {
29             if(d[k] + Map[k][j] < d[j])
30             {
31                 d[j] = d[k] + Map[k][j];
32                 if(!vis[j])
33                     q.push(j),vis[j] = 1;
34             }
35         }
36     }
37 }
38 void init()
39 {
40     for(int i = 0;i <= 150;i++)
41     {
42         for(int j = 0;j <= i;j++)
43         {
44             if(j != i)
45             Map[i][j] = Map[j][i] = INF;
46             else Map[i][j] = 0;
47         }
48     }
49 }
50 int main()
51 {
52     char a[50],b[50];
53     map<string,int> mp;
54     char st[50],ed[50];
55     int w;
56     while(~scanf("%d",&n) && n!= -1)
57     {
58         init();//初始化
59         mp.clear();
60         int count = 0;//用于map一对一转化;
61         scanf("%s%s",&a,&b);
62         mp[a] = ++count;
63         if(!mp[b]) mp[b] = ++count;//如果终点未出现过,则加入图中;
64         for(int i = 0;i < n;i++)
65         {
66             scanf("%s %s %d",&st,&ed,&w);
67             if(!mp[st]) mp[st] = ++count;//检查两点是否出现过
68             if(!mp[ed]) mp[ed] = ++count;
69             int u = mp[st],v = mp[ed];
70             Map[u][v] = Map[v][u] = w;//建图;
71         }
72         spfa(1,count);
73         if(d[ mp[b] ] == INF) printf("-1\n");
74         else printf("%d\n",d[ mp[b] ]);
75     }
76     return 0;
77 }