采用DFS解决这道题,从而得到如下代码,对于题目中给出的例子可以解决问题:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 20 + 10;
int sticks[N], side, n, m;
bool visited[N];
bool DFS(int sum, int number){
if(number == 4) return true;
for(int i = 0;i < m;i++){
if(visited[i] || sum + sticks[i] > side) continue;
visited[i] = true;
if(sum + sticks[i] == side){
if(DFS(0, number + 1)) return true;
}else{
if(DFS(sum + sticks[i], number)) return true;
}
visited[i] = false;
}
return false;
}
int main(){
scanf("%d", &n);
while(n--){
scanf("%d", &m);
int total = 0;
for(int i = 0;i < m;i++){
scanf("%d", &sticks[i]);
total += sticks[i];
}
side = total / 4;
if(DFS(0, 0)) printf("yes\n");
else printf("no\n");
}
return 0;
}
但是题目中明确说了木棍的数量最多有10000根,因此若是木棍数量太多,则递归层数太多,必然会导致超时,因此这里还需要对代码进行一定的优化,即剪枝:
- 木棍的累计长度total若是不能被4整除,则一定不行,同时,若能够被4整除,则只需要找到3条边即可
- 单个木棍的长度大于变长side
- 记录之前失败过的长度,避免重复匹配
- 将木棍按照从大到小的顺序进行排序,之后找木棍就不需要每次都从头开始
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 20 + 10;
int sticks[N], side, n, m;
bool visited[N];
bool DFS(int sum, int number, int position){
if(number == 3) return true;
int sample = 0;
for(int i = position;i < m;i++){
if(visited[i] || sum + sticks[i] > side || sticks[i] == sample) continue;
visited[i] = true;
if(sum + sticks[i] == side){
if(DFS(0, number + 1, 0)) return true;
else sample = sticks[i];
}else{
if(DFS(sum + sticks[i], number, i + 1)) return true;
else sample = sticks[i];
}
visited[i] = false;
}
return false;
}
bool cmp(int x, int y){
return x > y;
}
int main(){
scanf("%d", &n);
while(n--){
scanf("%d", &m);
int total = 0;
for(int i = 0;i < m;i++){
scanf("%d", &sticks[i]);
total += sticks[i];
}
if(total % 4 != 0) printf("no\n");
else{
side = total / 4;
memset(visited, false, sizeof(visited));
sort(sticks, sticks + m, cmp);
if(sticks[0] > side){
printf("no\n");
continue;
}
if(DFS(0, 0, 0)) printf("yes\n");
else printf("no\n");
}
}
return 0;
}