随机数据生成与对拍
当一个代码通过了所有样例,提交上去却wa掉,而又无法查看测试点数据时,可以用随机数据生成与对拍的方法,用程序随机生成若干组数据,并且比较你的答案与标准答案,将hack数据保留下来。
标准答案通过另一个可以得出正确答案的程序计算,可以写一个暴力方法,也可以复制网上的正确代码。
生成随机数据的程序需要根据题目输入来编写。
将两个程序的输出都记录在文件中,通过系统调用来比较两个文件内容是否相同。
随机数据生成
根据题目的输入格式来写,下面的程序以HDU - 5093 Battle ships为例。
#include<cstdio>
#include<cstdlib>
#include<ctime>
using namespace std;
char ch[3]={'*','#','o'};
int random(int n){
return 1LL*rand()*rand()%n;
}
int main(){
srand(time(0));
freopen("D:\\studyCode\\c++\\acmCode\\data.in","w",stdout);
printf("1\n");
int n=random(50)+1,m=random(50)+1;
printf("%d %d\n",n,m);
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++)
printf("%c",ch[random(3)]);
printf("\n");
}
}
也可以将生成的数据范围控制在一个比较小的范围,便于调试。
对拍
#include<cstdlib>
#include<cstdio>
#include<ctime>
using namespace std;
int main(){
for(int T=1;T<=10000;T++){
system("D:\\studyCode\\c++\\acmCode\\random\\bin\\Debug\\random.exe");
double st=clock();
system("D:\\studyCode\\c++\\acmCode\\demo\\bin\\Debug\\demo.exe");
double ed=clock();
system("D:\\studyCode\\c++\\acmCode\\bf\\bin\\Debug\\bf.exe");
if(system("fc D:\\studyCode\\c++\\acmCode\\data.out D:\\studyCode\\c++\\acmCode\\data.ans")){
puts("Wrong Answer"); return 0;
}else{
printf("Accepted, test point #%d, time %0.01fms\n",T,ed-st);
}
}
}
demo.exe为自己的测试程序,bf.exe为正确程序或暴力程序,random.exe程序随机生成一组输入数据,记录在data.in文件中,将demo.exe与bf.exe结果输出到文件data.out与data.ans中。window下的系统命令fc可以比较两个文件是否相同(Unix下使用diff命令)。
在demo.cpp和bf.cpp中加上下面两行代码。
所有的路径都根据实际情况决定。
freopen("D:\\studyCode\\c++\\acmCode\\data.in","r",stdin);
freopen("D:\\studyCode\\c++\\acmCode\\data.out","w",stdout);
运行情况
找到一组hack数据后,对拍程序停止,这组数据保存在data.in中。
之后就可以快乐的debug了。