Luogu P1195 Pocket Sky (Minimal Spanning Tree)

Topic background

Kosugi sat in the classroom, looking through the pocket-like windows through the pocket-like windows.

There are a lot of clouds floating there, and they look very beautiful. Kosugi wants to take off such beautiful clouds and make them into marshmallows.

Title description

Give you the number of clouds NN N, and then give you MM M relationships, which indicate which clouds can be connected together.

Now Xiaoshan wants to connect all the clouds into KK K marshmallows. One marshmallow needs to use at least one cloud. Xiaoshan wants to know how he connects them, and it costs the least.

Input format

For each set of test data

第一 行 有 三个 数N, M, K (1≤N≤1000,1≤M 100 10000,1 K K 10 10) N, M, K (1 \ le N \ le 1000,1 \ le M \ le 10000.1 \ le K \ le 10) N , M , K ( 1 N 1 0 0 0 , 1 M 1 0 0 0 0 , 1 K 1 0 )

Next, the MM M lines each three numbers X-, the Y, LX, the Y, L X- , the Y , L, represents XX X-cloud and YY the Y cloud by LL together L price. (1≤X, Y≤N, 0≤L <10000) (1 \ le X, Y \ le N, 0 \ le L <10000) ( 1 X , Y N , 0 L < 1 0 0 0 0 )

30% 30 \% 3 0 % of data N≤100, M≤1000N \ le 100, M \ le 1000 N 1 0 0 , M 1 0 0 0

Output format

There is only one integer for each row of data output, which represents the minimum cost.

If you can't even get KK K marshmallows, please output 'No Answer'.

Sample input and output

Enter # 1
3 1 2
1 2 1
Output # 1

The meaning of question 1 is to divide a graph into k connected blocks, and ask how to connect edges to minimize the total edge weight.
First find the minimum spanning tree, so as to ensure that all nodes are connected. At this time, dividing n points into k connected blocks only needs to break k-1 edges, and greedily choose the largest k-1 edge to break. .
#include <bits/stdc++.h>
using namespace std;
int fa[1005];
int n,m,k;
struct edge
{
    int x,y,z;
}e[10005];
bool cmp(edge a,edge b)
{
    return a.z<b.z;
}
int get(int x)
{
    if(x==fa[x])return x;
    return fa[x]=get(fa[x]);
}
int main()
{
    int i,ans=0,cnt=0;
    scanf("%d%d%d",&n,&m,&k);
    for(i=1;i<=n;i++)fa[i]=i;
    for(i=1;i<=m;i++)
    {
        int x,y,l;
        scanf("%d%d%d",&x,&y,&l);
        e[i].x=x,e[i].y=y,e[i].z=l;
    }
    sort(e+1,e+m+1,cmp);
    for(i=1;i<=m;i++)
    {
        int x=get(e[i].x),y=get (e [i] .y);
         if (x == y) continue ; 
        fa [x] = y; 
        cnt ++ ;
         if (cnt <= nk) // The minimum spanning tree has n-1 edges 
        { 
            ans + = e [i] .z; 
        } 
    } 
    cout << ans << endl;
     return  0 ; 
}

 



Guess you like

Origin www.cnblogs.com/lipoicyclic/p/12716992.html