import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.InputStreamReader;

import java.util.ArrayList;

import java.util.LinkedList;

import java.util.Queue;

import java.util.StringTokenizer;


class People {

int no;

int cept = -1;

int pair = -1;


public People(int no) {

this.no = no;

}


public void tag(int i) {


if (cept == -1) {

cept = i;

} else if (pair == -1) {

pair = i;

}

}



}


class Factory {


int seatSize;

int[] state;

People[] seat;


ArrayList<Integer> wList;

Queue<People> inQueue;

Queue<People> outQueue;


public Factory(ArrayList<Integer> wList, Queue inQueue, Queue outQueue) {

this.seatSize = wList.size();


this.wList = wList;

this.inQueue = inQueue;

this.outQueue = outQueue;


state = new int[seatSize];

seat = new People[seatSize];

for(int i=0 ; i<seatSize; i++) {

state[i] = wList.get(i);

}

}


public void tick() {


for (int i = 0; i < seatSize; i++) {

if (seat[i]!=null && state[i] != 0) {

state[i]--;

}

}


}


public void comeOut() {


for (int i = 0; i < seatSize; i++) {

if (seat[i]!=null && state[i] == 0) {

outQueue.offer(seat[i]);

state[i] = wList.get(i);

seat[i] = null;

}

}


}


public void comeIn() {


for (int i = 0; i < seatSize; i++) {

if (state[i] == wList.get(i)) {

if (!inQueue.isEmpty()) {

seat[i] = inQueue.poll();

seat[i].tag(i+1);

// Solution.log(seat[i]!=null ?"O":"X");

}

}

}


}


}


class Solution {


static boolean Debug = true;

private static int T;


public static void main(String args[]) throws Exception {


BufferedReader br;

if (Debug) {

// C:\Users\wvimi\Downloads\input (2).txt

File f = new File("C:\\Users\\wvimi\\Downloads", "sample_input (8).txt");

FileReader reader = new FileReader(f);

br = new BufferedReader(reader);

} else {

br = new BufferedReader(new InputStreamReader(System.in)); // 직접입력시 이용

}


StringTokenizer st;


int TestSize = Integer.parseInt(br.readLine());

for (T = 1; T <= TestSize; T++) {


st = new StringTokenizer(br.readLine());

int ReceptSize = Integer.parseInt(st.nextToken());

int RepairSize = Integer.parseInt(st.nextToken());

int CustomerNum = Integer.parseInt(st.nextToken());

int ReceptUseNo = Integer.parseInt(st.nextToken());

int RepairUseNo = Integer.parseInt(st.nextToken());


// 좌석 마다 걸리는 시간

st = new StringTokenizer(br.readLine());

ArrayList<Integer> cepList = new ArrayList();

for (int i = 0; i < ReceptSize; i++) {

cepList.add(Integer.parseInt(st.nextToken()));

}

// 좌석 마다 걸리는 시간

ArrayList<Integer> piarList = new ArrayList();

st = new StringTokenizer(br.readLine());

for (int i = 0; i < RepairSize; i++) {

piarList.add(Integer.parseInt(st.nextToken()));

}


// 고객 오는 스케줄

st = new StringTokenizer(br.readLine());

ArrayList<Integer> duleList = new ArrayList();

for (int i = 0; i < CustomerNum; i++) {

duleList.add(Integer.parseInt(st.nextToken()));

}


// 로비1(대기), 로비2(대기), 로비3(완료)

Queue<People> Robby1 = new LinkedList();

Queue<People> Robby2 = new LinkedList();

Queue<People> Robby3 = new LinkedList();


Factory cepFactory = new Factory(cepList, Robby1, Robby2);

Factory pairFactory = new Factory(piarList, Robby2, Robby3);


boolean isduleEnd = false;

int timer = -1;

while (true) {

timer++;


// Robby1에 손님 입장

if (!isduleEnd) {

for (int i = 0; i < CustomerNum; i++) {

// 시간이 되면 입장한다.

if (duleList.get(i) == timer) {

Robby1.offer(new People(i+1));

// 마지막 고객까지 나갔다면

if (i == CustomerNum) {

isduleEnd = true;

}

}

}

}


// 시간이 흐른다. (작업량 1감소)

cepFactory.tick();

pairFactory.tick();


// 완료된 사람은 다음 장소로 이동.

cepFactory.comeOut();

pairFactory.comeOut();


// 대기 중인 사람은 들어온다.

cepFactory.comeIn();

pairFactory.comeIn();


if (Robby3.size() == CustomerNum) {

// 모든 고객이 일을 마친다면...

break;

}

}


int Answer = 0;


People person;

while(!Robby3.isEmpty()) {

person = Robby3.poll();

// 지갑을 놓고온 접수, 수리 테이블을 이용한 고객을 추적

if(person.cept == ReceptUseNo && person.pair == RepairUseNo) {

Answer += person.no;

}else {

// Non-target

}

}


System.out.println(String.format("#%d %d", T, Answer > 0 ? Answer : -1));

}


}


public static void log(String input) {

if (Debug) {

System.out.println(input);

}

}


public static void log(String input, Object... args) {

if (Debug) {

System.out.println(String.format(input, args));

}

}


}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
import java.util.StringTokenizer;
 
class Bar {
    int head, tail;
 
    public Bar(int head, int tail) {
        this.head = head;
        this.tail = tail;
    }
}
 
class Solution {
 
    static boolean Debug = false;
    static int BarSize;
 
    private static int T;
    private static int MaxCount;
    private static Queue<Integer> AnswerQueue;
 
    private static ArrayList<Bar> bList;
    private static int[] visited;
    private static int[] headInfo;
 
