我对CF584D题 Cow and Snacks的认识

文章讲述了如何使用并查集数据结构解决一个餐厅菜品分配问题,确保每位客人都能吃到至少一种之前没有人吃过的菜品,避免形成环路导致某些人无法满足。作者提供了代码示例和思考过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考了一下CF官方给的题解,并结合自己的做题感悟,主要考察普通并查集,图的连通性。

定义一个数量数组shu【100010】,记录每种菜被吃了几次;定义ans,记录不能满足的客人数。

我是这样思考的,不需要dp什么的,顺序请客人,当他的口味

1.至少一种之前还没有人吃过,那么他可以吃没人吃的那个,肯定能做到不让他失望。之后把那两种菜的shu数组值各自加一,并查集并到一块去。

2.两种之前都被人吃过,但并查集的值不一样,也是可以的,读者可以想象成一个链,第一个人吃两个,后续每一个人吃一个。之后把那两种菜的shu数组值各自加一,并查集并到一块去。

3.唯一的一种不能满足的情况,两种之前都被人吃过,但并查集的值一样,这就相当于链成了环,最后一个人吃不到东西,这种情况ans++。

代码如下:

#include<iostream>
using namespace std;
#include<set>
#include<algorithm>
#include<cmath>
#include<map>
#include<cstdio>
#include<string>
#include<cstring>
#include<string.h>
#include<stdlib.h>
#include<iomanip>
#include<fstream>
#include<stdio.h>
#include<stack>
#include<queue>
#include<ctype.h>
#include<vector>
#define lowbit(x) (x&(-x))
#define inf 1e8
inline int read()//快读模板
{
    bool flag = false; int x = 0;
    char ch = getchar();
    while (ch < '0' || ch > '9')
    {
        if (ch == '-') flag = true;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9')
    {
        x = (x << 1) + (x << 3) + ch - '0';
        ch = getchar();
    }
    return flag ? -x : x;
}
int dir[5][3] =
{
    {0,1},{0,-1},{1,0},{-1,0}
};
//
int n, k, i, j, ans;
int shu[100010], cha[100010];
int find(int x)//一条路径上的点全部更新了cha[ ]值
{
    int i = x, j;
    while (cha[x] != x)
    {
        x = cha[x];
    }
    while (i != x)
    {
        j = cha[i];
        cha[i] = x;
        i = j;
    }
    return x;
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
    cin >> n >> k;
    for (i = 1; i <= n; i++)
    {
        cha[i] = i;
    }
    for (i = 1; i <= k; i++)
    {
        int x, y;
        cin >> x >> y;

        if ((shu[x]==0||shu[y]==0)||shu[x]&&shu[y]&&find(x)!=find(y))//这个地方一定是find()比较,cha[ ]比较是不准的,值可能没有更新
        {
            int rootx = find(x), rooty = find(y);
            shu[x]++;
            shu[y]++;
            cha[rootx] = rooty;//一定是一个并查集的根插到另一个根上面去,保证两个集指向的根相等
        }       
        else 
        {
            ans++;
        }
    }
    cout << ans;
}

限于笔者水平不够,如有不当,欢迎批评指正。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值