HDU 1874 Smooth Traffic Project (single starting point for a single end Dykstra method)

Problem Description
province since the smooth implementation of the project for many years, finally built many roads. But more is not a good way, each time from one town to another, there are many kinds of road schemes to choose from, and some programs are other programs, walking distance much shorter than others. This allows pedestrians very troubled.
Now, start and end points are known, you calculate from the beginning to the end, how much the shortest distance required to walk.

Input
this topic contains multiple sets of data, the processing to the end of the file.
Each test line contains two positive integers N and M (0 <N <200,0 < M <1000), represents the number of towns and the number of existing roads have been built. In urban numbered 0 ~ N-1.
Followed by M lines road information. Each row contains three integers A, B, X (0 < = A, B <N, A! = B, 0 <X <10000), expressed between towns and urban A B X a length of two-way road.
The next line followed by two integers S, T (0 <= S , T <N), representing the start and end points.

Output
For each set of data, the output from the minimum required to walk on one line. If the route from S to T does not exist, the output of -1.

Sample Input
3 3
0 1 1
0 2 3
1 2 1
0 2
3 1
0 1 1
1 2

Sample Output
2
-1

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
using namespace std;
//这道题倒像是迪杰特斯拉的套用模板就行,这道新的题的难点在于,需要判断最后是否存在这个路径,我的想法是,看最后那个路径长度是不是大于我给定的原始值100,如果大于
//如果大于,说明就不行其实可以就直接照搬源码的,但是想想,还是自己再写一遍吧
int n,m;
int a,b,x;
int q,t;
bool mark[100];
int maplen[100][100];
int dis[100];
int i,j,k;
void Dj(int s){
    //先初始化
    for(i=0;i<n;i++){
        dis[i]=maplen[s][i];
        mark[i]=false;
    }
    dis[s]=0;
    mark[s]=true;
    //开始循环
    for(i=0;i<n-1;i++){
        int mmin=1000;
        for(j=0;j<n;j++){
            if(!mark[j]&&dis[j]<mmin){
                k=j;
                mmin=dis[j];
            }
        }
        mark[k]=true;
        for(j=0;j<n;j++){
            if(!mark[j]&&dis[j]>(dis[k]+maplen[k][j]))
                dis[j]=(dis[k]+maplen[k][j]);
        }
    }
}

int main(){
    //输入入口和路
    while(scanf("%d%d",&n,&m)!=EOF&&n!=0&&m!=0){
    //初始化maptime
    for(i=0;i<n;i++)
        for(j=0;j<n;j++)
        maplen[i][j]=100;
    //开始输入边
    for(i=0;i<m;i++){
        scanf("%d%d%d",&a,&b,&x);
        maplen[a][b]=x;
        maplen[b][a]=x;
    }
    //开始输入起点和终点
    scanf("%d%d",&q,&t);
    Dj(q);
    if(dis[t]>=100)
        printf("-1\n");
    else
        printf("%d\n",dis[t]);

}
}

Published 72 original articles · won praise 5 · Views 2798

Guess you like

Origin blog.csdn.net/qq_41115379/article/details/104991510