    public static void main(String args[]) throws Exception {
 
        BufferedReader br;
        if (Debug) {
            // C:\Users\wvimi\Downloads\input (2).txt
            File f = new File("디렉토리", "input (2).txt");
            FileReader reader = new FileReader(f);
            br = new BufferedReader(reader);
        } else {
            br = new BufferedReader(new InputStreamReader(System.in)); // 직접입력시 이용
        }
 
        StringTokenizer st;
 
        int TestSize = Integer.parseInt(br.readLine());
        for (T = 1; T <= TestSize; T++) {
 
            // BarSize ;
            st = new StringTokenizer(br.readLine());
            BarSize = Integer.parseInt(st.nextToken());
 
            // 초기화
            visited = new int[BarSize];
            headInfo = new int[BarSize];
            bList = new ArrayList<>();
 
            //
            Hashtable<Integer, Integer> startList = new Hashtable<>();
             
            // 시작의 경우의 수
            Bar item;
            int head, tail;
            st = new StringTokenizer(br.readLine());
            for (int i = 0; i < BarSize; i++) {
                head = Integer.parseInt(st.nextToken());
                tail = Integer.parseInt(st.nextToken());
                 
                item = new Bar(head, tail);
                bList.add(item);
                headInfo[i] = head;
                 
            }
 
            // 완전탐색
            MaxCount = 0;
            AnswerQueue = new LinkedList<>();
            for(int i=0; i <BarSize; i++) {
                findPath(i);
            }
             
            // log(MaxStack.toString());
             
            // 값 출력
            int index;
            Bar bar;
            String result = String.format("#%d", T);
            while(!AnswerQueue.isEmpty()) {
                index = AnswerQueue.poll();
                bar = bList.get(index);
                result += String.format(" %d %d", bar.head, bar.tail);
            }
 
            System.out.println(result);
        }
 
    }
 
    static Stack<Integer> bStack = new Stack();
    private static void findPath(int index) {
        visited[index] = 1;
        bStack.add(index);
 
        boolean isLast = true;
        int tail = bList.get(index).tail;
        for (int i = 0; i < BarSize; i++) {
            if (visited[i] == 0 && headInfo[i] == tail) {
                findPath(i);
                isLast = false;
            }
        }
         
        if(isLast) {
            // log("완성: " + bStack.toString());
            if(MaxCount < bStack.size()) {
                MaxCount = bStack.size();
                 
                AnswerQueue.clear();
                AnswerQueue.addAll(bStack);
            }
        }
 
        visited[index] = 0;
        bStack.pop();
    }
     
    private static void log(String input) {
        if (Debug) {
            System.out.println(input);
        }
    }
 
    private static void log(String input, Object... args) {
        if (Debug) {
            System.out.println(String.format(input, args));
        }
    }
 
}


import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.InputStreamReader;

import java.util.ArrayList;

import java.util.Stack;

import java.util.StringTokenizer;


class Home {

int x, y;


public Home(int y, int x) {

this.y = y;

this.x = x;

}

}


class Solution {


static boolean Debug = false;

static int MapSize, ServFee;

static int[][] Map;

static ArrayList<Home> hList;


private static int T;

private static int MaxCount;


public static void main(String args[]) throws Exception {


BufferedReader br;

if (Debug) {

File f = new File("디렉토리", "sample_input (7).txt");

FileReader reader = new FileReader(f);

br = new BufferedReader(reader);

} else {

br = new BufferedReader(new InputStreamReader(System.in)); // 직접입력시 이용

}


StringTokenizer st;


int TestSize = Integer.parseInt(br.readLine());

for (T = 1; T <= TestSize; T++) {


// MapSize , ServFee ;

st = new StringTokenizer(br.readLine());

MapSize = Integer.parseInt(st.nextToken());

ServFee = Integer.parseInt(st.nextToken());


// 맵 데이터 & 홈 집합

hList = new ArrayList<>();

Map = new int[MapSize][];

for (int i = 0; i < MapSize; i++) {

Map[i] = new int[MapSize];

st = new StringTokenizer(br.readLine());

for (int j = 0; j < MapSize; j++) {

Map[i][j] = Integer.parseInt(st.nextToken());

if (Map[i][j] == 1) {

hList.add(new Home(i, j));

}

}

}


// 완전탐색

MaxCount = 0;

findPath();


System.out.println(String.format("#%d %d", T, MaxCount));

}


}


private static void findPath() {


// [준비] 최대 방범 크기는?

int maxSize = -1;

for (int k = 1; ; k++) {

int profit = ServFee * hList.size() - (k * k + (k - 1) * (k - 1));

if (profit >= 0) {

maxSize = k;

} else {

break;

}

}

// log("hSize: %d  ,  maxSize: %d", hList.size(), maxSize);


int tempCount;

// 1. 크기를 적용한다.

for (int s = maxSize; s >= 0; s--) {

// 2. 좌표를 돈다.

for (int i = 0; i < MapSize * MapSize; i++) {

// 해당 좌표에서 해당 크기에, 몇개의 집이 들어가는가?

tempCount = countHome(s, i);

// log("countHome(%d,%d) = %d", s, i, tempCount);

if (MaxCount < tempCount) {

MaxCount = tempCount;

}

}

}


}


private static int countHome(int scanSize, int xy) {

// log("countHome(%d,%d)", scanSize, xy);


int y = xy / MapSize;

int x = xy % MapSize;


Stack<Home> dStack = new Stack<>();

int gap;

for (Home home : hList) {

gap = ((x - home.x) > 0 ? (x - home.x) : (home.x - x));

gap += ((y - home.y) > 0 ? (y - home.y) : (home.y - y));


if (gap < scanSize) {

dStack.add(home);

} else {

// Non-target

}

}


int Profit = dStack.size() * ServFee;

Profit -= scanSize * scanSize + (scanSize - 1) * (scanSize - 1);


return Profit >= 0 ? dStack.size() : 0;

}


private static void log(String input) {

if (Debug) {

System.out.println(input);

}

}


private static void log(String input, Object... args) {

if (Debug) {

System.out.println(String.format(input, args));

}

}


}

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.InputStreamReader;

import java.util.ArrayList;

import java.util.Stack;

import java.util.StringTokenizer;


class Virus {

int x, y;

int amount;

int rIndex;


public Virus(int y, int x, int amount, int rIndex) {

this.y = y;

this.x = x;

this.amount = amount;

this.rIndex = rIndex;

}


public int getXY() {

return Solution.MapSize * y + x;

}


}


