【并查集】【模拟】Codeforces 698B & 699D Fix a Tree

题目链接:

  http://codeforces.com/problemset/problem/698/B

  http://codeforces.com/problemset/problem/699/D

题目大意:

  通过给定当前节点的父亲给你一棵有错的树,可能有多个根和环,输出改成正确的一棵树至少要修改几个节点的父亲和修改后所有点的父亲值

题目思路:

  【并查集】【模拟】

  用并查集把成环的归在一起(类似强连通分量),然后统计分量数并修改。

  第一个出现的当作根,其余的每一块连通分量都去掉一条边改为连接到根上。

 

 1 //
 2 //by coolxxx
 3 ////<bits/stdc++.h>
 4 #include<iostream>
 5 #include<algorithm>
 6 #include<string>
 7 #include<iomanip>
 8 #include<map>
 9 #include<memory.h>
10 #include<time.h>
11 #include<stdio.h>
12 #include<stdlib.h>
13 #include<string.h>
14 //#include<stdbool.h>
15 #include<math.h>
16 #define min(a,b) ((a)<(b)?(a):(b))
17 #define max(a,b) ((a)>(b)?(a):(b))
18 #define abs(a) ((a)>0?(a):(-(a)))
19 #define lowbit(a) (a&(-a))
20 #define sqr(a) ((a)*(a))
21 #define swap(a,b) ((a)^=(b),(b)^=(a),(a)^=(b))
22 #define mem(a,b) memset(a,b,sizeof(a))
23 #define eps (1e-8)
24 #define J 10
25 #define MAX 0x7f7f7f7f
26 #define PI 3.14159265358979323
27 #define N 200004
28 using namespace std;
29 typedef long long LL;
30 int cas,cass;
31 int n,m,lll,ans;
32 int root;
33 int a[N],fa[N];
34 int zhao(int aa)
35 {
36     if(fa[aa]==0 || fa[aa]==aa)return aa;
37     return (fa[aa]=zhao(fa[aa]));
38 }
39 int main()
40 {
41     #ifndef ONLINE_JUDGE
42     freopen("1.txt","r",stdin);
43 //    freopen("2.txt","w",stdout);
44     #endif
45     int i,j,fx,fy;
46 //    for(scanf("%d",&cas);cas;cas--)
47 //    for(scanf("%d",&cas),cass=1;cass<=cas;cass++)
48     while(~scanf("%d",&n))
49 //    while(~scanf("%d",&n))
50     {
51         mem(fa,0);ans=0;root=0;
52         for(i=1;i<=n;i++)
53         {
54             scanf("%d",&a[i]);
55             if(a[i]==i)root=i;
56             fx=zhao(a[i]);
57             fy=zhao(i);
58             if(fx!=fy)
59                 fa[fy]=fx;
60         }
61         for(i=1;i<=n;i++)
62         {
63             fa[i]=zhao(i);
64             if(fa[i]==i)
65             {
66                 if(!root)
67                 {
68                     ans++;
69                     root=i;
70                     a[i]=i;
71                 }
72                 else if(i!=root)
73                     ans++,a[i]=root;
74             }
75         }
76         printf("%d\n",ans);
77         for(i=1;i<=n;i++)
78             printf("%d ",a[i]);
79         puts("");
80     }
81     return 0;
82 }
83 /*
84 //
85 
86 //
87 */
View Code

 

posted @ 2016-08-19 00:43  Cool639zhu  阅读(216)  评论(0编辑  收藏  举报