如何快速的写出对拍程序
前言
(dalao勿喷)
可能有很多小伙伴苦于自己造数据去验证自己程序的正确性。
对此我们珂以采用随机造数据的方式,进行对拍验证
但可能有很多小伙伴苦于不知道怎么对拍
今天就介绍一种比较简单的方法去实现对拍
第一步:放入要验证的程序和暴力
找到自己的暴力和yy的正解, 分别放入std和test两个cpp中
(以 A + B Problem 为例)
#include <iostream>
using namespace std;
int main()
{
freopen("in.in","r",stdin);
freopen("std.out","w",stdout);//这里是std
int a,b;
cin >> a >> b;
cout << a+b << endl;
return 0;
}
#include <stdio.h>
int main()
{
freopen("in.in","r",stdin);
freopen("test.out","w",stdout);//这里是自己写的暴力
int a, b;
scanf("%d %d",&a, &b);
printf("%d\n", a+b);
return 0;
}
第二步:造出随机数据
然后写一个用来创造随机数据的cpp,起名为data
#include<cstdio>
#include<cstdlib>
#include<ctime>
int main()
{
freopen("in.in","w",stdout);//创建一个 in.in 文本文档来存放我们的随机数据
srand(time(0));
//这是一个生成随机数随机种子,需要用到 ctime 库
printf("%d %d\n",rand(),rand());
//这样就生成了2个随机数
return 0;
}
第三步:进行文本对比
然后使用下面这个对拍程序
如果测试多组数据后程序仍然没有退出,恭喜,您的正解很可能是对的
如果测试几组数据后程序会停止运行,并会反馈两个不一样答案。
此时关掉正在运行的窗口,打开in.in文件,就可以查看Hack数据了。
#include<cstdio>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
//int T = 0;
while(1) //一直循环,直到找到不一样的数据
{
//cout << ++T;可以加一个计数器
system("data.exe");//运行data.exe
system("test.exe");//运行test.exe
system("std.exe");//运行std.exe
if(system("fc std.out test.out")) //当 fc 返回1时,说明这时数据不一样
break; //不一样就跳出循环
}
return 0;
}
鸣谢
感谢 Imy_bisLy 提供的技术与资源支持