需要写三个文件:
- 认为的正解
- 暴力做法
- 测试文件
以01背包为例
正解
#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
int f[N], v[N], w[N];
int n, m;
void solve(){
int n, m;
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; i++) scanf("%d%d", &v[i], &w[i]);
for(int i = 1; i <= n; i++){
for(int j = m; j >= v[i]; j--){
f[j] = max(f[j], f[j - v[i]] + w[i]);
}
}
printf("%d\n", f[m]);
}
int main(){
freopen("in.txt", "r", stdin);
freopen("ag.txt", "w", stdout);
int T = 1;
// scanf("%d", &T);
while(T -- ){
solve();
}
return 0;
}
暴力写法(bf.cpp)
#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
int f[N], v[N], w[N];
int n, m;
int ans;
void solve(){
int n, m;
scanf("%d%d", &n, &m);
for(int i = 0; i < n; i++) scanf("%d%d", &v[i], &w[i]);
for(int i = 0; i < 1 << n; i++){
int sv = 0, sw = 0;
for(int j = 0; j < n; j++){
if(i >> j & 1){
sv += v[j], sw += w[j];
}
}
if(sv <= m) ans = max(ans, sw);
}
printf("%d\n", ans);
}
int main(){
freopen("in.txt", "r", stdin);
freopen("bf.txt", "w", stdout);
int T = 1;
// scanf("%d", &T);
while(T -- ){
solve();
}
return 0;
}
测试文件(test.cpp)
用于生成数据和测试对比
#include <bits/stdc++.h>
using namespace std;
//利用ofstream将数据写入到in.txt中,这里不用freopen重定向的原因是这样依然能够向终端输出,更加多样化。
//方便在终端中输出一些调试信息。
void create_data(){
ofstream fout("in.txt");
int n = 10, m = rand() % 50 + 100;
fout << n << " " << m << endl;
for(int i = 0; i < n; i++){
int v = rand() % 50, w = rand() % 50;
fout << v << " " << w << endl;
}
fout.close();
}
int main(){
srand(time(0));
for(int i = 0; i < 100; i++){
printf("loop: %d\n", i);
create_data();
// getchar();
system("ag.exe");
system("bf.exe");
//win下用fc比较文件,相等则system返回0,不相等返回1
if(system("fc ag.txt bf.txt")){
puts("error!");
break;
}
}
puts("success!");
}