模板:
#include <cstdlib>
#include <ctime>
int random(int n) {
return (long long)rand() * rand() % n;
}
int main() {
srand((unsigned)time(0));
}
随机生成整数序列:
#include <bits/stdc++.h>
using namespace std;
int random(int n) {
return (long long)rand() * rand() % n;
}
const int N = 1e5, M = 1e9;
int a[N + 100];
int main() {
srand((unsigned)time(0));
int n = random(N) + 1;
for (int i = 1; i <= n; ++i) {
a[i] = random(2 * M + 1) - M;
printf("%d ", a[i]);
}
}
随机生成区间列:
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <cstdio>
using namespace std;
int random(int n) {
return (long long)rand() * rand() % n;
}
int m = 1e5, n = 1e9;
int main() {
freopen("czx.in", "w", stdout);
srand((unsigned)time(0));
for (int i = 1; i <= m; ++i) {
int l = random(n) + 1, r = random(n) + 1;
if (l > r) swap(l, r);
printf("%d %d\n", l, r);
}
}
随机生成树:
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <cstdio>
using namespace std;
int random(int n) {
return (long long)rand() * rand() % n;
}
const int N = 1e5, M = 1e9;
int main() {
freopen("czx.in", "w", stdout);
srand((unsigned)time(0));
int n = random(N) + 2;
for (int i = 2; i <= n; ++i) {
int fa = random(i - 1) + 1;
int val = random(M) + 1;
printf("%d %d %d\n", fa, i, val);
}
}
随机生成图:
#include <bits/stdc++.h>
using namespace std;
inline void print(int x) {
if (x < 0) putchar('-'), x = -x;
if (x < 10) putchar(x + '0');
else {
print(x / 10);
putchar(x % 10 + '0');
}
}
int random(int n) {
return (long long)rand() * rand() % n;
}
const int M = 1e6;
int n = 1e5, m = 1e6;
pair<int, int> e[M + 100];
map< pair<int, int>, bool > h;
int main() {
freopen("czx.in", "w", stdout);
srand((unsigned)time(0));
print(n); putchar(' '); print(m); putchar('\n');
for (int i = 1; i < n; ++i) {
int fa = random(i) + 1;
e[i] = make_pair(fa, i + 1);
h[e[i]] = h[make_pair(i + 1, fa)] = 1;
}
for (int i = n; i <= m; ++i) {
int x, y;
do {
x = random(n) + 1, y = random(n) + 1;
} while (x == y || h[make_pair(x, y)]);
e[i] = make_pair(x, y);
h[e[i]] = h[make_pair(y, x)] = 1;
}
random_shuffle(e + 1, e + m + 1);
for (int i = 1; i <= m; ++i) {
print(e[i].first); putchar(' '); print(e[i].second); putchar('\n');
}
}