P1194 买礼物【kruskal】

题目

https://www.luogu.com.cn/problem/P1194

 思路

如果有优惠才建边,而且在kruskal判断的过程中,如果优惠的价钱比原价低才算

代码

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
using namespace std;
#define maxn 10002
#define maxm 10002
struct node
{
    int from;
    int to;
    int dis;
}e[maxm * 2];
int edges[maxn][maxn];
int aa, bb,cnt=0;
int father[maxn];
bool cmp(struct node &a, struct node &b)
{
    return a.dis < b.dis;
}
int find(int x)
{
    if (father[x] == x)return x;
    return father[x] = find(father[x]);
}
int allcount = 0;
void kruskal()
{
    sort(e, e + cnt, cmp);
    for (int i = 0; i < cnt; i++)
    {
        int tempx = find(e[i].from);
        int tempy = find(e[i].to);
        if (tempx == tempy)continue;
        father[tempx] = tempy;
        if(e[i].dis<aa)
        allcount += e[i].dis;
        else allcount += aa;
    }
}

int main()
{
    scanf("%d%d", &aa, &bb);
    for (int i = 0; i < bb; i++)
        for (int j = 0; j < bb; j++)
        {
            scanf("%d", &edges[i][j]);
        }
    for (int i = 0; i <= bb; i++)father[i] = i;

    for (int i = 0; i < bb; i++)
    {
        for (int j = 0; j < i; j++)
        {
            if (edges[i][j]>0)
            {
                e[cnt].from = j;
                e[cnt].to = i;
                e[cnt++].dis = edges[i][j];
            }
        }
    }
    kruskal();
    printf("%d", allcount+aa);

}
原文地址:https://www.cnblogs.com/Jason66661010/p/13196121.html