class Solution {


static boolean Debug = false;

static int MapSize, TimeSize, VirusLen;

static ArrayList<Virus> vList;


private static int T;


public static void main(String args[]) throws Exception {


BufferedReader br;

if (Debug) {

File f = new File("디렉토리", "sample_input (5).txt");

FileReader reader = new FileReader(f);

br = new BufferedReader(reader);

} else {

br = new BufferedReader(new InputStreamReader(System.in)); // 직접입력시 이용

}


StringTokenizer st;


int TestSize = Integer.parseInt(br.readLine());

for (T = 1; T <= TestSize; T++) {


// MapSize , TimeSize , VirusLen;

st = new StringTokenizer(br.readLine());

MapSize = Integer.parseInt(st.nextToken());

TimeSize = Integer.parseInt(st.nextToken());

VirusLen = Integer.parseInt(st.nextToken());


// 균데이터

vList = new ArrayList<>();

int y, x, amount, rIndex;

for (int i = 0; i < VirusLen; i++) {

st = new StringTokenizer(br.readLine());

y = Integer.parseInt(st.nextToken());

x = Integer.parseInt(st.nextToken());

amount = Integer.parseInt(st.nextToken());

rIndex = Integer.parseInt(st.nextToken()) - 1;


vList.add(new Virus(y, x, amount, rIndex));

}


// 매초마다 시뮬레이션

for (int i = 0; i < TimeSize; i++) {

moveVirus();

modifyVirus();

}


// 결과 출력

int sumAmount = 0;

for (Virus item : vList) {

sumAmount += item.amount;

}


// 길찾기 (시작점은 가장 큰 수)

System.out.println(String.format("#%d %d", T, sumAmount));

}


}


private static void modifyVirus() {


int[] check = new int[MapSize * MapSize];

Stack<Integer> dStack = new Stack();


// 방향변경(반전) 및 해독제 효과(1/2)

for (Virus virus : vList) {


if (virus.x == 0 || virus.x == MapSize - 1) {

virus.rIndex = (virus.x == 0 ? 3 : 2); // 2(좌) 3(우)

virus.amount = virus.amount / 2;

} else if (virus.y == 0 || virus.y == MapSize - 1) {

virus.rIndex = (virus.y == 0 ? 1 : 0); // 0(상) 1(하)

virus.amount = virus.amount / 2;

}


// 중복값에 대한 좌표값 체크

// log("virus x:%d , y:%d", virus.x, virus.y);

if (++check[virus.getXY()] == 2) {

dStack.add(virus.getXY());

}


}


// 좌표가 중복되는  Virus

Stack<Virus> vStack = new Stack<>();

for (int xy : dStack) {

int maxAmount = -1;

int sumAmount = 0;


// 좌표가 같은 Virus 집단

for (Virus virus : vList) {

// log("v.amount: %d", virus.amount);


if (virus.getXY() == xy) {

vStack.add(virus);

sumAmount += virus.amount;

if (maxAmount < virus.amount) { // 같을 경우는 없다고 문제에서 가정

maxAmount = virus.amount;

}

} else {

// Non-target

}

}

// log("max: %d, sum: %d", maxAmount, sumAmount);

// 중복균 제거 & 병합

while (!vStack.isEmpty()) {

Virus virus = vStack.pop();

virus.amount = (virus.amount != maxAmount) ? 0 : sumAmount;

if (virus.amount == 0) {

vList.remove(virus);

}

}


}


}


// 상하좌우

static int[] rotX = { 0, 0, -1, 1 };

static int[] rotY = { -1, 1, 0, 0 };


private static void moveVirus() {

// 움직인다.

for (Virus virus : vList) {

int index = virus.rIndex;


virus.x = virus.x + rotX[index];

virus.y = virus.y + rotY[index];

}

}


private static void log(String input) {

if (Debug) {

System.out.println(input);

}

}


private static void log(String input, Object... args) {

if (Debug) {

System.out.println(String.format(input, args));

}

}


}

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.InputStreamReader;

import java.util.ArrayList;

import java.util.Stack;

import java.util.StringTokenizer;



