zoukankan      html  css  js  c++  java
  • 洛谷 P1396 营救(最小生成树)

    传送门


    解题思路

    两种方法:

    • 方法一:
      直接按照Kruskal的方法求最小生成树,求的过程中s和t刚刚联通时加的边的大小即为答案。

    • 方法二:
      先二分答案,然后跑一遍最短路,要求只能走边权小于二分值的边。

    AC代码

    #include<cstdio>
    #include<iostream>
    #include<cstring>
    #include<iomanip>
    #include<cmath>
    #include<algorithm>
    #include<queue>
    using namespace std;
    const int maxn=2e4+5;
    int n,m,s,t,fa[maxn],ans;
    struct node{
    	int u,v,w;
    }e[maxn];
    priority_queue<pair<int,int>,vector<pair<int,int> >,greater<pair<int,int> > > q; 
    int find(int x){
    	if(fa[x]==x) return x;
    	return fa[x]=find(fa[x]);
    }
    int main(){
    	ios::sync_with_stdio(false);
    	cin>>n>>m>>s>>t;
    	for(int i=1;i<=n;i++) fa[i]=i;
    	for(int i=1;i<=m;i++){
    		cin>>e[i].u>>e[i].v>>e[i].w;
    		q.push(make_pair(e[i].w,i));
    	}
    	while(find(s)!=find(t)){
    		ans=q.top().first;
    		int id=q.top().second;
    		if(find(e[id].u)!=find(e[id].v)){
    			fa[fa[e[id].u]]=fa[e[id].v];
    		}
    		q.pop();
    	}
    	cout<<ans;
        return 0;
    }
    
  • 相关阅读:
    spring retry注解
    安装mongodb并配置
    spring boot Hello World
    Linux命令echo
    Linux vi命令
    查看linux是ubuntu还是centos
    Linux系统时间, 硬件BIOS时间的校准与同步
    MySQL优化查询 5.7版本
    战略由谁来制定
    VS2015快捷键
  • 原文地址:https://www.cnblogs.com/yinyuqin/p/15328334.html
Copyright © 2011-2022 走看看