1043번: 거짓말

지민이는 파티에 가서 이야기 하는 것을 좋아한다. 파티에 갈 때마다, 지민이는 지민이가 가장 좋아하는 이야기를 한다. 지민이는 그 이야기를 말할 때, 있는 그대로 진실로 말하거나 엄청나게

www.acmicpc.net

 

 

 

 


 

 

 

  • 풀이

 

 

bfs방식으로 party를 돌아가며 겹치는 사람들까지 검사하며 솔직하게 말해야 되는 party가 있으면 총 파티 수에서 마이너스

 

 

  • 코드

 

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Queue;

public class Main {
	static int N, M, answer;
	static ArrayList<Integer>[] array;
	static boolean[] check, partyCheck;

	public static void main(String[] args) throws Exception {
		SetData();
		System.out.println(answer);
	}

	// 데이터
	private static void SetData() throws Exception {
		InputReader in = new InputReader(System.in);

		N = in.nextInt();
		M = in.nextInt();
		answer = M;
		check = new boolean[N + 1];
		partyCheck = new boolean[M];
		array = new ArrayList[M];

		int truesNumber = in.nextInt();
		for (int i = 0; i < truesNumber; i++) {
			check[in.nextInt()] = true;
		}

		for (int i = 0; i < M; i++) {
			array[i] = new ArrayList<Integer>();
			int size = in.nextInt();
			for (int j = 0; j < size; j++) {
				array[i].add(in.nextInt());
			}
		}

		SaveAnswer();
	}

	public static void SaveAnswer() {
		Queue<Integer> queue = new LinkedList<>();

		for (int i = 0; i <= N; i++) {
			if (check[i])	queue.add(i);
		}

		while (!queue.isEmpty()) {
			int now = queue.poll();

			for (int i = 0; i < M; i++) {
				if (partyCheck[i] || !array[i].contains(now))		continue;

				partyCheck[i] = true;
				answer--;				
				for (int j = 0; j < array[i].size(); j++) {
					int next = array[i].get(j);

					if (check[next]) continue;
					
					check[next] = true;
					queue.offer(next);					
				}				
			}
		}
	}
}

class InputReader {
	private final InputStream stream;
	private final byte[] buf = new byte[8192];
	private int curChar, snumChars;

	public InputReader(InputStream st) {
		this.stream = st;
	}

