C++对拍详解——EdisonBa’s Blog

生成随机数

1
2
3
4
5
6
7
8
9
10
#include<bits/stdc++.h>
int main()
{
struct _timeb T;
_ftime(&T);
srand(T.millitm); //获得毫秒

int a = rand();
printf("%d\n", a);
}

对拍

eg: A+B problem
正确代码(需要验证的代码) std.cpp

1
2
3
4
5
6
7
8
9
#include <cstdio>
using namespace std;
int main()
{
int a, b;
scanf("%d%d", &a, &b);
printf("%d\n", a + b);
return 0;
}

​暴力代码:baoli.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <cstdio>
using namespace std;
int main()
{
int a, b;
scanf("%d%d", &a, &b);
int ans = 0;
int i;
for (i = 1; i <= a; i++)
ans++;
for (i = 1; i <= b; i++)
ans++;
printf("%d\n", ans);
return 0;
}

std.cpp和baoli.cpp 放进一个文件夹

生成随机数 data.cpp

1
2
3
4
5
6
7
8
9
10
11
#include<bits/stdc++.h>
int main()
{
struct _timeb T;
_ftime(&T);
srand(T.millitm);
//生成随机数种子,利用 timeb 生成毫秒级别随机数

printf("%d %d\n", rand(), rand());
//这样就生成了2个随机数
}

生成随机数’数据范围
0 ≤ rand()%(a+1) ≤ a

Windows 系统下 rand() 生成的随机数的范围在 0~32767 之间。如果想要得到比32767更大的随机数
eg 1<= a <= 1,000,000

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<bits/stdc++.h>
#define ll long long

ll Random(ll mod)
{
ll ans = 2147483647;
return ans = ans * rand() % mod + 1;
}

int main()
{
struct _timeb T;
_ftime(&T);
srand(T.millitm);

ll n;
while (1)
{
n = Random(1000000);
printf("%lld\n", n);
}
return 0;
}

system(“A.exe > A.txt”)
指的是运行 A.exe,把结果输出(>)到 A.txt 中。
​system(“B.exe < A.txt > C.txt”)
指的是运行 B.exe,从 A.txt 中读入(<)数据,把结果输出(>)到 C.txt 中。
​system(“fc A.txt B.txt”)
指的是比较 A.txt 和 B.txt ,如果两个文件里的数据相同返回0,不同返回1。

steps:
先让数据生成器输出数据。 system(“data.exe > in.txt”)
然后用这个数据跑一遍暴力代码,输出结果。 system(“baoli.exe < in.txt > baoli.txt”)
再用这个数据跑一遍你写的正解代码,输出结果。 system(“std.exe < in.txt > std.txt”)
把两个结果相比较,判断是不是一样的。 system(“fc std.txt baoli.txt”)

duipai.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<bits/stdc++.h>
using namespace std;
int main()
{
while (1) //一直循环,直到找到不一样的数据
{
system("data.exe > in.txt");
system("baoli.exe < in.txt > baoli.txt");
system("std.exe < in.txt > std.txt");
if (system("fc std.txt baoli.txt")) //当 fc 返回 1 时,说明这时数据不一样
break; //不一样就跳出循环
}
return 0;
}

ps: ‘>’’<’符号对文件进行操作,但如果使用freopen等文件输入输出,则只需运行两个程序,不需’<’’>’