Square
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 5868 Accepted Submission(s): 1869
Problem Description
Given a set of sticks of various lengths, is it possible to join them end-to-end to form a square?
Input
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.
Output
For 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
Source
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Main{//8855163 2013-08-07 11:15:44 Accepted 1518 968MS 3940K 1278 B Java zhangyi
private static boolean vis[],ok=true;
private static Integer a[],sum=0,n;
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int N=input.nextInt();
while(N-->0){
n=input.nextInt();
Init();
int max=0;
for(int i=0;i<n;++i){
a[i]=input.nextInt();
max+=a[i];
}
sum=max>>2;
Arrays.sort(a,new Comparator<Integer>(){ //从大到小排序
@Override
public int compare(Integer o1, Integer o2){
return o2-o1;
}
});
if(max%4==0&&sum>=a[0]){
dfs(0,0,0);//当时少了一个参数,导致超时
if(ok)
System.out.println("yes");
else
System.out.println("no");
}
else{
System.out.println("no");
}
}
}
private static void Init() {
sum=0;
ok=false;
a=new Integer[n];
vis=new boolean[n];
}
private static void dfs(int s, int num,int i) {//一定要加i,否则会超时,下次直接从i处搜
if(ok)
return;
if(num==3){
ok=true;
return;
}
if(s==sum){
dfs(0,num+1,num+1);
}
for(;i<n;i++){
if(!vis[i]){
if(s+a[i]<=sum){
vis[i]=true;
dfs(s+a[i],num,i+1);
vis[i]=false;
}
}
}
}
}
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Main{//1508MS
static boolean vis[];
static Integer a[],arge=0;
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int N=input.nextInt();
while(N-->0){
int n=input.nextInt();
a=new Integer[n];
vis=new boolean[n];
int sum=0;
for(int i=0;i<n;i++){
a[i]=input.nextInt();
sum+=a[i];
}
arge=sum>>2;
if(sum%4==0){
Arrays.sort(a,new Comparator<Integer>(){
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
});
if(arge>=a[0]&&dfs(0,0,0)){
System.out.println("yes");
}
else
System.out.println("no");
}
else{
System.out.println("no");
}
}
}
private static boolean dfs(int len, int num, int i) {
if(num==3)
return true;
if(len==arge){
if(dfs(0,num+1,num+1))
return true;
else
return false;
}
else{
for(;i<a.length;i++){
if(!vis[i]){
if(len+a[i]<=arge){
vis[i]=true;
if(dfs(len+a[i],num,i+1)){
return true;
}
vis[i]=false;
}
}
}
}
return false;
}
}