Time Limit: 1000 ms Case Time Limit: 1000 ms Memory Limit: 64 MB
Total Submission: 205 Submission Accepted: 96
Total Submission: 205 Submission Accepted: 96
Description
求下图中从V1 到V10的最短路径
Input
输入图的邻接矩阵表示
Output
输出路径序列
Sample Input
Original | Transformed |
0 2 5 1 -1 -1 -1 -1 -1 -1 -1 0 -1 -1 12 14 -1 -1 -1 -1 -1 -1 0 -1 6 10 4 -1 -1 -1 -1 -1 -1 0 13 12 11 -1 -1 -1 -1 -1 -1 -1 0 -1 -1 3 9 -1 -1 -1 -1 -1 -1 0 -1 6 5 -1 -1 -1 -1 -1 -1 -1 0 -1 10 -1 -1 -1 -1 -1 -1 -1 -1 0 -1 5 -1 -1 -1 -1 -1 -1 -1 -1 0 2 -1 -1 -1 -1 -1 -1 -1 -1 -1 0
Sample Output
Original | Transformed |
1 3 5 8 10
#include<cstdio> #include<iostream> #include<cstring> #include<queue> #include<string> #include<vector> #include<ctime> #include<map> #include<set> #include<bitset> #include<algorithm> #include<cmath> #include<stack> //#define DEBUG using namespace std; const int INF = 0x7fffffff; const int maxn = 55; int matrix[maxn][maxn]; int path[maxn]; stack<int>sta; void Dijkstra(int v0,int out[],int n); int main(){ cin.tie(0); cin.sync_with_stdio(false); #ifdef DEBUG int START = clock(); freopen("Text.txt","r",stdin); #endif int i,j,n=10; for(i=0;i<n;i++) for(j=0;j<n;j++) cin>>matrix[i][j]; int a=0,b=9; int result[maxn]; Dijkstra(0,result,n); sta.push(b+1); while(path[b]!=-1){ sta.push(path[b]+1); b=path[b]; } while(!sta.empty()){ cout<<sta.top()<<ends; sta.pop(); } cout<<endl; #ifdef DEBUG printf("Time:%.3lf\n",(double)(clock() - START) / CLOCKS_PER_SEC); #endif return 0; } void Dijkstra(int v0,int out[],int n){ bool s[maxn]; int last_visited=0; int i,j; for(i=0;i<n;i++){ path[i]=-1; out[i]=INF; } memset(s,0,sizeof(s)); s[v0]=true; out[v0]=0; for(i=0;i<n-1;i++){ for(j=0;j<n;j++){ if(s[j]==0){ if(matrix[v0][j]!=-1){ int dist=matrix[v0][j]+last_visited; if(dist<out[j]){ out[j]=dist; path[j]=v0; } } } } int minIndex=0; while(s[minIndex]==1)minIndex++; for(j=minIndex;j<n;j++){ if(s[j]==0&&out[j]<out[minIndex]) minIndex=j; } s[minIndex]=1; last_visited=out[minIndex]; v0=minIndex; } }