zoukankan      html  css  js  c++  java
  • 洛谷 P1396 营救

    题目

    P1396 营救

    思路

    并查集,将读入的边按拥挤度从小到大排序,一开始(s)(t)在不同的集合中,然后从小到大枚举每一条边,如果这条边的起点与终点不在同一集合内(不连通),就合并,每合并一次判断(s)(t)是否在同一集合内(连通),如果(s)(t)连通了,当前边的拥挤度就是答案。

    (Code)

    #include<iostream>
    #include<cstring>
    #include<string>
    #include<cstdio>
    #include<algorithm>
    #define MAXN 10001
    using namespace std;
    int n,m,s,t,fa[MAXN],r[MAXN];
    struct info{
    	int u,v,c;
    }a[MAXN<<2];
    bool cmp(info a,info b){
    	return a.c<b.c;
    }
    int find(int x){
    	return fa[x]==x?x:fa[x]=find(fa[x]);
    }
    void Union(int x,int y){
    	int rootx=find(x),rooty=find(y);
    	if(rootx==rooty) return;
    	if(r[rootx]>r[rooty]) fa[rooty]=rootx;
    	else if(r[rooty]>r[rootx]) fa[rootx]=rooty;
    	else{
    		fa[rootx]=rooty;
    		r[rooty]++;
    	}
    }
    inline int read(){
    	int x=0;bool f=0;char c=getchar();
    	while(c<'0'||c>'9'){if(c=='-')f=!f;c=getchar();}
    	while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}
    	return f?-x:x;
    }
    
    int main(){
    	n=read(),m=read(),s=read(),t=read();
    	for(int i=1;i<=n;++i) fa[i]=i;
    	for(int i=1;i<=m;++i) a[i].u=read(),a[i].v=read(),a[i].c=read();
    	sort(a+1,a+m+1,cmp);
    	for(int i=1;i<=m;++i){
    		if(find(a[i].u)!=find(a[i].v)){
    			Union(a[i].u,a[i].v);
    			if(find(s)==find(t)){
    				printf("%d
    ",a[i].c);
    				return 0;
    			}
    		}
    	}
    	return 0;
    }
    
  • 相关阅读:
    Math 和 Date
    GRID布局
    移动端项目布局类型
    媒体查询 + rem用法
    字符串
    ES5 中常见的数组常用方法
    数组的排序
    毕设制作:前端界面 2020-02-01
    阅读笔记十六——排序算法
    阅读笔记十五——阿里面试题
  • 原文地址:https://www.cnblogs.com/poi-bolg-poi/p/11440205.html
Copyright © 2011-2022 走看看