用并查集来合并成功合成的一组药材,并且维护该组中药材一共有多少种药材,在之后遍历过程中我们统计每一组要求的每种药材在哪里出现过,并且将他们所出现的组的药材数量累加,如果累加数和当前要求数相同,说明每一种药材在之前都出现过,只需将这些组全部合并即可。
应为多个药材可能有相同父节点,所以用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;
}