# Fix a Tree

30人阅读 评论(0)

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).

For this rooted tree the array p is [2, 3, 3, 2].

Given a sequence p1, p2, ..., pn, one is able to restore a tree:

1. There must be exactly one index r that pr = r. A vertex r is a root of the tree.
2. 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;
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：3719次
• 积分：597
• 等级：
• 排名：千里之外
• 原创：59篇
• 转载：0篇
• 译文：0篇
• 评论：0条
友情链接
评论排行