题目链接:https://www.tyvj.cn/Problem_Show.aspx?id=1017

并查集

 1 #include <cstdio>
 2 #include <cstdlib>
 3 using namespace std;
 4 int parent[1001],n,m;
 5 void init() {for(int i=1;i<=m;++i)parent[i]=-1; }
 6 int Find(int x) {int s; for(s=x;parent[s]>=0;s=parent[s]);while (s!=x) {int tmp=parent[x];parent[x]=s;x=tmp; }return s; }
 7 void Union(int R1,int R2)
 8 {
 9     int r1=Find(R1),r2=Find(R2),tmp=parent[r1]+parent[r2]; if (parent[r1]<parent[r2]) parent[r2]=r1,parent[r1]=tmp;
10     else parent[r1]=r2,parent[r2]=tmp;
11 }
12 int main(void)
13 {
14     freopen("in1.txt","r",stdin);
15     int cnt=0;scanf("%d%d",&n,&m); init();
16     while (n--) {
17         int a,b; scanf("%d%d",&a,&b); if(Find(a)==Find(b)) cnt++;
18         else Union(a,b);
19     } printf("%d\n",cnt);
20     return 0;
21 }

=_=

相关文章:

  • 2021-11-26
  • 2021-08-29
  • 2021-12-30
  • 2021-06-20
  • 2022-12-23
  • 2021-12-15
  • 2021-10-03
  • 2021-10-13
猜你喜欢
  • 2021-07-28
  • 2022-12-23
  • 2022-12-23
  • 2021-06-21
  • 2022-12-23
  • 2021-06-17
  • 2021-12-07
相关资源
相似解决方案