题目
We have a permutation of the integers from 1 through N, p1, p2, .., pN. We also have M pairs of two integers between 1 and N (inclusive), represented as (x1,y1), (x2,y2), .., (xM,yM). AtCoDeer the deer is going to perform the following operation on pp as many times as desired so that the number of i (1 ≤ i ≤ N) such that pi=i is maximized:
- Choose j such that 1 ≤ j ≤ M, and swap pxj and pyj.
Find the maximum possible number of i such that pi=i after operations.
Constraints
- 2 ≤ N ≤
- 1 ≤ M ≤
- p is a permutation of integers from 1 through N.
- 1 ≤ xj,yj ≤ N
- xj ≠ yj
- If i ≠ j, {xi,yi} ≠ {xj,yj}.
- All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M p1 p2 .. pN x1 y1 x2 y2 : xM yM
Output
Print the maximum possible number of i such that pi=i after operations.
思路
在题目所给的M对(x,y)中,我们可以用并查集将其构成若干个无向图,在每个无向图中,所有元素都可以实现交换,因此在p排列中,只要值为i的元素和在i位置的pi在同一个无向图中,就可以实现交换使pi=i。
代码
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<bitset>
#include<set>
using namespace std;
#define _CRT_SECURE_NO_WARNINGS 1;
#define ll long long
#define pub push_back
#define pob pop_back
#define pii pair<int,int>
#define pll pair<ll,ll>
#define inf 2e9
#define llf 1e19
#define endl "\n"
const ll mod = 80112002;
ll qpow(ll base, ll power)
{
ll res = 1;
while (power > 0)
{
if (power & 1) res = base * res % mod;
power >>= 1;
base = base * base % mod;
}
return res;
}
ll gcd(ll a, ll b)
{
return b == 0 ? a : gcd(b, a % b);
}
ll lcm(ll a, ll b)
{
return a / gcd(a, b) * b;
}
double dis(double x, double y, double x1, double y1)
{
return sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1));
}
double dis1(double x, double y, double z, double x1, double y1, double z1)
{
return sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1) + (z - z1) * (z - z1));
}
double chaji(double x1, double x2, double y1, double y2)
{
return x1 * y2 - x2 * y1;
}
int n, m, ans;
int fa[100010],a[100010];
int find(int x)
{
if (fa[x] == x) return x;
else return fa[x] = find(fa[x]);
}
void uni(int x, int y)
{
fa[find(x)] = find(y);
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int i, j, x, y;
cin >> n >> m;
for (i = 1; i <= n; i++) cin >> a[i];
for (i = 1; i <= n; i++) fa[i] = i;
for (i = 1; i <= m; i++)
{
cin >> x >> y;
uni(y, x);//并查集
}
for (i = 1; i <= n; i++)
{
if (find(i) == find(a[i])) ans++;
}
cout << ans;
}