E - Easy Dijkstra Problem(求最短路)
阿新 • • 發佈:2018-07-20
cos rmi rom () lag col tro ring ecif , 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.
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
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(求最短路)