计算机考研上机软件,acm考研计算机上机模板.doc

最短路径(dijkstra)

Description

All one knows Jesse live in the city , but he must come to Xiasha twice in a week. The road is too long for him to go . But he is so much resolute that nothing can prevent him from coming . More, Jesse must take many bus to come , the length of road is different. So, Jesse think : can I take the shortest road to save time ?

Now , the problem is puting on you , can you help him to calculate the shortest length?

Is it easy? Just do it!

Input

The input has several test cases. The first line of each case has two number n,m (1 <= n,m <= 200 ). n means have n bus stations 1th,2th,....nth . m means have m roads. Then following next m lines ,each line have 3 integer a,b,c which means the length between a and b bus station is c(0 < c < 2000).

Then a line with two integer s,t,means the start and end bus station.

Output

For the given start and end bus station ,output the shortest lenth between s and t in one line.

If the road not exists,output -1.

Sample Input

3 3

1 2 3

1 3 10

2 3 11

1 3

3 1

2 3 1

1 2

Sample Output

10

-1

#include

int choose(long distance[],int n,int found[])

{

int i,minpos=-1;

long min

for(i=1;i<=n;i++)

if(distance[i]

min=distance[i];

minpos=i;

}

return minpos;

}

void shorpath(int s,int n,int t,long road[][205])

{

int i,u,w;

int found[201];long distance[205];

for(i=1;i<=n;i++) {

found[i]=0;

distance[i]=road[s][i];

}

found[s]=1;

distance[s]=0;

for(i=1;i

u=choose(distance,n,found);

found[u]=1;

for(w=1;w<=n;w++)

if(!found[w])

if(distance[u]+road[u][w]

distance[w]=distance[u]+road[u][w];

}

if(distance[t]==9999999) printf("-1\n");

else

printf("%d\n",distance[t]);

}

int main()

{

int i,n,m,a,b,c,s,t;

long road[205][205];

while((scanf("%d%d",&n,&m))!=EOF)

{

for(i=1;i<=n;i++)

for(a=0;a<=n;a++)

road[i][a]=9999999;

for(i=1;i<=n;i++)

road[i][i]=0;

for(i=0;i

{

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值