HDU 1598--find the most comfortable road【併査集+列挙】

2915 ワード

find the most comfortable road
Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 4418    Accepted Submission(s): 1912
Problem Description
XX星には多くの都市があり、都市間では奇妙な高速道路SARS(Super Air Roam Structure---スーパーエアウォーク構造)を通じて交流が行われている.各SARSは上を走るFlycarに対して固定的なSpeedを制限している.また、XX星人はFlycarの「快適度」に対して特殊な要求を持っている.すなわち、乗る過程で最高速度と最低速度の差が小さいほど座るのが快適である.(SARSの制限速度の要求と理解して、flycarは瞬間的にスピードアップ/降速しなければならなくて、苦痛です)、
しかし、XX星人は时间にそんなに要求していません.都市间の最も快适な道を见つけてください.(SARSは双方向です).
 
Input
入力には、次のような複数のテストインスタンスが含まれます.
1行目には2つの正の整数n(1次の行は3つの正の整数StartCity,EndCity,speedであり、表面的にはStartCityからEndCityまでを示し、速度制限はspeedSARSである.speed<00000=10
次に正の整数Q(Q<11)であり、探索の個数を表す.
次にQ行には1行あたり2つの正の整数Start,Endがあり,探索の開始点を示す.
 
Output
各ルックアップには1行の印刷が必要であり、非負の整数のみが最適なルートの快適度の最も高速と最も低速の差を示す.始点と終点が到達できない場合、出力-1.
 
Sample Input

   
   
   
   
4 4 1 2 2 2 3 4 1 4 1 3 4 2 2 1 3 1 2

 
Sample Output

   
   
   
   
1 0

 
データが弱く、暴力列挙+そして調査集が過ぎた.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define inf 0x3f3f3f3f
using namespace std;

struct node
{
    int a,b,c;
};
node map[1100];

int cmp(node s1,node s2){
    return s1.c < s2.c;
}

int per[220];
int n,m;
int find(int x){
    if(per[x] == -1)
        return x;
    return per[x] = find(per[x]);  
}


int main (){
    while(scanf("%d %d", &n, &m)!=EOF){
        for(int i = 1; i <= m; ++i)
            scanf("%d %d %d", &map[i].a, &map[i].b, &map[i].c);
        sort(map + 1, map + 1 + m, cmp); 
        int Q;
        scanf("%d", &Q);
        int st,ed;      
        while(Q--){
        	int MIN = inf;
            scanf("%d %d",&st, &ed);
            for(int i = 1; i <= m; ++i){ //     ,                     ,                ,      -     
                memset(per, -1, sizeof(per));
                for(int j = i; j <= m; ++j){
                    int fa = find(map[j].a);
                    int fb = find(map[j].b);
                    if(fa != fb)
                        per[fb] = fa;
                    if(find(st) == find(ed)){
                        MIN = min(MIN, map[j].c - map[i].c);
                        break;
                    }
                }
            }
            if(MIN == inf)
                printf("-1
"); else printf("%d
", MIN); } } return 0; }