class Solution {


static boolean Debug = false;

static int MapSize, DigSize;

static int Highset;

static int[][] Map;

static int[][] Visited;

private static int T;

private static int Answer;


public static void main(String args[]) throws Exception {


BufferedReader br;

if (Debug) {

File f = new File("C:\\Users\\wvimi\\Downloads", "sample_input (4).txt");

FileReader reader = new FileReader(f);

br = new BufferedReader(reader);

} else {

br = new BufferedReader(new InputStreamReader(System.in)); // 직접입력시 이용

}


StringTokenizer st;


int TestSize = Integer.parseInt(br.readLine());

for (T = 1; T <= TestSize; T++) {


// MapSize , DigSize , 본문 예제

st = new StringTokenizer(br.readLine());

MapSize = Integer.parseInt(st.nextToken());

DigSize = Integer.parseInt(st.nextToken());


// 지도데이터

Map = new int[MapSize][];

Visited = new int[MapSize][];

Highset = 0;

for (int i = 0; i < MapSize; i++) {

Map[i] = new int[MapSize];

Visited[i] = new int[MapSize];

st = new StringTokenizer(br.readLine());

for (int j = 0; j < MapSize; j++) {

Map[i][j] = Integer.parseInt(st.nextToken());

if (Highset < Map[i][j]) {

Highset = Map[i][j];

}

}

}


// 길찾기 (시작점은 가장 큰 수)

ArrayList<Integer> startList = new ArrayList<>();

for (int i = 0; i < MapSize; i++) {

for (int j = 0; j < MapSize; j++) {

if (Highset == Map[i][j]) {

startList.add(i * MapSize + j);

}

}

}


Answer = 0;

for (int item : startList) {

findPath(item / MapSize, item % MapSize, 0);

}


System.out.println(String.format("#%d %d", T, Answer));

}


}


static int rotX[] = { 0, 1, 0, -1 };

static int rotY[] = { 1, 0, -1, 0 };

static Stack<Integer> pStack = new Stack<>();


// 모든 경로를 탐색하는 알고리즘

private static void findPath(int y, int x, int hint) {

Visited[y][x] = 1;

pStack.push(Map[y][x]);


Boolean isLast = true;


for (int i = 0; i < 4; i++) {

int moveY = y + rotY[i];

int moveX = x + rotX[i];


int path = isRight(moveY, moveX, Map[y][x]);

if (path == 1) { // 힌트 없이 전진

findPath(moveY, moveX, hint);

isLast = false;

} else if (path == 0 && hint == 0) {

// 힌트 사용하여 전진

findPath(moveY, moveX, 1);

isLast = false;

} else {

// 못간다.

}

}

if (isLast) {

// 모든 가능한 경로에 도달한 경우

int count = countLength(pStack);

if (count>0) {

if(Answer < count) {

Answer = count;

}

}

}


Visited[y][x] = 0;

pStack.pop();

}


// 탐색경로에서 길이를 체크해주는 함수

private static int countLength(Stack<Integer> inStack) {


ArrayList<Integer> list = new ArrayList<>();

list.addAll(inStack);


// [9, 7, 7, 3, 2]

// a = 7, b= 7, c =3

int temp = list.get(0);

int findIndex = -1;

int size = list.size();

for (int i = 1; i < size; i++) {

if (temp > list.get(i)) {

temp = list.get(i);

} else {

findIndex = i; // found b-index

break;

}

if(i==size-1) {

return list.size();

}

}


int a, b, c; // 오름차순

a = list.get(findIndex - 1);

b = list.get(findIndex);

c = (findIndex + 1 != list.size()) ? list.get(findIndex + 1) : -1;


if(((b - a) + 1 <= DigSize)) { // 땅을 팔 수 있는 경우

if(a > c + 1) { // c가 a보다 2이상 차이 나는 경우, 이 후 순서도 보장

return size;

}else { // c가 a보다 크거나 같은 경우

return findIndex + 1; // b까지 옳음  (b_index + 1개 )

}

}else {

return findIndex ; // b-1 까지 옳음 (b_index-1 + 1개 )

}

}


// 경로 가능성 판단

private static int isRight(int y, int x, int num) {

// 갈수 있으면 1, 숫자 크기 때문에 못가면 0, 범위 밖이면 -1, 방문했던 곳 -1

if (y < 0 || y >= MapSize || x < 0 || x >= MapSize) {

return -1;

}


if (Visited[y][x] == 1) {

return -1;

}

return Map[y][x] < num ? 1 : 0;

}



private static void log(String input) {

System.out.println(input);

}


}

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.InputStreamReader;

import java.util.Stack;

import java.util.StringTokenizer;


class Solution {


static boolean Debug = false;

static int MapSize, GetSize, Capacity;

static int[][] Map;

private static int MaxProfit;


public static void main(String args[]) throws Exception {


BufferedReader br;

if (Debug) {

File f = new File("파일경로", "sample_input (3).txt");

FileReader reader = new FileReader(f);

br = new BufferedReader(reader);

} else {

br = new BufferedReader(new InputStreamReader(System.in)); // 직접입력시 이용

}


StringTokenizer st;


int T_Count = Integer.parseInt(br.readLine());

for (int T = 1; T <= T_Count; T++) {


// MapSize=4, GetSize=2, Capacity=13

st = new StringTokenizer(br.readLine());

MapSize = Integer.parseInt(st.nextToken());

GetSize = Integer.parseInt(st.nextToken());

Capacity = Integer.parseInt(st.nextToken());


// 지도데이터

Map = new int[MapSize][];

for (int i = 0; i < MapSize; i++) {

Map[i] = new int[MapSize];

st = new StringTokenizer(br.readLine());

for (int j = 0; j < MapSize; j++) {

Map[i][j] = Integer.parseInt(st.nextToken());

}

}


// 이용정보

MaxProfit = -1;

search();


System.out.println(String.format("#%d %d", T, MaxProfit));

}


}


private static void search() {


// 일꾼의 위치1, 위치2

int y1, x1, y2, x2;

for (int i = 0; i < MapSize * MapSize; i++) {

for (int j = i; j < MapSize * MapSize; j++) {


y1 = i / MapSize;

x1 = i % MapSize;


y2 = j / MapSize;

x2 = j % MapSize;


if (isRight(y1, x1, y2, x2) == false) {

continue;

}


// 계산하기

calculate(y1, x1, y2, x2);


}

}


}


private static void calculate(int y1, int x1, int y2, int x2) {

// 현재 좌표에서 최대의 벌꿀 수익량

int maxOne = 0, maxTwo = 0;

int one, two;

for (int i = 0; i < (1 << GetSize); i++) {

// Case (벌꾼 담기)

one = getProfit(y1, x1, i);

two = getProfit(y2, x2, i);


if (maxOne < one) {

maxOne = one;

}


if (maxTwo < two) {

maxTwo = two;

}

}

if(MaxProfit < maxOne + maxTwo) {

MaxProfit = maxOne + maxTwo;

}

}


private static Stack<Integer> pStack = new Stack<>();


private static int getProfit(int y, int x, int bitmask) {


int amount = 0;

for (int i = 0; i < GetSize; i++) {

// 현재 경우에서 일꾼 1의 수익량

if ((bitmask & (1 << i)) > 0) {

// i번째 꿀 수집

amount += Map[y][x + i];

pStack.push(Map[y][x + i]);

}

}


if (amount > Capacity) {

pStack.clear();

return 0;

} else {

int profit = 0;

int temp;

while (!pStack.isEmpty()) {

temp = pStack.pop();

profit += temp * temp;

}

return profit;

}

}


private static boolean isRight(int y1, int x1, int y2, int x2) {


if (y1 >= MapSize || y2 >= MapSize) {

// log("맵 사이즈 초과");

return false;

}

if (x1 + GetSize - 1 >= MapSize || x2 + GetSize - 1 >= MapSize) {

// log("맵 사이즈 초과");

return false;

}


int gap;

if (y1 == y2) {

gap = x1 - x2;

gap = gap > 0 ? gap : -gap;


if (gap < GetSize) {

return false;

}

}


return true;

}


private static void log(String input) {

if (Debug) {

System.out.println(input);

}

}


}

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.InputStreamReader;

