对拍

对拍是什么

当我们需要测试自己代码的正确性,或者需要能找到bug的样例,就可以用到对拍。对拍需要两份代码,一份是正确的(可以不是正解,但要保证正确性),另一份是自己的代码,然后生成随机数据让两份代码根据同一份输入一起运行比较结果,以此来检验自己代码的正确性。

对拍实现

以下用前缀和问题演示对拍。
首先需要两份代码,一种是正确的(此处用暴力实现),另一种的自己写的。
正确的代码:right.cpp(暴力)

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5;
#define ll long long
ll a[N];
int main()
{
    int n; cin >> n;
    for (int i = 1; i <= n; ++i) cin >> a[i];
    int q; cin >> q;
    while (q--)
    {
        int x, y; cin >> x >> y;
        ll ans = 0;
        for (int i = x; i <= y; ++i) ans += a[i];
        cout << ans << endl;
    }
    return 0;
}

自己的代码(测试代码):test.cpp(前缀和)

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5;
#define ll long long
ll a[N];
int main()
{
    int n; cin >> n;
    for (int i = 1; i <= n; ++i) cin >> a[i], a[i] += a[i - 1];
    int q; cin >> q;
    while (q--)
    {
        int x, y; cin >> x >> y;
        ll ans = 0;
        ans = a[y] - a[x - 1];
        cout << ans << endl;
    }
    return 0;
}

数据生成代码:makedata.cpp

#include <bits/stdc++.h>
using namespace std;
int main()
{
    unsigned seed1 = chrono::system_clock::now().time_since_epoch().count();
    mt19937 g1(seed1);
    int n = g1() % (int)1e4 + 1; cout << n << endl;
    for (int i = 1; i <= n; ++i) cout << g1() % (int)1e4 << " ";
    int q = g1() % (int)1e3; cout << q << endl;
    for (int i = 1; i <= n; ++i)
    {
        int y = g1() % n + 1;
        int x = g1() % y + 1;
        cout << x << " " << y << endl;
    }
}

对拍代码:check.cpp

#include <bits/stdc++.h>
#include <windows.h>
using namespace std;
int main()
{
    int ok = 0;
    int n = 10;
    for (int i = 1; i <= n; ++i)
    {
        system("makedata.exe > make.txt");//将生成的数据写入txt
        system("right.exe < make.txt > right.txt");
        double begin = clock();
        system("test.exe < make.txt > test.txt");
        double end = clock();
        
        double t = end - begin;
        
        if (system("fc right.txt test.txt"))
        {
            cout << "Test points#" << i << " Wrong Answer" << endl;
            break;
        }
        else if (t > 1000)
        {
            cout << "Test points#" << i << " Time Limited Exceeded TIME: "<< t << "ms" << endl;
            break;
        }
        else
        {
            cout << "Test points#" << i << " Accepted TIME:" << t << "ms" << endl;
            ++ok;
        }
    }
    
    cout << "AC Data " << ok << " sets" << endl;
    getchar();
}

编译好后放到同一个文件夹中:

执行check.exe开始对拍

参考博客:C++ 对拍详解

posted @ 2023-05-02 15:33  何太狼  阅读(77)  评论(0编辑  收藏  举报