Repository navigation
Expand file tree
/
Copy pathrandom_tree.cpp
More file actions
98 lines (87 loc) · 2.26 KB
/
Copy pathrandom_tree.cpp
File metadata and controls
98 lines (87 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <algorithm>
#include <iostream>
#include <vector>
#include <functional>
using namespace std;
// Copy begin
int random(int a, int b) {
return (rand() % (b - a + 1)) + a;
}
void generateRandomTree(int N, vector< vector<int> >& g) {
g.assign(N, vector<int>());
vector<int> a(N);
for (int i = 0; i < N; ++i) {
a[i] = i;
}
random_shuffle(a.begin(), a.end());
int freeV = 1;
for (int i = 0; i < N && freeV < N; ++i) {
int edgeCnt = random(1, 3);
for (int x = 0; x < edgeCnt && freeV < N; ++x) {
g[a[x]].push_back(a[freeV]);
g[a[freeV]].push_back(a[x]);
++freeV;
}
}
}
// Copy end
const int TEST_COUNT = 100;
bool randomTest() {
bool success = true;
vector< vector<int> > g;
for (int t = 0; t < TEST_COUNT && success; ++t) {
const int N = random(1, 10);
generateRandomTree(N, g);
vector<bool> used(N, false);
int usedCnt = 0;
int edgeCnt = 0;
for (int a = 0; a < N; ++a) {
if (!used[a]) {
used[a] = true;
++usedCnt;
}
for (int x = 0; x < g[a].size(); ++x) {
int b = g[a][x];
if (a < b) {
++edgeCnt;
}
if (!used[b]) {
used[b] = true;
++usedCnt;
}
}
}
success &= (edgeCnt == N - 1);
success &= (usedCnt == N);
if (!success) {
cout << "Test Failed. N = " << N << endl;
for (int a = 0; a < N; ++a) {
for (int x = 0; x < g[a].size(); ++x) {
int b = g[a][x];
cout << a << " " << b << endl;
}
}
}
}
return success;
}
bool processTest(const std::string& testName, std::function<bool()> testFun) {
bool testRes = testFun();
if (testRes) {
std::cout << testName << " -> SUCCESS" << std::endl;
}
else {
std::cout << testName << " -> FAILED" << std::endl;
}
return testRes;
}
int main() {
bool ok = true;
ok &= processTest("randomTest", randomTest);
if (ok) {
return 0;
}
else {
return 1;
}
}