import java.util.Arrays;

import java.util.Stack;

import java.util.StringTokenizer;


class Solution {


static boolean Debug = false;

static int[] Ticket = new int[4];

static int[] TicketCounter = new int[4];

static int[] Data = new int[12];

static int[] Visited = new int[12];

static int Data_Length = 12;

static int MIN_COST;

static int FIRST_DAY;


public static void main(String args[]) throws Exception {


BufferedReader br;

if (Debug) {

File f = new File("파일경로", "sample_input.txt");

FileReader reader = new FileReader(f);

br = new BufferedReader(reader);

} else {

br = new BufferedReader(new InputStreamReader(System.in)); // 직접입력시 이용

}


StringTokenizer st;


int T_Count = Integer.parseInt(br.readLine());

for (int T = 1; T <= T_Count; T++) {


// 가격정보

st = new StringTokenizer(br.readLine());

for (int i = 0; i < 4; i++) {

Ticket[i] = Integer.parseInt(st.nextToken());

TicketCounter[i] = 0;

}


FIRST_DAY = -1;

// 이용정보

st = new StringTokenizer(br.readLine());

for (int i = 0; i < 12; i++) {

Data[i] = Integer.parseInt(st.nextToken());

Visited[i] = (Data[i] == 0 ? 1 : 0);

if(FIRST_DAY == -1 && Data[i]!=0) {

FIRST_DAY = i;

}

}

MIN_COST = Integer.MAX_VALUE;

findFee();

System.out.println(String.format("#%d %d", T, MIN_COST));

}


}


static int[] rot = new int[] { 1, 30, 120, 360 };


static Stack<Integer> debug = new Stack();

private static void findFee() {


// 순차적 접근을 위하여, 가장 최초 index에서 시작

int next = -1;

for (int i = 0; i < Data_Length; i++) {

if (Visited[i] == 0) {

next = i;

break; 

}

}

if (next == -1) {

log(debug.toString());

writeMinCost();

return;

}


for (int i = 0; i < 4; i++) {

if (!isRight(next, rot[i])) {

continue;

}

checkPay(next, i, true);

debug.add(i);

findFee();

checkPay(next, i, false);

debug.pop();

}


}


private static void checkPay(int index, int rindex, boolean isGo) {


if (rot[rindex] == 1) {

TicketCounter[rindex] += isGo ? Data[index] : -Data[index];

} else {

TicketCounter[rindex] += isGo ? 1 : -1;

}


switch (rot[rindex]) {

case 360:

for (int i = 0; i < Data_Length; i++) {

if (Data[i] == 0) {

continue;

}

Visited[i] = isGo ? 1 : 0;

}

break;

case 120:

for (int i = index; (i < index + 3) && i < Data_Length; i++) {

if (Data[i] == 0) {

continue;

}

Visited[i] = isGo ? 1 : 0;

}

break;

case 30:

case 1:

if (Data[index] == 0) {

return;

}

Visited[index] = isGo ? 1 : 0;

break;

}


}


private static boolean isRight(int index, int day) {

if (Visited[index] == 1 || Data[index] == 0) {

return false;

}


// 비용계산

if (day == 360) {

return index == FIRST_DAY;

} else if (day == 120) {

return  Ticket[2] <= getCost(index, 1, 3) && Ticket[2] <= getCost(index, 30, 3);

} else if (day == 30) {

int month_fee = getCost(index, 30, 1);

int day_fee = getCost(index, 1, 1);

return month_fee <= day_fee;

} else if (day == 1) {

int month_fee = getCost(index, 30, 1);

int day_fee = getCost(index, 1, 1);

return month_fee >= day_fee;

}


return false;

}


private static int getCost(int index, int day, int length) {


if (day == 1) { // 1일로 구매한다면

int day_count = 0;

for (int i = index; i < index + length && i < Data_Length; i++) {

day_count += Data[i];

}

return day_count * Ticket[0];

} else if (day == 30) { // 1달로 구매한다면

int month_count = 0;

for (int i = index; i < index + length && i < Data_Length; i++) {

if (Data[i] > 0) {

month_count += 1;

}

}

return month_count * Ticket[1];

}


return Integer.MAX_VALUE;

}


private static void writeMinCost() {

int sum = 0;


for (int i = 0; i < 4; i++) {

if (TicketCounter[i] != 0) {

sum += (Ticket[i] * TicketCounter[i]);

}

}


if(MIN_COST>sum) {

MIN_COST = sum;

}

}


private static void log(String input) {

if (Debug) {

System.out.println(input);

}

}


}

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.InputStreamReader;

import java.util.StringTokenizer;



class Solution {


static int DataLen;

static String[][] map;

static boolean Debug = false;


public static void main(String args[]) throws Exception {


BufferedReader br;

if(Debug) {

File f = new File("C:\\Users\\wvimi\\eclipse-workspace\\HelloWorld2\\input", "input (0).txt");

FileReader reader = new FileReader(f);

br = new BufferedReader(reader);

}else {

br = new BufferedReader(new InputStreamReader(System.in)); // 직접입력시 이용

}

DataLen = Integer.parseInt(br.readLine());

int CommandLen = Integer.parseInt(br.readLine());


// 입력부

StringTokenizer st; 

map = new String[DataLen][];

for (int i = 0; i < DataLen; i++) {

map[i] = new String[DataLen];

st = new StringTokenizer(br.readLine());

for (int j = 0; j < DataLen; j++) {

map[i][j] = st.nextToken();

}

}


// 실행부

String result = "";

int y, x, num;

for (int i = 0; i < CommandLen; i++) {

st = new StringTokenizer(br.readLine());

y = Integer.parseInt(st.nextToken()) -1;

x = Integer.parseInt(st.nextToken()) -1;

num = Integer.parseInt(st.nextToken());

Amount = 0;

goPath(y,x, num);

result = String.format("#%d %d", i+1, Amount);

System.out.println(result);

}


}


static int rotX[] = { 1, 0, -1, 0 };

static int rotY[] = { 0, 1, 0, -1 };

static int Amount;

static private void goPath(int y, int x, int num) {

if(num==0) {

Amount = (map[y][x].charAt(1) - '0') * 1000 ;

return;

}


int move_len = map[y][x].charAt(1) - '0'; // 거리

int rot; // 방위

switch (map[y][x].charAt(0)) {

case 'E': // +x

rot = 0;

break;

case 'W': // -x

rot = 2;

break;

case 'S': // y+

rot = 1;

break;

case 'N': // y-

rot = 3;

break;

default: // input case Error

rot = -1; 

}

int move_y = y + move_len* rotY[rot];

int move_x = x + move_len* rotX[rot];

if(isRight(move_y, move_x)) {

goPath(move_y, move_x, num-1);

}else {

Amount = 10000;

}

}


static private boolean isRight(int y, int x) {

if (x < 0 || x > DataLen - 1 || y < 0 || y > DataLen - 1) {

return false;

}


return true;

}


private static void log(String input) {

if (true) {

System.out.println(input);

}

}


}

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.util.ArrayList;

