TOJ1049 Jesse's problem

Jesse's problem 分享至QQ空间 去爱问答提问或回答

Time Limit(Common/Java):1000MS/10000MS     Memory Limit:65536KByte
Total Submit: 31            Accepted: 15

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 <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <vector>
#include <cstring>
using namespace std;
const int INF = 0x7fffffff;
const int maxn = 310;

int gn, gm;
vector<pair<int, int> > g[maxn+10];
bool inque[maxn+10];
queue<int> Q;

void spfa(int s, int d[]) {
    int i;
    for(i = 1; i < maxn; i++) d[i] = INF;
    d[s] = 0;
    while(!Q.empty()) Q.pop();
    Q.push(s);
    inque[s] = true;
    while(!Q.empty()) {
        int u = Q.front();
        Q.pop();
        for(i = 0; i < (int)g[u].size(); i++) {
            int t = g[u][i].first;
            if(d[u] + g[u][i].second < d[t]) {
                d[t] = d[u] + g[u][i].second;
                if(!inque[t]) {
                    inque[t] = true;
                    Q.push(t);
                }
            }
        }
        inque[u] = false;
    }
}

void init() {
    int i;
    for(i = 1; i <= gn; i++) {
        g[i].clear();
    }
}

int main()
{
    int i;
    int u, v, w;
    int d[maxn];
    pair<int, int> t;
    while(scanf("%d%d", &gn, &gm) != EOF) {
        init(); //清空容器.
        for(i = 1; i <= gm; i++) {
            scanf("%d%d%d", &u, &v, &w);
            t.first = v;
            t.second = w;
            g[u].push_back(t);
            t.first = u;
            t.second = w;
            g[v].push_back(t);
        }
        int s, t;
        scanf("%d%d", &s, &t);
        spfa(s, d);
        if(d[t] == INF) printf("-1\n");
        else printf("%d\n", d[t]);
    }
    return 0;
}

你可能感兴趣的:(TOJ1049 Jesse's problem)