# prufer数列学习笔记

prufer数列是一种无根树的编码表示，对于一棵n个节点带编号的无根树，对应唯一一串长度为n-2的prufer编码。

（1）无根树转化为prufer序列。

/**********************

**********************/

#include <iostream>
#include <cmath>
#include <cstdlib>
#include <time.h>
#include <vector>
#include <cstdio>
#include <cstring>
#include <set>
using namespace std;
#define maxn 1111111
#define maxm 2111111

set <int> gg;
struct node {
int u, v, next;
} edge[maxm];
bool vis[maxn];

void add_edge (int u, int v) {
edge[cnt].u = u, edge[cnt].v = v, edge[cnt].next = head[u], head[u] = cnt++;
}

int main () {
cin >> n;
memset (degree, 0, sizeof degree);
memset (vis, 0, sizeof vis);
gg.clear ();
cnt = 0;
for (int i = 1; i < n; i++) {
int u, v;
scanf ("%d%d", &u, &v);
degree[u]++, degree[v]++;
}
for (int i = 1; i <= n; i++) {
if (degree[i] == 1) {
gg.insert (i);
vis[i] = 1;
}
}

set<int>::iterator it;
int prufer[maxn], id = 0;
for (; id <= n-3;) {
int u = (*(it = gg.begin ()));
gg.erase (u);
for (int i = head[u]; i != -1; i = edge[i].next) {
int v = edge[i].v;
if (vis[v])
continue;
degree[v]--;
prufer[++id] = v;
if (degree[v] == 1) {
gg.insert (v);
vis[v] = 1;
}
}
}
for (int i = 1; i <= id; i++) {
cout << prufer[i] << " ";
} cout << endl;
return 0;
}

（2）prufer序列转化为无根树。

/**********************
prufer序列解码
**********************/

#include <iostream>
#include <cmath>
#include <cstdlib>
#include <time.h>
#include <vector>
#include <cstdio>
#include <cstring>
#include <set>
using namespace std;
#define maxn 1111111
#define maxm 2111111

int n;
int prufer[maxn], node[maxn], cnt;
set<int> gg; //在prufer序列里没有出现的点
int vis[maxn]; //这个点是不是在prufer序列里面
bool used[maxn]; //这个点有没有使用过

int main () {
cin >> n;
gg.clear ();
memset (vis, 0, sizeof vis);
memset (used, 0, sizeof used);
cnt = 0;
for (int i = 1; i <= n-2; i++) {
cin >> prufer[i];
vis[prufer[i]]++;
}
for (int i = 1; i <= n; i++) {
if (!vis[i]) {
gg.insert (i);
}
}
set<int>::iterator it;
for (int i = 1; i <= n-2; i++) {
int v = (*(it = gg.begin ())), u = prufer[i];
cout << u << "-" << v << endl;
used[v] = 1;
gg.erase (v);
vis[u]--;
if (!vis[u] && !used[u]) {
gg.insert (u);
}
}
it = gg.begin ();
cout << *it << "-" << *(++it) << endl;
return 0;
}

05-13 282

08-10 921

03-07 948

11-17 5849

04-10 277

10-08 105

08-28 169

04-06 480

04-11 554

05-16 4

01-09 12

11-18 270

12-31 207

07-15 268

01-19 246

12-29 953

06-24 736

08-11 1017

06-24

03-13 1019

02-28 4

05-02 355

02-23 115

07-20 16

11-12 848

03-29 49

11-14 195

03-19 462

04-23 173

09-25 187

08-18 639

07-07 303

02-02 11

04-27 16

01-11 13

07-12 209

02-21 87

05-06 133

08-03 559

04-22 419

05-05 649

01-01 292

02-15 111

07-31 823

06-10

03-20 149

07-22 314

03-06 350

03-07 165

03-20 124

08-12 30

11-07 61

09-22

08-31 1024

04-28 1414

06-22 380

10-10 253

03-07 194

03-14 680

10-10 186

01-16 308

05-22 112

06-18 742

01-24 92

03-29 158

05-17 30

10-30 2460

04-14 59万+

03-13 15万+

03-04 14万+

03-08 2万+

04-25 6万+

#### 总结了 150 余个神奇网站，你不来瞅瞅吗？

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客