LightOJ Brush (V) 1019【简单最短路】

1019 - Brush (V)
PDF (English) Statistics Forum
Time Limit: 2 second(s) Memory Limit: 32 MB

Tanvir returned home from the contest and got angry after seeing his room dusty. Who likes to see a dusty room after a brain storming programming contest? After checking a bit he found that there is no brush in him room. So, he called Atiq to get a brush. But as usual Atiq refused to come. So, Tanvir decided to go to Atiq's house.

The city they live in is divided by some junctions. The junctions are connected by two way roads. They live in different junctions. And they can go to one junction to other by using the roads only.

Now you are given the map of the city and the distances of the roads. You have to find the minimum distance Tanvir has to travel to reach Atiq's house.

Input

Input starts with an integer T (≤ 100), denoting the number of test cases.

Each case starts with a blank line. The next line contains two integers N (2 ≤ N ≤ 100) and M (0 ≤ M ≤ 1000), means that there are N junctions and M two way roads. Each of the next M lines will contain three integers u v w (1 ≤ u, v ≤ N, w ≤ 1000), it means that there is a road between junctionu and v and the distance is w. You can assume that Tanvir lives in the 1st junction and Atiq lives in the Nth junction. There can be multiple roads between same pair of junctions.

Output

For each case print the case number and the minimum distance Tanvir has to travel to reach Atiq's house. If it's impossible, then print 'Impossible'.

Sample Input

Output for Sample Input

2

 

3 2

1 2 50

2 3 10

 

3 1

1 2 40

Case 1: 60

Case 2: Impossible

 


题意:

就是求一个最短路。

解题思路:

DIjkstra

AC代码:


#include <stdio.h>
#include <math.h>
#include <vector>
#include <queue>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
#define INF 0x3f3f3f3f

using namespace std;

const int MAXN = 110;
int used[110];
int d[110];
int cost[MAXN][MAXN];

int N,M;

void dijkstra()
{
    for(int i=1;i<=N;i++){
        used[i]=0;
        d[i]=INF;
    }
    d[1]=0;
    while(1){
        int v=-1;
        for(int i=1;i<=N;i++)
            if(!used[i]&&(v==-1||d[v]>d[i])) v=i;
        if(v==-1) break;
        used[v]=1;
        for(int i=1;i<=N;i++)
            d[i]=min(d[i],d[v]+cost[v][i]);
    }
}
int main()
{
    int T;
    scanf("%d",&T);
    int xp=0;
    while(T--){
        scanf("%d%d",&N,&M);
        for(int i=1;i<=N;i++){
            for(int j=1;j<=N;j++)
                cost[i][j]=INF;
        }
        int a,b,c;
        for(int i=0;i<M;i++){
            scanf("%d%d%d",&a,&b,&c);
            if(cost[a][b]>c){
                cost[a][b]=cost[b][a]=c;
            }
        }
        dijkstra();
        if(d[N]==INF) printf("Case %d: Impossible\n",++xp);
        else printf("Case %d: %d\n",++xp,d[N]);
    }
    return 0;
}


你可能感兴趣的:(LightOJ Brush (V) 1019【简单最短路】)