zoukankan      html  css  js  c++  java
  • 洛谷 P1340 兽径管理

    这道题也就是一个在线的最小生成树(虽然可以转化为离线但是懒嘛),因为给的是边,那么就是Kruskal算法了。由于在求解中需要排序,而因为序列本身是有序时插入一个数据,那么我们就可以直接用插入排序的思想做。

    代码:

    #include <bits/stdc++.h>
    using namespace std;
    struct node{
    	int l , r , w;
    };
    vector<node> e;
    int n , m , now , tot , ans;
    int fa[210];
    int find(int x){
    	if(fa[x] == x) return x;
    	return fa[x] = find(fa[x]);
    }
    bool cmp(node x , node y){
    	return x.w < y.w;
    }
    int main(){
    	cin >> n >> m;
    	while(m--){
    		int xx , yy , zz;
    		tot++;
    		cin >> xx >> yy >> zz;
    		int k = 0;
    		for(int i = 0; i < tot - 1; i++){
    			if(zz < e[i].w) break;
    			k++;
    		}
    		node bzzs;
    		bzzs.l = xx , bzzs.r = yy , bzzs.w = zz; 
    		e.insert(e.begin() + k , bzzs);
    		if(tot < n - 1){
    			cout << -1 << endl;
    			continue;
    		}
    		for(int i = 1; i <= n; i++) fa[i] = i;
    		now = 0 , ans = 0;
    		for(int i = 1; i <= tot; i++){
    			if(now == n - 1) break;
    			int x = find(e[i - 1].l) , y = find(e[i - 1].r);
    			if(x == y) continue;
    			now++;
    			ans += e[i - 1].w;
    			fa[x] = y;
    		}
    		if(now != n - 1) cout << -1 << endl;
    		else cout << ans << endl;
    	}
    	return 0;
    }
    
  • 相关阅读:
    凯撒密文的破解编程实现
    微软ping命令的源代码
    从编程到入侵
    永远的后门
    永远的后门
    奇妙的Base64编码
    用端口截听实现隐藏嗅探与攻击(二)
    奇妙的Base64编码
    Liferea 1.1.2
    Equinox Desktop Environment 1.1
  • 原文地址:https://www.cnblogs.com/bzzs/p/13204943.html
Copyright © 2011-2022 走看看