import java.util.StringTokenizer;


class Solution {


static int knum, depth, Width;

static int[][] data;

static boolean Converse;

private static int Result;

private static boolean Debug = false;


public static void main(String args[]) throws Exception {


BufferedReader br;

br = new BufferedReader(new InputStreamReader(System.in));

StringTokenizer st;

int TestNo = Integer.parseInt(br.readLine());

for (int T = 1; T <= TestNo; T++) {

st = new StringTokenizer(br.readLine());


// 문제 읽기

depth = Integer.parseInt(st.nextToken());

Width = Integer.parseInt(st.nextToken());

knum = Integer.parseInt(st.nextToken());


data = new int[depth][];

// 데이터 읽기

for (int i = 0; i < depth; i++) {

data[i] = new int[Width];

st = new StringTokenizer(br.readLine());

for (int j = 0; j < Width; j++) {

data[i][j] = Integer.parseInt(st.nextToken());

}

}


Result = -1;

if (isOkay()) { // 원형 그대로 두어도 Okay

Result = 0;

}


for (int i = 1; i <= knum; i++) { // i개의 행에 약물 주입

if (Result >= 0) {

break; // 찾았으면 종료

}


visitingList = new ArrayList<>(); // 중복검색 방지

possibleList = new ArrayList<Integer>(); // 1이 i개인 이진수 탐색


int con_i = i > Width / 2 ? Width - i : i;

Converse = i > Width / 2;


findPossible(con_i, 0); // 1이 i개인 이진수 탐색


for (int j = 0; j < possibleList.size(); j++) {

log(Integer.toBinaryString(possibleList.get(j)));


Result = inputMedi(possibleList.get(j)); // (약물 주입) 행들의 집합을 넘긴다.

if (Result > 0) {

break; // 찾았으면 종료

}


}

}


System.out.println(String.format("#%d %d", T, Result));

}


}




static ArrayList<Integer> possibleList;

static ArrayList<Integer> visitingList;


// width개 중 i개를 선택한다.

private static void findPossible(int i, int bitinfo) {

if (bitinfo >= (1 << depth + 1)) {

return;

}


int count = 0;

for (int j = 0; j < depth; j++) {

if ((bitinfo & (1 << j)) > 0) {

count++;

if (count == i) {

log(Integer.toBinaryString(bitinfo));

possibleList.add(bitinfo);

return;

}

}

}


for (int j = 0; j < depth; j++) {

if ((bitinfo & (1 << j)) > 0) {

continue;

}

int next_bitinfo = bitinfo + (1 << j);

if (visitingList.contains(next_bitinfo)) {

continue;

}

visitingList.add(next_bitinfo);

findPossible(i, next_bitinfo);

}

}


public static int inputMedi(int selbit) {


ArrayList<Integer> pocket = new ArrayList<Integer>();

// 사용되는 열 추출


int con_selbit = selbit;


if (Converse) {

con_selbit = 0;

for (int i = 0; i < Width; i++) {

if ((selbit & (1 << i)) == 0) {

con_selbit += (1 << i);

}

}

}


for (int i = 0; i < Width; i++) {

if ((con_selbit & (1 << i)) > 0) {

pocket.add(i);

}

}


// boolean isFound;

int size = pocket.size();


// 1,0의 적용의 경우의 수

for (int i = 0; i < 1 << size; i++) {

// log(Integer.toBinaryString(i));

if (isOkay(i, pocket)) {

return pocket.size();

}

}


return -1;

}


private static boolean isOkay(int bitmask, ArrayList<Integer> pocket) {


int depth = data.length;

int width = data[0].length;


int a_count;

int b_count;


for (int i = 0; i < width; i++) {

a_count = b_count = 0;

int atom;

for (int j = 0; j < depth; j++) { // 한 열을 검사

atom = data[j][i];

if (pocket.indexOf(j) >= 0) {

boolean isOne = (bitmask & (1 << pocket.indexOf(j))) > 0;

atom = isOne ? 1 : 0;

}


if (atom == 1) {

if (b_count != 0) {

a_count = b_count = 0;

}

a_count++;

} else {

if (a_count != 0) {

a_count = b_count = 0;

}

b_count++;

}

if (a_count == knum || b_count == knum) {

break;

}

if (j == depth - 1) {

return false;

}

}

}


log(Integer.toBinaryString(bitmask) + pocket.toString());

return true;


}


private static boolean isOkay() {

int depth = data.length;

int width = data[0].length;


int a_count;

int b_count;


for (int i = 0; i < width; i++) {

a_count = b_count = 0;

for (int j = 0; j < depth; j++) { // 한 열을 검사

if (data[j][i] == 1) {

if (b_count != 0) {

a_count = b_count = 0;

}

a_count++;

} else {

if (a_count != 0) {

a_count = b_count = 0;

}

b_count++;

}

if (a_count == knum || b_count == knum) {

break;

}

if (j == depth - 1) {

return false;

}

}

}


return true;

}


private static void log(String input) {

if (Debug) {

System.out.println(input);

}

}


}

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.InputStreamReader;

