题目:
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).
Given a sequence p1, p2, ..., pn, one is able to restore a tree:
- There must be exactly one index r that pr = r. A vertex r is a root of the tree.
- For all other n - 1 vertices i, there is an edge between vertex i and vertex pi.
A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.
You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
题意:给一个序列,序号代表父节点,内容是子节点,序列不一定成树,问更改最少数目使之成为一颗树。
分析:基本思路用并查集判断子树,更改子树根节点到一棵树上即可,坑在并查集的判环上,一直不是很理解,这道题的判环是判断有没有树根。
题解:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <string>
#include <cstring>
#include <functional>
#include <cmath>
#include <cctype>
#include <cfloat>
#include <climits>
#include <complex>
#include <deque>
#include <list>
#include <set>
#include <utility>
#define rt return 0
#define fr freopen("in.txt","r",stdin)
#define fw freopen("out.txt","w",stdout)
#define ll long long
#define ull unsigned long long
#define detie ios_base::sync_with_stdio(false);cin.tie(false);cout.tie(false)
#define maxi 0x3f3f3f3f
using namespace std;
int s[300000];
int pre[300000];
int n;
int find(int x)
{
if (s[x]!=x)
s[x] = find(s[x]);
return s[x];
}
void uni(int x, int y)
{
int xx = find(x);
int yy = find(y);
s[xx] = yy;
}
int main()
{
//fr;
detie;
cin >> n;
int root = -1;
vector<int> v;
for (int i = 1; i <= n; i++)
{
s[i] = i;
cin >> pre[i];
}
for (int i = 1; i <= n; i++)
{
if (pre[i] == i)
{
root = i;
v.push_back(i);
}
else
{
int xx = find(i);
int yy = find(pre[i]);
if (xx == yy)
v.push_back(i);
else
uni(i, pre[i]);
}
}
int num = 0;
if (root != -1)
{
num = v.size() - 1;
for (int i = 0; i <= num; i++)
pre[v[i]] = root;
}
else
{
root = v[0];
num = v.size();
for (int i = 0; i < num; i++)
pre[v[i]] = root;
}
cout << num << endl;
for (int i = 1; i <= n; i++)
cout << pre[i] << ' ';
cout << endl;
rt;
}