1. 程式人生 > >HDU 1518

HDU 1518

和上一題一樣

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>

using namespace std;

int len[30];
int mark[30];
int ans, m;
int aim;

void dfs(int now, int finish, int k) {
	if(finish == 4) {
		ans = 1;
		return;
	}
	if(ans == 1) return;
	int j;
	for(int i = k+1; i < m; i++) {
		if(mark[i]) continue;
		if(now+len[i] > aim) return;
		mark[i] = 1;
		if(now+len[i] == aim) dfs(0, finish+1, -1);
		else dfs(now+len[i], finish, i);
		mark[i] = 0;
		if(!now) return;
		if(ans) return;
		for(j = i+1; j < m; j++) {
			if(len[j] != len[j-1]) break;
		}
		i = j-1;
	}
}

int main() {
	int n;
	scanf("%d", &n);
	while(n--) {
		int sum = 0;
		memset(mark, 0, sizeof(mark));
		ans = 0;
		scanf("%d", &m);
		for(int i = 0; i < m; i++) {
			scanf("%d", &len[i]);
			sum += len[i];
		}
		sort(len, len+m);
		if(sum%4) {
			printf("no\n");
			continue;
		}
		aim = sum/4;
		dfs(0, 0, -1);
		if(ans) printf("yes\n");
		else printf("no\n");
	}
	return 0;
}