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

E - Easy Dijkstra Problem(求最短路)

时间:2018-07-20 13:49:48      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:AMM   stream   直接   class   pat   mil   each   \n   desc   

Description

Determine the shortest path between the specified vertices in the graph given in the input data.
Hint: You can use Dijkstra‘s algorithm.
Hint 2: if you‘re a lazy C++ programmer, you can use set and cin/cout (with sync_with_stdio(0)) - it should suffice.

Input

first line - one integer - number of test cases For each test case the numbers V, K (number of vertices, number of edges) are given,Then K lines follow, each containing the following numbers separated by a single space:ai, bi, ci ,It means that the graph being described contains an edge from ai to bi,with a weight of ci.Below the graph description a line containing a pair of integers A, B is present.The goal is to find the shortest path from vertex A to vertex B.All numbers in the input data are integers in the range 0..10000.

Output

For each test case your program should output (in a separate line) a single number C - the length of the shortest path from vertex A to vertex B. In case there is no such path, your program should output a single word "NO" (without quotes)

Example

Input:
3
3 2
1 2 5
2 3 7
1 3
3 3
1 2 4
1 3 7
2 3 1
1 3
3 1
1 2 4
1 3

Output:
12
5
NO
解题思路:坑题,WA了好几发=_=||原来题目说明的是顶点a到顶点b是一条有向边,即a-->b,而不是无向图求单源最短路,裸题(邻接矩阵)水过!
AC代码:
 1 #include<iostream>
 2 #include<string.h>
 3 #include<cstdio>
 4 using namespace std;
 5 const int INF=0x3f3f3f3f;
 6 const int maxn=10005;
 7 int t,n,k,a,b,c,st,ed,dis[maxn],cost[maxn][maxn];bool flag,vis[maxn];
 8 void dijkstra(){
 9     for(int i=1;i<=n;++i)
10         dis[i]=cost[st][i];
11     dis[st]=0;vis[st]=true;
12     for(int i=1;i<n;++i){
13         int k=-1;
14         for(int j=1;j<=n;++j)
15             if(!vis[j]&&(k==-1||dis[k]>dis[j]))k=j;
16         if(dis[k]==INF){flag=true;break;}//如果此时没有最小值即为INF,说明肯定是达不到终点ed,直接退出循环
17         if(k==-1)break;
18         vis[k]=true;
19         for(int j=1;j<=n;++j)
20             if(!vis[j])dis[j]=min(dis[j],dis[k]+cost[k][j]);
21     }
22 }
23 int main(){
24     scanf("%d",&t);
25     while(t--){
26         scanf("%d%d",&n,&k);
27         for(int i=1;i<=n;++i)
28             for(int j=1;j<=n;++j)
29                 cost[i][j]=cost[j][i]=(i==j?0:INF);
30         memset(vis,false,sizeof(vis));
31         while(k--){
32             scanf("%d%d%d",&a,&b,&c);
33             cost[a][b]=min(cost[a][b],c);//去重
34         }
35         scanf("%d%d",&st,&ed);
36         flag=false;
37         dijkstra();
38         if(flag)printf("NO\n");
39         else printf("%d\n",dis[ed]);
40     }
41     return 0;
42 }

 

E - Easy Dijkstra Problem(求最短路)

标签:AMM   stream   直接   class   pat   mil   each   \n   desc   

原文地址:https://www.cnblogs.com/acgoto/p/9340867.html

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