1. 题目
2. 代码
其实就是一个简单的深度优先搜索(dfs),但是可能我好久没写代码了,一个漏洞我找了好久。。。甚至开始怀疑自己学的递归是个错的。(头大)
<果然开始热衷于写bug和debug了吗,看这丑陋的注释,都是找bug的中间产物>
#include <iostream>
using namespace std;
typedef struct node{
int num;
bool used;
// int group;
}Node;
int n;
int sum1, sum2;
Node a[1000];
bool flag;
void dfs(int k){
if(k == n){
if(sum1 == sum2){
/* cout << "sum1 == sum2: " << sum1 << " " << sum2 << endl;
cout << "group5:" << endl;
for(int i=0; i<n; i++){
if(a[i].group == 5){
cout << a[i].num << " ";
}
}
cout << endl;
cout << "group3:" << endl;
for(int i=0; i<n; i++){
if(a[i].group == 3){
cout << a[i].num << " ";
}
}
cout << endl;*/
flag = true;
}
return;
}
if(a[k].used){
dfs(k+1);
}
else{
sum1 += a[k].num;
// a[k].group = 5;
dfs(k+1);
// a[k].group = 3;
sum1 -= a[k].num;
sum2 += a[k].num;
dfs(k+1);
sum2 -= a[k].num; //这里!!!这里一定一定要记得减啊!!!花了我好久时间debug!!!
}
}
int main(){
while(cin >> n){
flag = false;
sum1 = 0, sum2 = 0;
for(int i=0; i<n; i++){
cin >> a[i].num;
// cout << "a[i]" << i << " :" << a[i].num << " " << a[i].used << endl;
a[i].used = false;
if(a[i].num % 5 == 0){
// cout << "%5: " << a[i].num << endl;
sum1 += a[i].num;
a[i].used = true;
// a[i].group = 5;
}
else if(a[i].num % 3 == 0){
// cout << "%3: " << a[i].num << endl;
sum2 += a[i].num;
a[i].used = true;
// a[i].group = 3;
}
// cout << "a[i]" << i << " :" << a[i].num << " " << a[i].used << endl;
}
dfs(0);
if(flag){
cout << "true" << endl;;
}
else{
cout << "false" << endl;
}
}
return 0;
}
去掉注释清爽多了
#include <iostream>
using namespace std;
typedef struct node{
int num;
bool used;
}Node;
int n;
int sum1, sum2;
Node a[1000];
bool flag;
void dfs(int k){
if(k == n){
if(sum1 == sum2){
flag = true;
}
return;
}
if(a[k].used){
dfs(k+1);
}
else{
sum1 += a[k].num;
dfs(k+1);
sum1 -= a[k].num;
sum2 += a[k].num;
dfs(k+1);
sum2 -= a[k].num; //这里!!!这里一定一定要记得减啊!!!花了我好久时间debug!!!
}
}
int main(){
while(cin >> n){
flag = false;
sum1 = 0, sum2 = 0;
for(int i=0; i<n; i++){
cin >> a[i].num;
a[i].used = false;
if(a[i].num % 5 == 0){
sum1 += a[i].num;
a[i].used = true;
}
else if(a[i].num % 3 == 0){
sum2 += a[i].num;
a[i].used = true;
}
}
dfs(0);
if(flag){
cout << "true" << endl;;
}
else{
cout << "false" << endl;
}
}
return 0;
}