Mac OS下编写对拍程序

介绍

  对拍是信息学竞赛中重要的技巧,它通过一个效率低下但正确率可以保证的程序,利用庞大的随机生成数据来验证我们的高级算法程序。对拍最大的优势在于可以通过人力所不能及的速度和数量达到验证的效果。下面我们来看一下简单的对拍程序该如何编写

举例

给定一个自然数n (n<=50000),求解1+2+3+...+n的和。

test1.cpp //算法程序1

test2.cpp //算法程序2

data.cpp //数据生成器

compare.cpp //比较程序

说明

test1.cpp和test2.cpp都是我们所写的算法程序,其中test1.cpp使用朴素的for循环求解,代码如下:

 1 #include<cstdio>
 2 
 3 int main()
 4 {
 5     freopen("test.in"  ,"r",stdin);
 6     freopen("test1.out","w",stdout);
 7 
 8     int n;
 9     long long ans=0;
10     scanf("%d",&n);
11     for(int i=1;i<=n;i++) ans+=i;
12     printf("%lld
",ans);
13     
14     return 0;
15 }
test1.cpp

test2.cpp利用公式计算,代码如下:

 1 #include<cstdio>
 2 
 3 int main()
 4 {
 5     freopen("test.in"  ,"r",stdin);
 6     freopen("test2.out","w",stdout);
 7 
 8     int n;
 9     scanf("%d",&n);
10     //printf("%lld
",(long long) (n+1)*n/2);
11     printf("%d
",(n+1)*n/2);
12     return 0;
13 }
test2.cpp

data.cpp是我们写的数据生成器

 1 #include<cstdio>
 2 #include<ctime>
 3 #include<cstdlib>
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     freopen("test.in","w",stdout);
 9     srand(time(0));
10     printf("%d",abs(rand()*rand()%50000));
11     return 0;
12 }
data.cpp

而compare.cpp则是对拍程序的主体

 1 #include<cstdio>
 2 #include<cstdlib>
 3 
 4 int main()
 5 {
 6     int tmp=0;
 7     for(int i=1;i<=10000;i++)
 8     {
 9         system("./data");
10         system("./test1");
11         system("./test2");
12         
13         if(i/100>tmp) {printf("-- %d --
",i);tmp=i/100;}
14         if(system("diff test1.out test2.out"))
15         {
16             printf("wrong in --> %d 
",i);
17             break;
18         }
19     }
20     return 0;
21 }
compare.cpp

将四个文件编译后的可执行文件放到一个文件夹里,用cd进入这个文件夹,输入

1 ./compare

即可运行。

Tips

1.“./”表示当前目录下,如果在终端中输入的是./compare 的话就已经默认在当前目录里了,程序里不写“./”也是可行的。
2.diff函数在得到不同的比较值时会返回“1”。
3.mac os下对比是没有提示的,知道有不同的结果出现时才有所提示。所以建议自己写的时候附带提示功能。

----不要温顺地走进那良宵
原文地址:https://www.cnblogs.com/Hist/p/4852754.html