	public int read() {
		if (snumChars == -1)
			throw new InputMismatchException();
		if (curChar >= snumChars) {
			curChar = 0;
			try {
				snumChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (snumChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}

	public int nextInt() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public long nextLong() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		long res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public int[] nextIntArray(int n) {
		int a[] = new int[n];
		for (int i = 0; i < n; i++) {
			a[i] = nextInt();
		}
		return a;
	}

	public String nextLine() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isEndOfLine(c));
		return res.toString();
	}

	public boolean isSpaceChar(int c) {
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	private boolean isEndOfLine(int c) {
		return c == '\n' || c == '\r' || c == -1;
	}
}

 

2003번: 수들의 합 2

첫째 줄에 N(1 ≤ N ≤ 10,000), M(1 ≤ M ≤ 300,000,000)이 주어진다. 다음 줄에는 A[1], A[2], …, A[N]이 공백으로 분리되어 주어진다. 각각의 A[x]는 30,000을 넘지 않는 자연수이다.

www.acmicpc.net

 

 

 

 


 

 

 

  • 풀이

 

투포인터 문제이다.

왼쪽부터 오른쪽으로 sum이 M보다 작으면 right를 더해주면서 증가, sum이 M보다 크거나 같으면 left를 빼주면서 증가

 

 

  • 코드

 

import java.io.IOException;
import java.io.InputStream;
import java.util.InputMismatchException;

public class Main {
	static int N, M, answer;
	static int[] array;
	
	public static void main(String[] args) throws Exception {
		SetData();
		System.out.println(answer);
	}

	// 데이터
	private static void SetData() throws Exception {
		InputReader in = new InputReader(System.in);

		N = in.nextInt();
		M = in.nextInt();
		answer = 0;
		array = new int[N+1];
        
		for(int i = 0; i < N; i++)
			array[i] = in.nextInt();
		
		TwoPoint(0, 0);
	}
	
	private static void TwoPoint(int left, int right) {
		int sum = 0;
		while(right <= N) {			
			if(sum >= M)
				sum -= array[left++];				
			else
				sum += array[right++];
			
			if(sum == M) 	answer++;			
		}
	}
}

class InputReader {
	private final InputStream stream;
	private final byte[] buf = new byte[8192];
	private int curChar, snumChars;

	public InputReader(InputStream st) {
		this.stream = st;
	}

	public int read() {
		if (snumChars == -1)
			throw new InputMismatchException();
		if (curChar >= snumChars) {
			curChar = 0;
			try {
				snumChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (snumChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}

	public int nextInt() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public long nextLong() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		long res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public int[] nextIntArray(int n) {
		int a[] = new int[n];
		for (int i = 0; i < n; i++) {
			a[i] = nextInt();
		}
		return a;
	}

	public String nextLine() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isEndOfLine(c));
		return res.toString();
	}

	public boolean isSpaceChar(int c) {
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	private boolean isEndOfLine(int c) {
		return c == '\n' || c == '\r' || c == -1;
	}
}

 

1074번: Z

한수는 크기가 2N × 2N인 2차원 배열을 Z모양으로 탐색하려고 한다. 예를 들어, 2×2배열을 왼쪽 위칸, 오른쪽 위칸, 왼쪽 아래칸, 오른쪽 아래칸 순서대로 방문하면 Z모양이다. 만약, N > 1이 라서

www.acmicpc.net

 

 

 

 


 

 

 

 

 

  • 풀이

 

사각형을 4등분하면서 2x2(n이 2일때) Z모양으로 탐색을 해주며 횟수를 증가시켜주었다.

 

 

  • 코드

 

import java.io.IOException;
import java.io.InputStream;
import java.util.InputMismatchException;

public class Main {
	static int N, r, c, answer;
	static int[] x = {0, 0, 1, 1};
	static int[] y = {0, 1, 0, 1};

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

	// 데이터
	private static void SetData() throws Exception {
		InputReader in = new InputReader(System.in);

		N = in.nextInt();
		r = in.nextInt();
		c = in.nextInt();
		answer = 0;
		
        dfs((int)Math.pow(2, N), 0, 0);
	}

    private static void dfs(int n, int i, int j) {
        if(n == 2) {
            for (int direction = 0; direction < 4; direction++) {
                int rx = i + x[direction];
                int ry = j + y[direction];
            	
                if (rx == r && ry == c) {
                    System.out.println(answer);
                    System.exit(0);
                }
                answer++;
            }
            return;
        }
        
		for (int s = i; s < i+n; s+=n/2) {
			for (int e = j; e < j+n; e+=n/2) {
				if(s+n/2-1<r || e+n/2-1<c) {
					answer+=(n/2)*(n/2);
					continue;
				}
				dfs(n/2,s,e);
			}
		}
    }
}

class InputReader {
	private final InputStream stream;
	private final byte[] buf = new byte[8192];
	private int curChar, snumChars;

	public InputReader(InputStream st) {
		this.stream = st;
	}

	public int read() {
		if (snumChars == -1)
			throw new InputMismatchException();
		if (curChar >= snumChars) {
			curChar = 0;
			try {
				snumChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (snumChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}

	public int nextInt() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public long nextLong() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		long res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public int[] nextIntArray(int n) {
		int a[] = new int[n];
		for (int i = 0; i < n; i++) {
			a[i] = nextInt();
		}
		return a;
	}

	public String nextLine() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isEndOfLine(c));
		return res.toString();
	}

	public boolean isSpaceChar(int c) {
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	private boolean isEndOfLine(int c) {
		return c == '\n' || c == '\r' || c == -1;
	}
}

 

1992번: 쿼드트리

첫째 줄에는 영상의 크기를 나타내는 숫자 N 이 주어진다. N 은 언제나 2의 제곱수로 주어지며, 1 ≤ N ≤ 64의 범위를 가진다. 두 번째 줄부터는 길이 N의 문자열이 N개 들어온다. 각 문자열은 0 또

www.acmicpc.net

 

 

 

 

 


 

 

 

 

 

  • 풀이

 

 압축하기 위해서는 부분 영역이 모두 같은 색상이어야 한다.

 

처음 사각형에서부터 4등분하면서 같은 색만있으면 출력해주면서 계속 재귀로 들어간다.

 

 

 

  • 코드

 

import java.io.IOException;
import java.io.InputStream;
import java.util.InputMismatchException;

public class Main {
	static int N, answer;
	static StringBuilder sb;
	static int[][] array;
	
	public static void main(String[] args) throws Exception {
		SetData();
		System.out.println(sb);
	}

	// 데이터
	private static void SetData() throws Exception {
		InputReader in = new InputReader(System.in);

		N = in.nextInt();
		sb = new StringBuilder();		
		array = new int[N][N];	
        
		for(int i = 0; i < N; i++) {
			String s = in.nextLine();
			
			for(int j = 0; j < N; j++) {
				array[i][j] = s.charAt(j) - '0';
			}
		}

		dfs(N, 0, 0);
	}

	private static void dfs(int n, int i, int j) {
		// 압축 가능
		if(compression(n, i, j)) {
			sb.append(array[i][j]);
			return;
		}

		n = n / 2;	
		
		sb.append('(');	
		
		dfs(n, i, j);	// 왼위
		dfs(n, i, j + n);	// 오위
		dfs(n, i + n, j);	// 왼밑
		dfs(n ,i + n, j + n);	// 오밑
		
		sb.append(')');	
	}
	
	public static boolean compression(int n, int i, int j) {
		int value = array[i][j];
		
		for(int x = i; x < i + n; x++) {
			for(int y = j; y < j + n; y++) {
				if(value != array[x][y]) {
					return false;
				}
			}
		}
		return true;
	}
}

class InputReader {
	private final InputStream stream;
	private final byte[] buf = new byte[8192];
	private int curChar, snumChars;

	public InputReader(InputStream st) {
		this.stream = st;
	}

	public int read() {
		if (snumChars == -1)
			throw new InputMismatchException();
		if (curChar >= snumChars) {
			curChar = 0;
			try {
				snumChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (snumChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}

	public int nextInt() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public long nextLong() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		long res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public int[] nextIntArray(int n) {
		int a[] = new int[n];
		for (int i = 0; i < n; i++) {
			a[i] = nextInt();
		}
		return a;
	}

	public String nextLine() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isEndOfLine(c));
		return res.toString();
	}

	public boolean isSpaceChar(int c) {
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	private boolean isEndOfLine(int c) {
		return c == '\n' || c == '\r' || c == -1;
	}
}

 

2688번: 줄어들지 않아

첫째 줄에 테스트 케이스의 개수 T(1 <= T <= 1,000)이 주어진다. 각 테스트 케이스는 숫자 하나 n으로 이루어져 있다. (1 <= n <= 64)

www.acmicpc.net

 

 

 


 

 

 

  • 풀이

 

 

문제를 읽어보면 각 자리수마다 줄어들지 않는 수의 개수를 찾는 문제이다.

 

문제를 읽은다음 DP라고 알 수 있었던 부분은 전의 계산이 뒤의 계산에 중복된 영향을 끼친다는 것이다.

 

예를 들면)

1의 자리 수 - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9로 10개이다.

2의 자리 수 - 00, 01, 11 ...이런식으로 온다. 제약사항이 앞에 숫자가 뒤의 숫자보다 작거나 같아야한다.

 

이걸 토대로 점화식을 찾을 수 있나 그려보았다.

 

 

 

다음과 같은 점화식을 찾을 수 있었다.

 

이러한 점화식을 통해 구현한 코드이다.

 

		array[0][0] = 1;
		array[0][1] = 1;
		array[0][2] = 1;
		array[0][3] = 1;
		array[0][4] = 1;
		array[0][5] = 1;
		array[0][6] = 1;
		array[0][7] = 1;
		array[0][8] = 1;
		array[0][9] = 1;
		
		for(int i = 1 ; i < 65; i++) {
			for(int j = 0; j < 10; j++) {
				for (int k = 0; k <= j; k++) {
					array[i][j] += array[i - 1][k];
				}
			}
		}

 

 

 

  • 코드

 

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Queue;

public class Main {
	static int T;
	static long[][] array;
	static StringBuilder sb;

	public static void main(String[] args) throws Exception {
		SetData();
		System.out.println(sb);
	}

	// 데이터
	private static void SetData() throws Exception {
		InputReader in = new InputReader(System.in);

		T = in.nextInt();
		sb = new StringBuilder();
		array = new long[65][10];
		
		array[0][0] = 1;
		array[0][1] = 1;
		array[0][2] = 1;
		array[0][3] = 1;
		array[0][4] = 1;
		array[0][5] = 1;
		array[0][6] = 1;
		array[0][7] = 1;
		array[0][8] = 1;
		array[0][9] = 1;
		
		for(int i = 1 ; i < 65; i++) {
			for(int j = 0; j < 10; j++) {
				for (int k = 0; k <= j; k++) {
					array[i][j] += array[i - 1][k];
				}
			}
		}
		
		for(int t = 0; t < T; t++) {
			int n = in.nextInt();
			
			long sum = 0;
			for(int i = 0 ; i < 10; i++) {
				sum += array[n-1][i];
			}
			
			sb.append(sum).append("\n");
		}
	}
}

class InputReader {
	private final InputStream stream;
	private final byte[] buf = new byte[8192];
	private int curChar, snumChars;

	public InputReader(InputStream st) {
		this.stream = st;
	}

	public int read() {
		if (snumChars == -1)
			throw new InputMismatchException();
		if (curChar >= snumChars) {
			curChar = 0;
			try {
				snumChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (snumChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}

	public int nextInt() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public long nextLong() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		long res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public int[] nextIntArray(int n) {
		int a[] = new int[n];
		for (int i = 0; i < n; i++) {
			a[i] = nextInt();
		}
		return a;
	}

	public String nextLine() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isEndOfLine(c));
		return res.toString();
	}

	public boolean isSpaceChar(int c) {
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	private boolean isEndOfLine(int c) {
		return c == '\n' || c == '\r' || c == -1;
	}
}

 

14490번: 백대열

n과 m이 :을 사이에 두고 주어진다. (1 <= n, m <= 100,000,000)

www.acmicpc.net

 

 

 

 


 

 

 

 

  • 풀이

 

n과 m을 최대 공약수로 나누어주면 되는 문제이다. 최대 공약수는 재귀형식(유클리드 호제법)으로 구했다.

 

 

  • 코드

 

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Queue;

public class Main {
	static StringBuilder sb;

	public static void main(String[] args) throws Exception {
		SetData();
		System.out.println(sb);
	}

	// 데이터
	private static void SetData() throws Exception {
		InputReader in = new InputReader(System.in);

		String[] s = in.nextLine().split(":");
		sb = new StringBuilder();
		
		int n = Integer.parseInt(s[0]);
		int m = Integer.parseInt(s[1]);
		int gcd = GCD(n,m);
		
		sb.append(n/gcd+":"+m/gcd);
	}
	
	// 최대 공약수 구하는 재귀메소드
	private static int GCD(int a, int b) {
        if (b == 0) return a;
        return GCD(b, a % b);
    }
}

class InputReader {
	private final InputStream stream;
	private final byte[] buf = new byte[8192];
	private int curChar, snumChars;

	public InputReader(InputStream st) {
		this.stream = st;
	}

	public int read() {
		if (snumChars == -1)
			throw new InputMismatchException();
		if (curChar >= snumChars) {
			curChar = 0;
			try {
				snumChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (snumChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}

	public int nextInt() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public long nextLong() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		long res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public int[] nextIntArray(int n) {
		int a[] = new int[n];
		for (int i = 0; i < n; i++) {
			a[i] = nextInt();
		}
		return a;
	}

	public String nextLine() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isEndOfLine(c));
		return res.toString();
	}

	public boolean isSpaceChar(int c) {
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	private boolean isEndOfLine(int c) {
		return c == '\n' || c == '\r' || c == -1;
	}
}

 

11062번: 카드 게임

근우와 명우는 재미있는 카드 게임을 하고 있다. N개의 카드가 일렬로 놓여 있다. 각 카드에는 점수가 적혀있다. 근우부터 시작하여 번갈아가면서 턴이 진행되는데 한 턴에는 가장 왼쪽에 있는

www.acmicpc.net

 

 

 

 


 

 

 

  • 풀이

 

분할 정복을 사용해서 푼 코드이다.

 

왼쪽, 오른쪽의 경우의 수로 재귀형식으로 파고들어 결국엔 가장 큰 경우의 데이터를 가져온다.

 

  • 코드

 

 

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Queue;

public class Main {
	static int T, N;
	static int[] input;
	static int[][][] array;
	static StringBuilder sb;

	public static void main(String[] args) throws Exception {
		SetData();
		System.out.println(sb);
	}

	// 데이터
	private static void SetData() throws Exception {
		InputReader in = new InputReader(System.in);

		T = in.nextInt();
		sb = new StringBuilder();
		
		for (int t = 0; t < T; t++) {
			N = in.nextInt();

			input = new int[N];
			for (int i = 0; i < N; i++) {
				input[i] = in.nextInt();
			}

			array = new int[2][N][N];
			sb.append(SaveAnswer(0, 0, N-1) + "\n");
		}
	}
	
	static int SaveAnswer(int who, int left, int right) {
		// basecase
		if (left == right) {
			if (who == 0) {
				return array[who][left][right] = input[left];
			}
			else {
				return array[who][left][right] = 0;
			}
		}
		
		if (array[who][left][right] != 0)
			return array[who][left][right];

		// 근우
		if (who == 0) {
			array[who][left][right] = Math.max(SaveAnswer(1, left + 1, right) + input[left], SaveAnswer(1, left, right - 1) + input[right]);
		}
		else {		// 명우
			array[who][left][right] = Math.min(SaveAnswer(0, left + 1, right), SaveAnswer(0, left, right - 1));
		}
		return array[who][left][right];
	}
}

class InputReader {
	private final InputStream stream;
	private final byte[] buf = new byte[8192];
	private int curChar, snumChars;

	public InputReader(InputStream st) {
		this.stream = st;
	}

	public int read() {
		if (snumChars == -1)
			throw new InputMismatchException();
		if (curChar >= snumChars) {
			curChar = 0;
			try {
				snumChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (snumChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}

	public int nextInt() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public long nextLong() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		long res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public int[] nextIntArray(int n) {
		int a[] = new int[n];
		for (int i = 0; i < n; i++) {
			a[i] = nextInt();
		}
		return a;
	}

	public String nextLine() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isEndOfLine(c));
		return res.toString();
	}

	public boolean isSpaceChar(int c) {
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	private boolean isEndOfLine(int c) {
		return c == '\n' || c == '\r' || c == -1;
	}
}

 

11723번: 집합

첫째 줄에 수행해야 하는 연산의 수 M (1 ≤ M ≤ 3,000,000)이 주어진다. 둘째 줄부터 M개의 줄에 수행해야 하는 연산이 한 줄에 하나씩 주어진다.

www.acmicpc.net

 

 

 

 


 

 

  • 풀이

 

 

HashSet을 사용해서 푼 문제이다. HashSet으로 하는 이유는 입력한 데이터 중 특정 값의 데이터가 있었는지 판단하기 쉽고, 추가하고, 지우기 간편하기 때문이다. 이러한 자료구조는 ArrayList도 있지만 Hashset이 더 빠르기 때문에 사용했다.

 

HashSet과 ArrayList의 차이점은 ArrayList는 넣은 순서대로 저장되지만 HashSet은 순서대로 저장되지 않는다.

이러한 차이점 때문에 HashSet이 더 빠르다고 보면된다.

 

 

참고) 원래는 비트마스킹으로 해결하라고 낸 문제이다.

 

 

 

  • 코드

 

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Queue;

public class Main {
	static int M;
	static HashSet<Integer> set;
	static StringBuilder sb;

	public static void main(String[] args) throws Exception {
		SetData();
		System.out.println(sb);
	}

	// 데이터
	private static void SetData() throws Exception {
		InputReader in = new InputReader(System.in);

		M = in.nextInt();
		set = new LinkedHashSet<>();
		sb = new StringBuilder();		
		
        for(int i = 0; i < M; i++){
            String[] s = in.nextLine().split(" ");
            String command = s[0];

            switch (command){
                case "add" :                	
                    set.add(Integer.parseInt(s[1]));
                    break;

                case "remove":
                    set.remove(Integer.parseInt(s[1]));
                    break;

                case "check" :
                    if(set.contains(Integer.parseInt(s[1]))) sb.append("1\n");
                    else sb.append("0\n");
                    break;
                    
                case "toggle" :
                    if(set.contains(Integer.parseInt(s[1]))) set.remove(Integer.parseInt(s[1]));
                    else set.add(Integer.parseInt(s[1]));
                    break;

                case "all" :
                    for(int num = 1; num<=20; num++){
                        set.add(num);
                    }
                    break;
                    
                case "empty" :
                    set.clear();
                    break;
            }

        }
	}
	
	//private static int SaveAnswer() {
	//}	
}

class InputReader {
	private final InputStream stream;
	private final byte[] buf = new byte[8192];
	private int curChar, snumChars;

	public InputReader(InputStream st) {
		this.stream = st;
	}

	public int read() {
		if (snumChars == -1)
			throw new InputMismatchException();
		if (curChar >= snumChars) {
			curChar = 0;
			try {
				snumChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (snumChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}

	public int nextInt() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public long nextLong() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		long res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public int[] nextIntArray(int n) {
		int a[] = new int[n];
		for (int i = 0; i < n; i++) {
			a[i] = nextInt();
		}
		return a;
	}

	public String nextLine() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isEndOfLine(c));
		return res.toString();
	}

	public boolean isSpaceChar(int c) {
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	private boolean isEndOfLine(int c) {
		return c == '\n' || c == '\r' || c == -1;
	}
}

+ Recent posts