【3 月小记】Part 2: 对拍

对拍

对拍是一种常用的代码调试方法,常用于检验程序是否正确。

要想对拍,需要以下四个程序:

程序名 意义 标准输入 标准输出
data_maker.cpp 数据生成器。 task.in
brute.cpp 确保完全正确的暴力程序。 task.in brute.out
std.cpp 要检验正确性的程序。 task.in std.out
brute.cpp 对拍程序。 控制台 控制台

例如,以 A+B Problem 为例,演示各个程序的编写模式。(以下代码中,输入输出的文件名略与上表有出入)

  • data_maker.cpp

    #include <bits/stdc++.h>
    #include <sys/timeb.h>
    int main() {
    	freopen("taskin.txt", "w", stdout);
    	struct _timeb T;
    	_ftime(&T);
    	srand(T.millitm);
    	printf("%d %d\n", rand(), rand());
    }
    
  • brute.cpp

    #include <cstdio>
    using namespace std;
    int main() {
    	freopen("taskin.txt", "r", stdin);
    	freopen("bruteout.txt", "w", stdout);
    	int a, b;
    	scanf("%d%d", &a, &b);
    	int ans = 0;
    	int i;
    	for (i = 1; i <= a; i++)
    		ans++;
    	for (i = 1; i <= b; i++)
    		ans++;
    	printf("%d\n", ans);
    	return 0;
    }
    
  • std.cpp

    #include <cstdio>
    using namespace std;
    int main() {
    	freopen("taskin.txt", "r", stdin);
    	freopen("stdout.txt", "w", stdout);
    	int a, b;
    	scanf("%d%d", &a, &b);
    	printf("%d\n", a + b);
    	return 0;
    }
    
  • compare.cpp

    #include <bits/stdc++.h>
    int main() {
    	const double limit = 1000;
    	const int N = 50;
    	int ac = 0;
    	for (int i = 1; i <= N; i++) {
    		system("data_maker.exe");
    		system("std.exe");
    		double begin = clock();
    		system("brute.exe");
    		double end = clock();
    		double t = end - begin;
    		if (system("fc stdout.txt bruteout.txt")) {
    			printf("WA on #%d", i);
    		} else if (t > limit) {
    			printf("TLE on #%d", i);
    		} else {
    			printf("AC on #%d", i);
    			ac++;
    		}
    		printf(", time = %gms\n", t);
    	}
    	double avg = 100.0 * ac / N;
    	printf("\n==COMPARE INFO==\n%d datas\n%d AC\naverage %.2lf%%", N, ac, avg);
    }
    
posted @ 2026-03-05 13:13  L-Coding  阅读(1)  评论(0)    收藏  举报