toj1398Square

来源:互联网 发布:阿里云和腾讯云百度云 编辑:程序博客网 时间:2024/05/18 01:02


package work;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Square {

 static int total;
 static int N, T;
 static int[] sti;
 static int len;
 static boolean[] isV;

 public static void main(String args[]) throws FileNotFoundException {
  // Scanner sc=new Scanner(System.in);
  Scanner sc = new Scanner(new File("src/1398.txt"));
  T = sc.nextInt();
  for (int t = 0; t < T; t++) {
   total = 0;
   N = sc.nextInt();
   sti = new int[N];
   for (int i = 0; i < N; i++) {
    sti[i] = sc.nextInt();
    total += sti[i];
   }

   if (total % 4 != 0) {
    System.out.println("no");
    continue;
   }
   if (N == 4) {
    if (sti[0] == sti[1] && sti[0] == sti[2] && sti[0] == sti[3]) {
     System.out.println("yes");
    } else
     System.out.println("no");
    continue;
   }
   if (N > 4) {
    Qsort(0, N-1, sti);
    len=total/4;
    isV = new boolean[N];
    if (dfs(0, 0, 0))
     System.out.println("yes");
    else
     System.out.println("no");
   }
  }
 }
 private static boolean dfs(int step, int n, int num) {
  // TODO Auto-generated method stub
  if (num == 3) {
   return true;
  }
  for (int i = step; i < N; i++) {
   if (isV[i]||i>0&&!isV[i-1]&&sti[i]==sti[i-1]) {
    continue;
   }
   if (n + sti[i] == len) {
    isV[i] = true;
    if (dfs(0, 0, num+1))
     return true;
    isV[i] = false;
    return false;
   }
   if (n + sti[i] < len) {
    isV[i] = true;
    if (dfs(step + 1, n + sti[i], num))
     return true;
    isV[i] = false;
    if(n==0)
     return false;
   }
  }
  return false;
 }

 private static void Qsort(int l, int r, int[] ss) {
  // TODO Auto-generated method stub
  if (l < r) {
   int key = ss[r];
   int i = l;
   int j = r;
   while (i < j) {
    while (i < j && ss[i] > key)
     i++;
    ss[j] = ss[i];
    while (i < j && ss[j] <= key)
     j--;
    ss[i] = ss[j];
   }
   ss[j] = key;
   Qsort(l, j - 1, ss);
   Qsort(j + 1, r, ss);
  }
 }

}

、、input

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

、、output

yes
no
yes

0 0