AOJ.187图的最短路径

Time Limit: 1000 ms   Case Time Limit: 1000 ms   Memory Limit: 64 MB
Total Submission: 205   Submission Accepted: 96
Description
求下图中从V1 到V10的最短路径

Input
输入图的邻接矩阵表示

Output
输出路径序列

Sample Input
OriginalTransformed
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
OriginalTransformed
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;

}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值