BZOJ 1050 旅行(并查集)

很好的一道题。。

首先把边权排序。然后枚举最小的边,再依次添加不小于该边的边,直到s和t联通。用并查集维护即可。

# include <cstdio>
# include <cstring>
# include <cstdlib>
# include <iostream>
# include <vector>
# include <queue>
# include <stack>
# include <map>
# include <set>
# include <cmath>
# include <algorithm>
using namespace std;
# define lowbit(x) ((x)&(-x))
# define pi acos(-1.0)
# define eps 1e-
# define MOD
# define INF
# define mem(a,b) memset(a,b,sizeof(a))
# define FOR(i,a,n) for(int i=a; i<=n; ++i)
# define FO(i,a,n) for(int i=a; i<n; ++i)
# define bug puts("H");
# define lch p<<,l,mid
# define rch p<<|,mid+,r
# define mp make_pair
# define pb push_back
# define set pabs
typedef pair<int,int> PII;
typedef vector<int> VI;
# pragma comment(linker, "/STACK:1024000000,1024000000")
typedef long long LL;
int Scan() {
int res=, flag=;
char ch;
if((ch=getchar())=='-') flag=;
else if(ch>=''&&ch<='') res=ch-'';
while((ch=getchar())>=''&&ch<='') res=res*+(ch-'');
return flag?-res:res;
}
void Out(int a) {
if(a<) {putchar('-'); a=-a;}
if(a>=) Out(a/);
putchar(a%+'');
}
const int N=;
//Code begin...
typedef struct{int u, v, w;}Node;
Node edge[];
int fa[N]; bool comp(Node a, Node b){return a.w<b.w;}
int find(int x)
{
int s, temp;
for (s=x; fa[s]>=; s=fa[s]) ;
while (s!=x) temp=fa[x], fa[x]=s, x=temp;
return s;
}
void union_set(int x, int y)
{
int temp=fa[x]+fa[y];
if (fa[x]>fa[y]) fa[x]=y, fa[y]=temp;
else fa[y]=x, fa[x]=temp;
}
int gcd(int x, int y){return y?gcd(y,x%y):x;}
int main ()
{
int n, m, u, v, mi, ma, s, t, ans[];
double answer=INF;
scanf("%d%d",&n,&m);
FOR(i,,m) scanf("%d%d%d",&edge[i].u,&edge[i].v,&edge[i].w);
scanf("%d%d",&s,&t);
sort(edge+,edge+m+,comp);
FOR(i,,m) {
mem(fa,-);
mi=edge[i].w; ma=;
FOR(j,i,m) {
u=edge[j].u, v=edge[j].v;
if (find(u)!=find(v)) union_set(find(u),find(v));
if (find(s)==find(t)) {ma=edge[j].w; break;}
}
if (ma) if (answer>(double)ma/mi) answer=(double)ma/mi, ans[]=ma/gcd(ma,mi), ans[]=mi/gcd(ma,mi);
}
if (fabs(answer-INF)<eps) puts("IMPOSSIBLE");
else {
if (ans[]==) printf("%d\n",ans[]);
else printf("%d/%d\n",ans[],ans[]);
}
return ;
}
上一篇:BZOJ 1050 旅行


下一篇:Spring Boot2.0之注解方式启动Springmvc