使用 set_intersection() 判断两个集合之间重复元素,时间复杂度最坏O(nlogn),最好O(n)
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, m;
cin >> n >> m;
vector<set<int> > res(m+1);
for(int i = 1; i <= n; ++ i)
{
int k;
scanf("%d",&k);
for(int j = 1; j <= k; ++ j)
{
int m;
scanf("%d",&m);
res[m].insert(i);
}
}
int q;
cin >> q;
for(int i = 1; i <= q; ++ i)
{
int a, b;
scanf("%d%d",&a,&b);
vector<int> cnt;
set_intersection(res[a].begin(), res[a].end(),
res[b].begin(), res[b].end(), back_inserter(cnt));
// set_intersection(res[a].begin(), res[a].end(),
// res[b].begin(), res[b].end(), inserter(cnt,cnt.end()));
printf("%d\n",cnt.size());
}
return 0;
}
标签:cnt,set,end,int,res,begin,L2,049,鱼与熊掌
From: https://www.cnblogs.com/Frodnx/p/18400724