C - Association for Control Over Minds(并查集维护额外信息)

用并查集来合并成功合成的一组药材,并且维护该组中药材一共有多少种药材,在之后遍历过程中我们统计每一组要求的每种药材在哪里出现过,并且将他们所出现的组的药材数量累加,如果累加数和当前要求数相同,说明每一种药材在之前都出现过,只需将这些组全部合并即可。

应为多个药材可能有相同父节点,所以用vector进行去重。

#include <iostream>
#include <cstring>
#include <algorithm>
#include <sstream>
#include <cmath>
#include <queue>
#include <bitset>
#include <vector>
#include <map>
#define int long long
#define endl '\n'
#define lowbit(x) x &(-x)
#define mh(x) memset(x, -1, sizeof h)
#define debug(x) cerr << #x << "=" << x << endl;
#define brk exit(0);
using namespace std;
void TLE() { ios::sync_with_stdio(false), cin.tie(0), cout.tie(0); }
const int N = 5e5 + 10;
const int M = 2 * N;
const int mod = 80112002;
const double esp = 1e-6;
const double pi = acos(-1);
typedef pair<int, int> PII;
typedef long long ll;
int e[N], ne[N], h[N], cnt;
int din[N], dout[N];
int n, m;
inline int read()
{
    register int x = 0, f = 1;
    register char c = getchar();
    while (c < '0' || c > '9')
    {
        if (c == '-')
            f = -1;
        c = getchar();
    }
    while (c >= '0' && c <= '9')
        x = (x << 3) + (x << 1) + (c ^ 48), c = getchar();
    return x * f;
}
inline void write(register int x)
{
    if (x > 9)
        write(x / 10);
    putchar(x % 10 + '0');
}
int p[N], Size[N];
int find(int x)
{
    if (x != p[x])
        p[x] = find(p[x]);
    return p[x];
}
void init()
{
    for (int i = 0; i <= N; i++)
    {
        p[i] = i;
        Size[i] = 1;
    }
}
void merge(int a, int b)
{
    a = find(a), b = find(b);
    if (a != b)
    {
        p[a] = p[b];
        Size[b] += Size[a];
    }
}
signed main()
{
    int T, ans = 0;
    cin >> T;
    init();
    while (T--)
    {
        vector<int> cnt;
        int n;
        cin >> n;
        for (int i = 1; i <= n; i++)
        {
            int x;
            cin >> x;
            cnt.push_back(find(x));
        }
        sort(cnt.begin(), cnt.end());
        cnt.erase(unique(cnt.begin(), cnt.end()), cnt.end());
        int res = 0;
        for (auto t : cnt)
        {
            res += Size[t];
        }
        if (res == n)
        {
            ans++;
            for(auto t:cnt)
            {
                merge(cnt[0], t);
            }
        }
    }
    cout << ans << endl;
    return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值