c++对拍详解

准备

  1. 暴力代码(或保证对的代码) baoli.cpp
  2. 准备验证是否正确的代码 sol.cpp
  3. 随机数据生成器 random.cpp
  4. 对拍执行代码 duipai.cpp

过程

  1. 将 随机数据生成器 的 输出文件 改为1.in
  2. 将 暴力代码 和 准备验证是否正确的代码 的 输入文件 改为 1.in
  3. 将 暴力代码 的 输出文件 改为 1.ans
  4. 将 准备验证是否正确的代码 的 输出文件改为 1.out
  5. 比较1.ans 和 1.out,如果一样,说明在此样例下,代码正确。

具体实现

随机数据生成器(random.cpp)

#include<bits/stdc++.h>
#define int long long
using namespace std;
int random(int Lim)//Lim为数据范围,[0,Lim-1] 
{
	return (int)rand()*rand()%Lim;
}
signed main()
{
	freopen("1.in","w",stdout);//输出到1.in 
	srand((unsigned)time(0));
	int x=random(10000)+1;//随机生成1~10000之间的数 
	cout<<x<<'\n';
	return 0;
}

暴力代码(baoli.cpp)

freopen("1.in","r",stdin);//从1.in读入 
freopen("1.ans","w",stdout)//输出到1.ans

验证代码(sol.cpp)

freopen("1.in","r",stdin);//从1.in读入 
freopen("1.out","w",stdout)//输出到1.out

对拍代码(duipai.cpp)

#include<bits/stdc++.h>
#define int long long
using namespace std;
signed main()
{
	for(int i=1;i<=1000;i++)
	{
		system("random.exe");
		double st=clock();
		system("sol.exe");
		double ed=clock();
		system("baoli.exe");
		if(system("fc 1.ans 1.out"))
		{
			puts("WA!");
			// 程序立即退出,此时 1.in即为发生错误的数据
			return 0;
		}
		else
		{
			printf("AC!,测试点:%d ,用时 %.0lfms\n",i,ed-st);
		}
	}
	return 0;
}

原理

自己看吧,应该能懂

注意

所有代码和文件一定都要在同级目录中(也就是上级路径相同),才能在 duipai.cpp 中直接调用同级目录中的文件(如 system("random.exe"); ),否则就需要把文件的完整路径写下来(如 system("C:\???\???\random.exe"); )。

posted @ 2026-10-26 07:29  hemingxi_2030  阅读(17)  评论(0)    收藏  举报