【解题报告】luogu P2078 朋友

题目:luogu P2078

题目思路:

并查集,C++ STL

有了C++stl容器,我们就high了,map可以处理数组下标为负的情况,然后男女朋友的关系的话,就分别统计每个公司有多少人有关系,取一个最小值就好了

AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <map>
using namespace std;
map<int,int>f;
int n,m,p,q;
int fm,fh;
int max(int a,int b)
{
return a<b? a:b;
}
int get(int x)
{
return f[x]=(x==f[x]? x:get(f[x]));
}
void merge(int x,int y)
{
f[get(x)]=get(y);
}
int main()
{
int x,y;
cin>>n>>m>>p>>q;
for(int i=(-1*m);i<=n;i++)
f[i]=i;
for(int i=1;i<=p+q;i++)
{
cin>>x>>y;
merge(x,y);
}
for(int i=1;i<=n;i++)
{
if(get(f[i])==get(1))
fm++;
}
for(int i=(-1*m);i<=-1;i++)
{
if(get(f[i])==get(-1))
fh++;
}
cout<<max(fm,fh)<<endl;
return 0;
}