对拍

发布时间 2023-11-27 19:34:48作者: 梓熠帅哥

对拍是 $OI$ 比赛中非常重要的技巧,可以帮助我们去找到我们程序的一些漏洞。具体来说,就是通过自己的代码和一份暴力的代码(暴力代码保证正确)去跑同一份样例,比较不同。注意:自己还要写一个数据生成器。

我们以这道题做例子:

>给你 $n$ 个整数,请按从大到小的顺序输出其中前 $m$ 大的数。

>输入:每组测试数据有两行,第一行有两个数 $n$,$m$(0 < $n, m$ < 1000000)。第二行包含 $n$ 个各不相同,且都处于区间 [-500000, 500000] 的整数。

>输出:对每组测试数据按从大到小的顺序输出前 $m$ 大的数。

对于这道题,我们采用三种方式:

1. 我的代码,采用 sort 和归并。
2. 暴力代码,采用冒泡来判断我的代码是否正确。

## 开始解题

### Sort
```cpp
#include <bits/stdc++.h>
using namespace std;
int main()
{
freopen("1.in","r",stdin);
freopen("1.out","w",stdout);
int n,m;cin>>n>>m;
vector<int> a(n);
for(int i=0;i<n;i++) cin>>a[i];
sort(a.begin(),a.end());
reverse(a.begin(),a.end());
for(int i=0;i<m;i++) cout<<a[i]<<" ";
return 0;
}
```

### 冒泡

```cpp
#include <bits/stdc++.h>
using namespace std;
int main()
{
freopen("1.in","r",stdin);
freopen("1.ans","w",stdout);
int n,m;cin>>n>>m;
vector<int> a(n);
for(int i=0;i<n;i++) cin>>a[i];
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(a[i]<a[j]) swap(a[i],a[j]);
}
}
for(int i=0;i<m;i++) cout<<a[i]<<" ";
return 0;
}
```

### 归并

```cpp
#include <bits/stdc++.h>
using namespace std;
const int N=1000005;
int a[N],b[N];
void merge(int l,int r)
{
for(int i=l;i<=r;i++) b[i]=a[i];
int mid=(l+r)/2;
int i=l,j=mid+1;
for(int k=l;k<=r;k++){
if(j>r||i<=mid&&b[i]>b[j]) a[k]=b[i++];
else a[k]=b[j++];
}
}
void merge_sort(int l,int r)
{
if(l>=r) return ;
int mid=(l+r)/2;
merge_sort(l,mid);
merge_sort(mid+1,r);
merge(l,r);
}
int main()
{
freopen("1.in","r",stdin);
freopen("2.ans","w",stdout);
int n,m;cin>>n>>m;
for(int i=0;i<n;i++) cin>>a[i];
merge_sort(0,n-1);
for(int i=0;i<m;i++) cout<<a[i]<<" ";
return 0;
}

```
### 数据生成器
```cpp
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int MOD=1000000;
signed main()
{
freopen("i.in","w",stdout);

srand(time(nullptr));
int n=(rand()<<10)%MOD+1;
int m=(rand()<<10)%n+1;
cout<<n<<" "<<m<<endl;
for(int i=0;i<n;i++) {
cout<<(rand()<<10)%MOD-500000<<" ";
}
cout<<endl;
return 0;
}
```

### 对拍器

```cpp
#include <bits/stdc++.h>
#include <windows.h>
using namespace std;
int main()
{
int q=10000000;
while(q--)
{
system("shuju.exe");
system("AC.exe");
system("AC2.exe");
system("baoli.exe");
if(system("fc 1.out 1.ans")){
cout<<"WA"<<endl;
return 0;
}
if(system("fc 1.out 2.ans")){
cout<<"WA"<<endl;
return 0;
}
cout<<"AC"<<endl;
}
return 0;
}
```