HDU 1518 Square

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

InputThe 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. 
OutputFor each case, output a line containing "yes" if is is possible to form a square; otherwise output "no". 
Sample Input

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

Sample Output

yes
no
yes

简单的DFS,不能被4整除的sum不考虑,先把棍子从小到大排序,确保dfs的正确。然后进行dfs,输入三个形参,cnt成功边数,pos当前位置,res剩余值。注意pos不能省去否则会tle,当cnt==3的时候即可输出

 

#define _CRT_SECURE_NO_WARNINGS
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cmath>
using namespace std;
typedef long long ll;
#define Inf 0x3f3f3f3f
#define Maxn 21

int n;
int mstick[Maxn];
bool book[Maxn];
int x;

bool cmp(int a, int b) {
    return a > b;
}

bool DFS(int cnt, int pos, int res) {
    if (cnt == 3) {
        return true;
    }

    for (int i = pos; i < n; i++) {
        if (book[i]) {
            continue;
        }
        book[i] = true;
        if (mstick[i] == res) {
            if (DFS(cnt + 1, 0, x)) {
                return true;
            }
        }
        else if (mstick[i] < res) {
            if (DFS(cnt, i + 1, res - mstick[i])) {
                return true;
            }
        }
        book[i] = false;
    }
    return false;
}

int main(){
    int m;
    scanf("%d", &m);
    while (m--) {
        scanf("%d", &n);
        int sum = 0;
        for (int i = 0; i < n; i++) {
            scanf("%d", &mstick[i]);
            sum += mstick[i];
        }
        if (sum % 4) {
            printf("no\n");
            continue;
        }
        memset(book, false, sizeof(book));
        x = sum / 4;
        sort(mstick, mstick + n, cmp);


        if (DFS(0, 0, x)) {
            printf("yes\n");
        }
        else {
            printf("no\n");
        }
    }



    return 0;
}

 

posted @ 2020-07-26 19:33  Vetsama  阅读(120)  评论(0)    收藏  举报