import java.util.ArrayList;

import java.util.LinkedList;

import java.util.Queue;

import java.util.Stack;

import java.util.StringTokenizer;


class Edge {

int start, end;

int weight;


public Edge(int start, int end, int weight) {

this.start = start;

this.end = end;

this.weight = weight;

}

}


class Node<T> extends ArrayList<T> {

public static Node[] Tree;

public int nodeNo;

public int parentNo;

public int rank;


public void makeSet(int x) {

nodeNo = x;

parentNo = x;

rank = 0;

}


public int findSet() {


Stack<Integer> nodeStack = new Stack<>();


nodeStack.add(nodeNo); // 검색 노드 조건

Node moveNode = Tree[nodeNo];

while (moveNode.nodeNo != moveNode.parentNo) { // 부모 노드 조건

moveNode = Tree[moveNode.parentNo];

nodeStack.add(parentNo);

}


if (nodeStack.size() > 1) { // 찾은 부모가 있다면

int represent = moveNode.nodeNo;


while (!nodeStack.isEmpty()) { // 부모노드를 가르키도록

Tree[nodeStack.pop()].parentNo = represent;

}

}


return moveNode.nodeNo;

}


public void unionSet(Node<T> node) {

Node first = Tree[this.nodeNo];

Node second = Tree[node.nodeNo];

int f = first.findSet();

int s = second.findSet();

if (f == s) {

return;

}


first = Tree[f];

second = Tree[s];


if (first.rank > second.rank) {

second.parentNo = first.nodeNo;

} else {

first.parentNo = second.nodeNo;

if (this.rank == node.rank) {

node.rank++;

}

}

}


}


class Solution {


static int DATA_SIZE;

static Node<Edge>[] tree;

static Boolean isFound;

static int[] visited;

static int[] distance;

static boolean Debug = true;


public static void main(String args[]) throws Exception {


BufferedReader br;

if (Debug) {

File f = new File("C:\\Users\\wvimi\\Downloads", "input (29).txt");

FileReader reader = new FileReader(f);

br = new BufferedReader(reader);

} else {

br = new BufferedReader(new InputStreamReader(System.in));

}


StringTokenizer st;

int start, end, weight;

int testNo = Integer.parseInt(br.readLine());

for (int T = 1; T <= 6; T++) {

st = new StringTokenizer(br.readLine());

int nodeNum = Integer.parseInt(st.nextToken());

int taskNum = Integer.parseInt(st.nextToken());


StringBuffer sb = new StringBuffer();

System.out.print(String.format("#%d", T, nodeNum, taskNum));

log("");


tree = new Node[nodeNum + 1];

visited = new int[nodeNum + 1];

distance = new int[nodeNum + 1];


Node.Tree = tree;

for (int i = 0; i < tree.length; i++) {

tree[i] = new Node<Edge>();

tree[i].makeSet(i);

}

// [방법2]

ArrayList<Integer> representList = new ArrayList<>();


for (int i = 0; i < taskNum; i++) {

st = new StringTokenizer(br.readLine());

switch (st.nextToken()) {

case "!":

start = Integer.parseInt(st.nextToken());

end = Integer.parseInt(st.nextToken());

weight = Integer.parseInt(st.nextToken());


tree[start].add(new Edge(start, end, weight));

tree[end].add(new Edge(end, start, -1 * weight));

tree[start].unionSet(tree[end]);

break;

case "?":

start = Integer.parseInt(st.nextToken());

end = Integer.parseInt(st.nextToken());


// findPath(start, end);

int a = tree[start].findSet();

int b = tree[end].findSet();

if (a == b) {

// [방법2 ] 무게의 상대값을 기록하여 재활용하기

// if(!representList.contains((Integer) a)) {

// representList.add(a);

// visited = new int[nodeNum + 1];

// distance = new int[nodeNum + 1];

// }

int w_end = findWeight(end);

int w_start = findWeight(start);

int answer = w_end - w_start;


sb.append(String.format(" %d", answer));

} else {

sb.append(" UNKOWN");

}

break;

}

}


System.out.println(sb.toString());

}


}


private static int findWeight(int nodeNo) {

if (visited[nodeNo] == 1) {

log(String.format("3. distance[%d] = %d", nodeNo, distance[nodeNo]));

return distance[nodeNo];

}


// 연결된 노드를 찾는다.

int subParent = 0;

Queue<Integer> que = new LinkedList();

que.add(nodeNo);

Stack<Integer> visiting = new Stack();


while (!que.isEmpty()) {

int reStart = que.poll();

log(String.format("nodeNo:%d    reStart: %d", nodeNo, reStart));

for (Edge line : tree[reStart]) {

log(String.format("visited[%d] = %d", line.end, visited[line.end]));

if (visited[line.end] == 1 || line.end == tree[nodeNo].parentNo) {

// 무게가 기록된 연결된 노드를 찾음 || 부모노드

subParent = line.end;

break;

}

que.add(line.end);

visited[line.end] = 1;

visiting.add(line.end);

}

}


for (int i : visiting) {

visited[i] = 0;

}

que = new LinkedList();

que.add(subParent);

log("subParent 진입: " + subParent);

while (!que.isEmpty()) {

int reStart = que.poll();

for (Edge line : tree[reStart]) {

if (visited[line.end] == 1) {

continue;

}

// que.add(line.end);

que.add(line.end);

visited[line.end] = 1;

distance[line.end] = distance[line.start] + line.weight;

log(String.format("2. distance[%d] = %d", line.end, distance[line.end]));


if (line.end == nodeNo) {

return distance[line.end];

}

}

}


return -1;

}

private static void log(String input) {

if (true) {

System.out.println(input);

}

}


}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
 
class Solution {
 
