首页 > 搜索 > DFS搜索 > HDU 1518 Square-DFS-[解题报告] C++
2013
12-12

HDU 1518 Square-DFS-[解题报告] C++

Square

问题描述 :

Given a set of sticks of various lengths, is it possible to join them end-to-end to form a square?

输入:

The first line of input contains N, the number of test cases. Each test case begins with an integer 4 <= M <= 20, the number of sticks. M integers follow; each gives the length of a stick – an integer between 1 and 10,000.

输出:

For each case, output a line containing "yes" if is is possible to form a square; otherwise output "no".

样例输入:

3
4 1 1 1 1
5 10 20 30 40 50
8 1 7 2 6 4 4 3 5

样例输出:

yes
no
yes

不要有侥幸心理,能剪的都剪了再交。

#include <iostream>
using namespace std;

int s[23], n, m, k, l;
bool f, v[23];
void dfs(int l, int u, int c)
{
    if (l==0) l = k, u = m-1, c++;
    if (c>2) f = 1;
    if (f) return ;
    for (int i=u;i>=0;--i)
    if (!v[i] && s[i]<=l)
    {
        v[i] = 1;
        dfs(l-s[i], i-1, c);
        if (f) break;
        v[i] = 0;
        if (l==s[i]) return;
        if (l==k) return;
        while (s[i-1]==s[i]) i--;
    }
}

int main()
{
    for (scanf("%d", &n);n;n--)
    {
        scanf("%d", &m);
        for (int i=f=k=l=0;i<m;scanf("%d", &s[i]),v[i]=0,l+=s[i++])
        if (k<s[i]) s[i] = k;
        sort(s, s+m);
        if (l%4==0 && k<=l/4)
        dfs(k=l/4, m-1, 0);
        if (f) printf("yes\n");
        else printf("no\n");
    }
    return 0;
}

 

解题报告转自:http://blog.csdn.net/welcome_z/article/details/7933137


,