zoukankan      html  css  js  c++  java
  • P1195 口袋的天空 (生成树)

    题目链接

    解法:

    初始n个节点,n颗树,每连一条边,减少一棵树。k棵树需要连n-k条边。。。1棵树需要连n-1条边。。。

    给每条可以连的边按代价从小到大排个序,然后连n-k条边造k个最小生成树就可以了。

    Code:

     1 #include <bits/stdc++.h>
     2 # define LL long long
     3 using namespace std;
     4 
     5 const int maxn=1000+10;
     6 const int maxm=10000+10;
     7 int parent[maxn];
     8 int N, M, K;
     9 
    10 struct Edge{
    11     int u,v,w;
    12 }e[maxm];
    13 
    14 int find(int p){
    15     if(p==parent[p]) return p;
    16     parent[p]=find(parent[p]);
    17     return parent[p];
    18 }
    19 
    20 int main(){
    21     scanf("%d %d %d", &N, &M, &K);
    22     for(int i=1;i<=N;++i){
    23         parent[i]=i;
    24     }
    25     for(int i=1;i<=M;++i){
    26         int u,v,w;
    27         scanf("%d %d %d", &e[i].u, &e[i].v, &e[i].w);
    28     }
    29     sort(e+1,e+M+1,[](Edge e1, Edge e2){
    30         return e1.w<e2.w;
    31     });
    32     int res=0;
    33     int cnt=0;
    34     for(int i=1;i<=M;++i){
    35         int u=e[i].u;
    36         int v=e[i].v;
    37         if(find(u)==find(v)) continue;
    38         cnt++;
    39         res+=e[i].w;
    40         parent[find(u)]=find(v);
    41         if(cnt==N-K){
    42             printf("%d", res);
    43             return 0;
    44         }
    45     }
    46     printf("No Answer");
    47     return 0;
    48 }
  • 相关阅读:
    CentOS配置bond
    rsync 06-sersync文件实时同步
    rsync 07-confxml.xml配置文件
    rsync 04-rsyncd启动脚本
    rsync 03-rsyncd.conf配置文件
    rsync 01-rsync命令使用
    rsync 02-部署rsync的daemon模式
    CentOS7升级OpenSSH
    iptables 02-CentOS7.x 启用iptables
    iptables 01-iptables命令
  • 原文地址:https://www.cnblogs.com/FEIIEF/p/12246104.html
Copyright © 2011-2022 走看看