#include<iostream>
#include<algorithm>
#include<fstream>
#include<ctime>
using namespace std;
//#define DEBUG
/* 240K 297MS */
#define MAX 64
static int len[MAX];
static int used[MAX];
static int ok;
static int sum;
static int n;
static int side;
void search_dfs(int start, int curlen, int count)/* 共有4个返回点 */
{
if (count >= 3)
ok = 1;
if (ok == 1)
return ; /* 剪枝,已经找到了*/
for (int i = start; i < n; i++)
{
if (used[i]) continue;
int tmplen = curlen + len[i];
if (tmplen == side) /* 已经找到一条边 */
{
used[i] = 1;
search_dfs(0, 0, count + 1);
used[i] = 0;/* 上面的搜索没有成功时,很重要*/
}
else if (tmplen < side) /* 不足一条边 */
{
used[i] = 1;
search_dfs(i + 1, tmplen, count);
used[i] = 0;
}
else /* 超过一条边,剪枝因为边长升序排列 */
{
return;
}
}
}
int main()
{
#ifdef DEBUG
fstream cin("G:\\book\\algorithms\\acm\\Debug\\dat.txt");
clock_t start, end;
start = clock();
#endif
int t;
cin >> t;
while (t-- > 0)
{
int i;
cin >> n;
for (i = 0, sum = 0; i < n; i++)
{
cin >> len[i];
sum += len[i];
}
sort(len,len + n); //升序排列
if (sum % 4 == 0)
{
side = sum / 4; ok = 0;
memset(used, 0, sizeof used);
search_dfs(0, 0, 0);
if (ok)
printf("yes\n");
else
printf("no\n");
}
else
{
printf("no\n");
}
}
#ifdef DEBUG
end = clock();
cout << "Time:" << (double)(end - start) / CLOCKS_PER_SEC << "S\n";
#endif
return 0;
}
POJ2362
一组小木棒是否能够组成正方形? 使用深度搜索解决该题,总的说来思路比较简单,可以作为深度搜索类题目的一个范本进行复习。先计算出小木棒的总长,判断是否是4的整数倍。如果满足进行深度搜索,深度搜索是采用递归的方式进行设计的,注意观察递归函数的各个出口。