BZOJ 1050: [HAOI2006]旅行comf( 并查集 )

-----------------------------------------------------------------------------------------

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>

#define rep( i , n ) for( int i = 0 ; i < n ; ++i )
#define clr( x , c ) memset( x , c ,sizeof( x ) )

using namespace std;

const int maxn = 500 + 5;
const int maxm = 5000 + 5;

int n;

int gcd( int a , int b ) {
return b ? gcd( b , a % b ) : a;
}

struct edge {
int u , v , d;
scanf( "%d%d%d" , &u , &v , &d );
u-- , v--;
}
bool operator < ( const edge &e ) const {
return d < e.d;
}
};

int p[ maxn ];

inline void UF_init() {
rep( i , n ) p[ i ] = i;
}

int find( int x ) {
return x == p[ x ] ? x : p[ x ] = find( p[ x ] );
}

edge E[ maxm ];

int main() {

int m;
cin >> n >> m;
rep( i , m ) E[ i ].Read();
int s , t;
cin >> s >> t;
s-- , t--;
sort( E , E + m );
pair< int , int > ans( -1 , -1 );
rep( i , m ) {
UF_init();
int Min = E[ i ].d , Max;
for( int j = i ; j < m ; ++j ) {
int a = find( E[ j ].u ) , b = find( E[ j ].v );
if( a != b )
p[ a ] = b , Max = E[ j ].d;

if( find( s ) == find( t ) ) {
if( ans.first * 1.0 / ans.second > Max * 1.0 / Min || ans.first == -1)
ans = make_pair( Max , Min );
break;
}
}
}
if( ans.first == -1 )
printf( "IMPOSSIBLE\n" );
else {
int a = ans.first , b = ans.second;
int c = gcd( a , b );
if( c == b )
printf( "%d\n" , a / b );
else
printf( "%d/%d\n" , a / c , b / c );
}
return 0;
}

-----------------------------------------------------------------------------------------

1050: [HAOI2006]旅行comf

Time Limit: 10 Sec  Memory Limit: 162 MB
Submit: 1775  Solved: 898
[Submit][Status][Discuss]

【样例输入1】
4 2
1 2 1
3 4 2
1 4
【样例输入2】
3 3
1 2 10
1 2 5
2 3 8
1 3
【样例输入3】
3 2
1 2 2
2 3 4
1 3

【样例输出1】
IMPOSSIBLE
【样例输出2】
5/4
【样例输出3】
2

HINT

【数据范围】

1<  N < = 500

1 < = x, y < = N，0 < v < 30000，x ≠ y

0 < M < =5000

Source

posted @ 2015-05-31 14:51  JSZX11556  阅读(112)  评论(0编辑  收藏