Square (DFS) 剪枝
#include<bits/stdc++.h>
using namespace std;
const int Max=20;
int stick[Max];
bool visit[Max];
int m;
int side;
bool DFS(int sum,int number,int p){
if(number==3){
cout<<"yes"<<endl;
return true;
}
int error=0;
for(int i=p;i<m;i++){
if(visit[i]||sum+stick[i]>side||stick[i]==error){
continue;
}
visit[i]=1;
if(sum+stick[i]==side){
if(DFS(0,number+1,0)){
return 1;
}
else{
error=stick[i]; //说明这根木棍放在这里不合适。
}
}
else{
if(DFS(stick[i]+sum,number,p)){
return 1;
}
else{
error=stick[i]; //说明这根木棍放在这里不合适。
}
}
visit[i]=0;
}
return 0;
}
bool Com(int x,int y){
return x>y;
}
int main() {
int caseN;
cin>>caseN;
while(caseN--) {
memset(visit,0,sizeof(visit));
int sum=0;
cin>>m;
for(int i=0; i<m; i++) {
cin>>stick[i];
sum+=stick[i];
}
sort(stick,stick+m);
if(sum%4!=0) {
cout<<"no"<<endl;
continue;
}
side=sum/4;
if(stick[0]>side){
cout<<"no"<<endl;
continue;
}
visit[0]=true;
if(!DFS(0,0,0)){
cout<<"no"<<endl;
}
}
return 0;
}
using namespace std;
const int Max=20;
int stick[Max];
bool visit[Max];
int m;
int side;
bool DFS(int sum,int number,int p){
if(number==3){
cout<<"yes"<<endl;
return true;
}
int error=0;
for(int i=p;i<m;i++){
if(visit[i]||sum+stick[i]>side||stick[i]==error){
continue;
}
visit[i]=1;
if(sum+stick[i]==side){
if(DFS(0,number+1,0)){
return 1;
}
else{
error=stick[i]; //说明这根木棍放在这里不合适。
}
}
else{
if(DFS(stick[i]+sum,number,p)){
return 1;
}
else{
error=stick[i]; //说明这根木棍放在这里不合适。
}
}
visit[i]=0;
}
return 0;
}
bool Com(int x,int y){
return x>y;
}
int main() {
int caseN;
cin>>caseN;
while(caseN--) {
memset(visit,0,sizeof(visit));
int sum=0;
cin>>m;
for(int i=0; i<m; i++) {
cin>>stick[i];
sum+=stick[i];
}
sort(stick,stick+m);
if(sum%4!=0) {
cout<<"no"<<endl;
continue;
}
side=sum/4;
if(stick[0]>side){
cout<<"no"<<endl;
continue;
}
visit[0]=true;
if(!DFS(0,0,0)){
cout<<"no"<<endl;
}
}
return 0;
}