[SWEA] 8458. 原点集合


コード#コード#

import java.util.Scanner;
import java.io.FileInputStream;

class Solution {
  public static void main(String args[]) throws Exception {
    Scanner sc = new Scanner(System.in);
    int T;
    T = sc.nextInt();

    for (int test_case = 1; test_case <= T; test_case++) {
      int n = sc.nextInt();
      int zeroCount = 0;
      int[] length = new int[n];
      boolean odd = false, even = false;
      for (int i = 0; i < n; i++) {
        length[i] = Math.abs(sc.nextInt()) + Math.abs(sc.nextInt());
        if (length[i] == 0)
          zeroCount++;
        else {
          if (length[i] % 2 == 0)
            even = true;
          else
            odd = true;
        }
      }
      if (zeroCount == n) {
        System.out.println("#" + test_case + " 0");
        continue;
      }
      if (odd && even) {
        System.out.println("#" + test_case + " -1");
        continue;
      }

      int count = 1;
      while (true) {
        int curZeroCount = 0;
        for (int i = 0; i < n; i++) {
          if (length[i] == 0) {	// 0일 때
            if (count % 2 == 1) {
              length[i]++;
            }
          } else {	// 0이 아닐 때
            if (length[i] - count >= 0) {	// 빼도 될 경우
              length[i] -= count;
            } else {    // 범위를 벗어날 경우
              if (length[i] == 1 && count % 2 == 1) {
                length[i]--;
              } else {
                if (count % 2 == 0) {
                  if (length[i] % 2 == 0)
                    length[i] = 0;
                  else 
                    length[i] = 1;
                } else {
                  if (length[i] % 2 == 0) 
                    length[i] = 1; 
                  else 
                    length[i] = 0;
                }
              }
            }
          }
          if (length[i] == 0) curZeroCount++;
        }
        if (curZeroCount == n) break;
        count++;
      }
      
    System.out.println("#" + test_case + " " + count);
    }
  }
}