The shortest path | dijkstra

Shortest path


from hdu 2544
Time limit:1s
Memory limit:32MB

Problem Description

In the annual school competition, all students who enter the finals will get a very beautiful t-shirt. But every time our staff transported hundreds of clothes from the store back to the stadium, they were very tired! So now they want to find the shortest route from the store to the stadium, can you help them?

Input

The input includes multiple sets of data. The first row of each group of data is two integers N and M (N<=100, M<=10000). N indicates how many intersections on the streets of Chengdu, the intersection marked 1 is the location of the store, and the intersection marked N It is the location of the stadium, M said there are several roads in Chengdu. N=M=0 means the end of input. The next M lines, each line includes 3 integers A, B, C (1<=A, B<=N, 1<=C<=1000), indicating that there is a road between intersection A and intersection B. We The staff needs C minutes to walk this way.
Enter to ensure that there is at least one route from the store to the stadium.

Output

For each group of input, output one line, which means the shortest time for the staff to walk from the store to the stadium

Sample Input

2 1
1 2 3
3 3
1 2 5
2 3 5
3 1 2
0 0

Sample Output

3
2

The shortest path problem, if there is no negative side, dijkstra can drop ac.

#include<cstdio>
#include<cstring>
using namespace std;
int mp[105][105],dis[105];               //mp存储地图,dis是距离状态
bool note[105];                          //后续dij算法查看某个点是否已经被选取过
int n,m;                                 //点、边
void init(){
    
                                 //初始化
    memset(mp,0x3f,sizeof(mp)),memset(note,false,sizeof(note));
    int f,t,w;
    for(int i = 1;i <= m;++i)
        scanf("%d %d %d",&f,&t,&w),mp[f][t] = mp[t][f] = w;
    for(int i = 2;i <= n;++i)
        dis[i] = mp[1][i];
    dis[1] = 0;note[1] = true;
} 
void solve(){
    
    
    for(int i = 2;i <= n;++i){
    
          //dijkstra
        int mi = 0x3f3f3f3f,k = -1;
        for(int j = 2;j <= n;++j)
            if(!note[j] && mi > dis[j])
                mi = dis[j],k = j;
        note[k] = true;
        for(int j = 2;j <= n;++j)
            if(dis[j] > dis[k] + mp[k][j])
                dis[j] = dis[k] + mp[k][j];
    }
    printf("%d\n",dis[n]);
}
int main(){
    
    
    while(scanf("%d %d",&n,&m) && (n || m)){
    
    
        init();
        solve();
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_45985728/article/details/113702520