LightOJ - 1019 Brush (V)

Description

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 junction u and v and the distance is w. You can assume that Tanvir lives in the 1st junction and Atiq lives in the Nthjunction. 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

2

 

3 2

1 2 50

2 3 10

 

3 1

1 2 40

Sample Output

Case 1: 60

Case 2: Impossible


題解,Tanvir到Atiq家的通過給定路線數據求最短距離  。最短路問題,用dijkstra算法,做題一直沒有A到時因爲:以爲路徑一直小於1010,我笑了!!!!



#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

int n,m,U,V,W;
int d[110];
bool v[110];
int w[110][110];

void dijkstra(int start,int endx){
    memset(v,false,sizeof(v));
    for(int i = 1; i <= n; i++) d[i] = (i==start? 0 : w[start][i]);
    v[start] = true;
    for(int i = 1; i <= n; i++){
        int x,m = 0x3fffffff;
        for(int y = 1; y<=n;y++) if(!v[y] && d[y]<m) m=d[x=y];
        if (m == 0x3fffffff) break;
        v[x] = true;
        for(int y = 1; y<=n;y++) d[y] = min(d[y],d[x]+w[x][y]);
    }
}

int main(){
    int T;
    cin>>T;
    for(int i = 1; i <= T; i++){
        cin>>n>>m;
        for(int i  = 0; i <= n;i++)
            for(int j = 0; j <= n;j++)w[i][j] = 0x3fffffff;
        while(m--){
            cin>>U>>V>>W;
            if(w[U][V]>W) w[U][V]=w[V][U]=W;
        }
        dijkstra(1,n);
        d[n] != 0x3fffffff?printf("Case %d: %d\n",i,d[n]):printf("Case %d: Impossible\n",i);
    }
    return 0;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章