跳到正文

科技·工程

构造随机树

2huk约 1 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年3月30日
篇幅
约 1 分钟

版本

  1. v1当前
C++
#include <bits/stdc++.h>

using namespace std;

#define int long long

const int N = 1000001; 		// N = 点数 + 1

int n, p[N];

struct Edge
{
	int a, b;
}e[N];

int randi(int P)
{
	int res = (((rand() << 15ll) | rand()));
	return res % P + 1;
}

void CreateTree()
{
	n = randi(N - 1);
	for (int i = 1; i <= n; ++ i ) p[i] = i;
	random_shuffle(p + 1, p + n + 1);

	for (int i = 2; i <= n; ++ i )
		e[i - 1] = {p[randi(i - 1)], p[i]};

	random_shuffle(e + 1, e + n);
}

main()
{
	srand(time(0));

	CreateTree();

	cout << n << '\n';

	for (int i = 1; i < n; ++ i ) cout << e[i].a << ' ' << e[i].b << '\n';

	return 0;
}
原文