    public static void main(String args[]) throws Exception {
 
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 
        for (int T = 1; T <= 10; T++) {
 
            // [input] 데이터 입력
            int dataSize = Integer.parseInt(br.readLine());
            String[] originData = br.readLine().trim().split(" ");
            int commandSize = Integer.parseInt(br.readLine());
            String[] commandData = br.readLine().trim().split(" ");
 
            LinkedList<Integer> ticket = new LinkedList<>();
 
            for (int i = 0; i < originData.length; i++) {
                ticket.add(Integer.parseInt(originData[i]));
            }
 
            int cnt = 0;
            while (cnt < commandData.length) {
                String Command = commandData[cnt++];
                 
                int commandIndex = -1;
                if(!Command.equals("A")) {
                    commandIndex = Integer.parseInt(commandData[cnt++]);
                }
                 
                int Valuecount = Integer.parseInt(commandData[cnt++]);
 
                if(Command.equals("I")) {
                    int insertValue;
                    for (int j = 0; j < Valuecount; j++) {
                        insertValue = Integer.parseInt(commandData[cnt++]);
                        ticket.add(commandIndex++, insertValue);
                    }
                }else if(Command.equals("D")) {
                    for (int j = 0; j < Valuecount; j++) {
                        ticket.remove(commandIndex);
                    }
                }else {
                    int addValue;
                    for (int j = 0; j < Valuecount; j++) {
                        addValue = Integer.parseInt(commandData[cnt++]);
                        ticket.add(addValue);
                    }
                }
                 
            }
 
            String result = String.format("#%d", T);
            for (int i = 0; i < 10; i++) {
                result += String.format(" %d", ticket.get(i));
            }
             
            System.out.println(result);
        }
 
    }
 
}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Stack;
 
class Solution {
 
 
    public static void main(String args[]) throws Exception {
 
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 
        for (int T = 1; T <= 10; T++) {
 
            Stack<Character> operStack = new Stack<>();
            Stack<Character> postStack = new Stack<>();
             
            Stack<Integer> calStack = new Stack<>();
 
            // [input] CaseNo DataLen
            int testLen = Integer.parseInt(br.readLine());
 
            // [input] 데이터 입력 ex. "(3+5+(4+3*6))", "3*2*6*(2+3)+4+1+5*7*8"
            String readLine = br.readLine();
             
            // Part1. 후위연산으로 변환
            for (int i = 0; i < testLen; i++) {
                char input = readLine.charAt(i);
                 
                if(input == '(') {
                    operStack.push(input);
                }else if(input == ')') {
                    while(operStack.peek()!='(') { // 연산자 스택에는 괄호가 pair로 존재
                        // 괄호 안에 연산자가 남아있는 연산자 처리 (우선순위가 높은 연산자, 혹
                        postStack.push(operStack.pop());
                    }
                    operStack.pop(); // ( ) 까지 연산을 끝냈으므로  '('을 날림
                }else if(input >= '0' && input <='9') {
                    postStack.push(input);
                }else {
                    // 연산자가 2번 연달아오기 직전 5 + 6 * 7 + 8
                    // post: [5,6,7] oper: [+,*] input:'+' => post: [5,6,7,*,+] oper[+]
                     
                    // case1(While 통과). 우선순위가 낮거나 같은 연산자가 온 경우, 연산자 스택의 pop하여 후위연산 배열에 넣는다.
                    while(!operStack.isEmpty() && priority(input) >= priority(operStack.peek())) {
                        postStack.push(operStack.pop());
                        if(operStack.isEmpty()) {
                            break;
                        }
                    }
                    // case2(While 무시). 우선순위가 높은 연산자가 input으로 왔을 때는, 연산자스택의 값을 pop하지 않는다.
                     
                    operStack.push(input); // 최근 연산자는 스택에 저장
                }
            }
             
            // 괄호가 없는 input 값이 주어졌다면, 마지막에 스택에는 마지막 연산자가 남아있다.
            while(!operStack.isEmpty()) {
                postStack.push(operStack.pop());
            }
             
             
            // Part2. 계산과정
            int x,y;
            int length = postStack.size();
            Character[] postArr = new Character[length];
            postStack.toArray(postArr);
             
            for(int i=0; i<length; i++) {
                char item = postArr[i];
                // System.out.print(item); 후위연산 변환 디버깅
                if(item >= '0' && item <= '9') {
                    calStack.push(item-'0');
                }else if(item == '*') {
                    x = calStack.pop();
                    y = calStack.pop();
                    calStack.push(x*y);
                }else if(item == '+') {
                    x = calStack.pop();
                    y = calStack.pop();
                    calStack.push(x+y);
                }
            }
 
            System.out.println(String.format("#%d %d", T, calStack.pop()));
        }
 
    }
 
    // 연산자 우선 순위 (값이 낮을 수록 우선순위가 높다)
     
    private static int priority(char c) {
        switch(c) {
        case '(':   return 5; // 괄호가 로직에 영향을 주지 않도록 큰 값을 부여
        case '*':   return 1;
        case '-':   return 2
        case '+':   return 2;
        default : return -1;
        }
    }
 
}


import java.util.Scanner;
import java.util.Stack;
 
class Solution {
 
    public static void main(String args[]) throws Exception {
 
        Scanner sc = new Scanner(System.in);
        int[] pair = new int[256]; // 아스키코드
         
        pair['('] = ')';
        pair['['] = ']';
        pair['{'] = '}';
        pair['<'] = '>';
         
        for (int T = 1; T <= 10; T++) {
 
            Stack<Character> stack = new Stack();
            boolean possible = true;
 
            // [input] Test 번호
            int inputLen = Integer.parseInt(sc.nextLine());
             
            // [input] 데이터 입력 & 풀이
            String line = sc.nextLine();
            for (int i = 0; i < inputLen; i++) {
                 
                char input = line.charAt(i);
                // 괄호시작
                if(input == '(' ||input == '[' ||input == '{' ||input == '<')
                {
                    stack.push(input);
                }
                 
                // 괄호끝
                if(input == ')' ||input == ']' ||input == '}' ||input == '>')
                {
                    if(stack.empty()) {
                        possible = false;
                        break;
                    }
                     
                    if(pair[stack.pop().charValue()] != input) {
                        possible = false;
                        break;
                    }
                }
            }
 
            System.out.println(String.format("#%d %d", T, possible?1:0));
        }
 
    }
 
}


+ Recent posts