题意:给定n个数,Ai的下标为1~n。对于每一个i,Ai与i在同一个树上,且是与i最远的点中id最小的点(这个条件变相的说明i与Ai连通)。求森林中树的个数。
分析:若i与Ai连通,则在同一个树上,因此连通块的个数就是树的个数。并查集即可。
#pragma comment(linker, "/STACK:102400000, 102400000") #include<cstdio> #include<cstring> #include<cstdlib> #include<cctype> #include<cmath> #include<iostream> #include<sstream> #include<iterator> #include<algorithm> #include<string> #include<vector> #include<set> #include<map> #include<stack> #include<deque> #include<queue> #include<list> #define Min(a, b) ((a < b) ? a : b) #define Max(a, b) ((a < b) ? b : a) typedef long long ll; typedef unsigned long long llu; const int INT_INF = 0x3f3f3f3f; const int INT_M_INF = 0x7f7f7f7f; const ll LL_INF = 0x3f3f3f3f3f3f3f3f; const ll LL_M_INF = 0x7f7f7f7f7f7f7f7f; const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1}; const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1}; const int MOD = 1e9 + 7; const double pi = acos(-1.0); const double eps = 1e-8; const int MAXN = 10000 + 10; const int MAXT = 10000 + 10; using namespace std; int fa[MAXN]; int a[MAXN]; set<int> s; int Find(int v){ return fa[v] = (fa[v] == v) ? v : Find(fa[v]); } int main(){ for(int i = 0; i < MAXN; ++i){ fa[i] = i; } int n; scanf("%d", &n); for(int i = 1; i <= n; ++i){ scanf("%d", &a[i]); int tx = Find(i); int ty = Find(a[i]); if(tx < ty) fa[ty] = tx; else fa[tx] = ty; } for(int i = 1; i <= n; ++i){ if(Find(i) == i) s.insert(i); if(Find(a[i]) == a[i]) s.insert(a[i]); } printf("%d\n", s.size()); return 0; }