对拍板子(Linux)

Linux下的对拍代码

  • 在考试的时候想出来的所谓的正解的正确性不能保证,有可能还没暴力分数高,于是就有了对拍,可以检验是否有错误。
  • 这里举一个例子,比如我们写了个冒泡排序,然后用 STL 中的 sort 检验其正确性。

a.cpp

  • 这是自己写的不知道对错的代码
#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 5e3 + 5;
int n, a[N];
int main() {
    scanf("%d", &n);
    for (int i = 1; i <= n; ++i)
        scanf("%d", &a[i]);
    for (int i = 1; i <= n; ++i)
        for (int j = 1; j <= n - i; ++j)
            if (a[j] > a[j+1])
                swap(a[j], a[j+1]);
    for (int i = 1; i <= n; ++i)
        printf("%d ", a[i]);
    return 0;
}

b.cpp

  • 这是知道是正确的暴力代码,可以用时间效率比较低的,数据造的小一点就好了。
#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 5e3 + 5;
int n, a[N];
int main() {
    scanf("%d", &n);
    for (int i = 1; i <= n; ++i)
        scanf("%d", &a[i]);
    sort(a + 1, a + n + 1);
    for (int i = 1; i <= n; ++i)
        printf("%d ", a[i]);
    return 0;
}

1.cpp

  • 这是造数据的代码。
#include <bits/stdc++.h>
using namespace std;
int main() {
    srand(time(0));//为随机数提供一个种子,不然会一直输出一样的数据
    int n = rand() % 100 + 1;
    printf("%d
", n);
    for (int i = 1; i <= n; ++i)
        printf("%d ", rand() % 1000);
}

1.py

  • 造数据还可以用python,因为python的数据在一秒内也是不同的,而C++由于随机种子是时间,在一秒内出来的数据是完全相同的
from random import * #引用随机函数的库
n=randint(1, 100);
print(n); #默认换行输出
for i in range(1, n + 1, 1): 
    print(randint(1, 1000), end = ' '); #end = ' '后就不会换行了

dp.cpp

  • 然后就是对拍的代码了
#include <bits/stdc++.h>

int main() {
    system("rm 1; rm a; rm b; make 1 && make a && make b");//把每个程序先编译一下
    int t = 0; 
    while (1) {//这里设置的是无限循环,直到出现错误,也可以限制次数
        printf("#%d------->", ++t);//方便查看
        system("./1 > IN");//将生成的数据放到in中
        //system("python3 1.py > IN");//用python造数据
        system("./a < IN > a.out");//从in中读取放到out中
        system("./b < IN > b.out");
        if (system("diff a.out b.out"))//比较两个输出,diff若不相同返回1
            return system("gnome-terminal -x bash -c echo 'Wrong Answer'"), 0;//弹出窗口提示并结束程序
        puts("Accepted");
    }
}

dp.sh

  • 对拍用脚本写更加方便,只不过没有C++快
make 1
make a
make b
cnt=1
while true; do
    ((cnt++))
    ./1 > IN
    #python3 1.py > IN
    ./a < IN > a.out
    ./b < IN > b.out
    if diff a.out b.out; then
        printf "#$cnt Accepted
"
    else 
        notify-send 'Wrong Answer'
        break
    fi
done
原文地址:https://www.cnblogs.com/shawk/p/13178750.html