标签:
[BZOJ1529][POI2005]ska Piggy banks
试题描述
输入
输出
输入示例
4 2 1 2 4
输出示例
2
数据规模及约定
见“输入”
题解
加边找连通块个数。
#include <iostream> #include <cstdio> #include <algorithm> #include <cmath> #include <stack> #include <vector> #include <queue> #include <cstring> #include <string> #include <map> #include <set> using namespace std; const int BufferSize = 1 << 16; char buffer[BufferSize], *Head, *Tail; inline char Getchar() { if(Head == Tail) { int l = fread(buffer, 1, BufferSize, stdin); Tail = (Head = buffer) + l; } return *Head++; } int read() { int x = 0, f = 1; char c = Getchar(); while(!isdigit(c)){ if(c == ‘-‘) f = -1; c = Getchar(); } while(isdigit(c)){ x = x * 10 + c - ‘0‘; c = Getchar(); } return x * f; } #define maxn 1000010 int n, fa[maxn], pos[maxn]; int findset(int x) { return x == fa[x] ? x : fa[x] = findset(fa[x]); } int main() { n = read(); for(int i = 1; i <= n; i++) fa[i] = i; for(int i = 1; i <= n; i++) { int u = findset(i), v = findset(read()); if(u != v) fa[v] = u; } for(int i = 1; i <= n; i++) pos[i] = findset(i); sort(pos + 1, pos + n + 1); int cnt = 0; for(int i = 1; i <= n; i++) if(i == 1 || pos[i] != pos[i-1]) cnt++; printf("%d\n", cnt); return 0; }
[BZOJ1529][POI2005]ska Piggy banks
标签:
原文地址:http://www.cnblogs.com/xiao-ju-ruo-xjr/p/5724535.html