对拍

· · 算法·理论

前言

众所周知,当我们做出最优解的时候,我们往往无法判断它的正确性。

众所又周知,有一个叫对拍的东西。

正文

对拍,即对比朴素做法与最优做法的程序。

举个栗子:P1255 数楼梯

我们首先使用朴素方法,可以看到得50分。

这个朴素做法没有得满分的原因是没用高精。

高精写不对,WA两行泪。Asher12提醒您,不要先写高精。

当我们保证朴素做法一定是正确的时候,我们就可以用对拍来验证优化算法的正确性。

写出来正解后,我们就可以开始验证了。

首先,为了保证数据的随机性,我们需要写一个程序以随机生成输入数据。

#include <bits/stdc++.h>
using namespace std;
int main()
{
    mt19937 gen(chrono::system_clock::now().time_since_epoch().count());
    uniform_int_distribution<int>dist(1,30);
    int x=dist(gen);
    cout<<x;
    return 0;
}

里面有一些陌生的东西,比如mt19937,chrono,uniform_int_distribution等,都是C++11的新特性。除了chrono定义在<chrono>中之外,剩下两个都定义在<rand>中。

生成了数据,就要用对拍程序进行验证。利用Windows中cmd的指令,可以得出以下命令:

程序 > 输出文件(输出结果到文件)

程序 < 输入文件 > 输出文件(从文件中读取输入数据,输出结果到文件)

fc 文件1 文件2(文件比较)

#include <iostream>
#include <stdexcept>
using namespace std;
int main()
{
    bool flag=false;
    for (int i=1;i<=10;i++)
    {
        system("data.exe > data.in");
        system("pusu.exe < data.in > test.out");
        system("zhengjie.exe < data.in > test.ans");//避免混淆,一个是.out,一个是.ans
        try
        {
            bool ff=system("fc test.out test.ans");
            if (ff!=false)
            {
                flag=true;
                throw runtime_error("Error:The answer is not true.");
            }
        }
        catch (runtime_error err)
        {
            cout<<err.what()<<'\n';
            break;
        }
    }
    if (!flag)
    {
        puts("The same.");
    }
    return 0;
}

提前用编译器生成程序,才可以使用。

这里使用system(c_str)来与终端交互。

当输入样例太过复杂时,不应使用对拍哦。