ACM程序对拍

有时候在OJ刷题目的时候,总是会遇到不知名bug,题目总不能AC,自己测试的一些数据又都能得出正确的结果,又或是直接暴力会TLE,改了算法,但是仍然WA,这时候进行程序对拍测试数据不失为一个好办法。程序对拍主要是通过数据生成器生成随机数据,然后与正确程序跑出来的结果进行比对,虽然有时候数据很难构造,但是对于一般的题目却能起到很到的作用。

通过一个简单的例子进行解释:求两个数之和。

两个进行对拍的程序

#include<stdio.h>

int main()
{
	freopen("data.txt","r",stdin);  //从文件读入数据 
	freopen("1.txt","w",stdout);    //写出数据到文件 
	int a,b;
	while (~scanf("%d%d",&a,&b))
	{
		printf("%d+%d=%d
",a,b,a+b);
	}
	return 0;
} 

#include<stdio.h>

int main()
{
	freopen("data.txt","r",stdin);  //从文件读入数据 
	freopen("1.txt","w",stdout);    //写出数据到文件
	int a,b;
	while (~scanf("%d%d",&a,&b))
	{
		printf("%d+%d=%d",a,a,a+a);
	}
	return 0;
}

  数据生成器程序

#include<stdio.h>  
#include<stdlib.h>   
#include<time.h> 
#include<limits.h>
int main()
{
	freopen("data.txt","w",stdout);    //随机数据生成写入到此文件 
	srand(time(NULL));
	int n = 100;        //数据规模
	while (n--)
	{
		printf("%d %d
",rand()%INT_MAX,rand()%INT_MAX);
	}
	return 0;
}

  

  重要的一步:在保存数据的位置新建一个txt文本文件,输入如下内容,并把“.txt”的后缀名改为“.bat”,双击运行即可。

@echo off
fc 1.txt 2.txt 
pause

  二者结果若无差异,显示为

若有差异,显示为

几种常用的数据生成程序:

//生成int型数据
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<time.h>
int main()
{
    freopen("data.txt", "w", stdout);
    srand(time(NULL));
    //通过控制t的大小控制产生数的范围,控制n可以控制数据的产生量。
    int t, n = 1000;
    while(n--)
    {
        printf("%d
",rand()%t);
    }
    return 0;
}

//生成两位小数数据
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<time.h>
int main()
{
    freopen("data.txt", "w", stdout);
    srand(time(NULL));
    int n = 1000;
    while(n--)
    {
        printf("%.2lf
",rand()*1.0/100);
    }
    return 0;
}

//生成字符串
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<time.h>
int main()
{
    freopen("data.txt", "w", stdout);
    srand(time(NULL));
    int t, n = 1000;
    while(n--)
    {
        printf("%c
",rand()%26 + 'A');
    }
    return 0;
}

  

最后再通过一个例子加深对数据生成器的理解,假设有一组输入数据如下:

  • IN x(0=<x<1000000000)表示队伍最后面新来了一个饥饿值为 x 的同学
  • OUT 表示队伍最前面的同学打饭结束离开队伍(若无人则跳过该操作)
  • QUERY
  • END 表示输入结束

数据生成器可写成如下:

#include<cstdio>  
#include<cstdlib>  
#include<cstring>  
#include<time.h>  
const int maxn = 1000000000;
int main() {  
    freopen("data.txt", "w", stdout);  
    srand(time(NULL));  
    //通过控制t的大小控制产生数的范围,控制n可以控制数据的产生量。  
    int t = 3,n = 7000;
    while (n--)
    {
    	if (rand()%t+1 == 1)
    	{
    		printf("IN %d
",rand()%maxn);
    	}
    	else if (rand()%t + 2 == 2)
    	{
    		printf("OUT
");
    	}
    	else if (rand()%t + 3 == 3)
    	{
    		printf("QUERY
");
    	}
    }
    printf("END");
    return 0;  
}  
原文地址:https://www.cnblogs.com/ZhaoxiCheung/p/5902030.html