跳到正文

题解

题解 P1195 【口袋的天空】

Kwork约 3 分钟
原文
文章信息与版本

文章信息

发布
2016年10月12日
收录
2025年12月12日
更新
2026年10月30日
篇幅
约 3 分钟
题目
P1195

版本

  1. v1当前

根据题面我们可以知道这是最小生成树的变形。

用克鲁斯卡尔算法,不断的连边,更新答案,直到剩余云朵数量达到要求,输出解即可。

克鲁斯卡尔的具体证明请自行google。

C++
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <vector>
#include <queue>
using namespace std;
const int maxn=1000+20,maxm=100000+20;
struct data{int u,v,w;};
data edge[maxm];
int n,m,k,ans=0,p[maxn];
void read(int &n){
    n=0;int f=1;
    char ch=getchar();
    while(ch<'0' || ch>'9'){
        if(ch=='-') f=-1;
        ch=getchar();
    }
    do{
        n=n*10+ch-'0';
        ch=getchar();
    }while(ch>='0' && ch<='9');
    n=n*f;
    return;
}
void write(int n){
    if(n<0){
        putchar('-');
        n=0-n;
    }
    if(n>=10) write(n/10);
    putchar((n % 10)+'0');
    return;
}
bool cmp(const data &x,const data &y){
    return x.w<y.w;
}
int find(int x){
    return x==p[x]? x:p[x]=find(p[x]);
}
int main(){
    read(n);read(m);read(k);
    for(int i=1;i<=m;i++){
        read(edge[i].u);read(edge[i].v);read(edge[i].w);
    }
    sort(edge+1,edge+m+1,cmp);
    int tot=0;
    for(int i=1;i<=n;i++) p[i]=i;
    for(int i=1;i<=m;i++){
        int x=find(edge[i].u);
        int y=find(edge[i].v);
        if(x!=y){
            p[x]=y;
            ans+=edge[i].w;
            tot++;
        }
        if(tot==(n-k)) break;
    }
    write(ans);
    return 0;
}
原文
存档评论1 条抓取于