1285번: 동전 뒤집기

첫째 줄에 20이하의 자연수 N이 주어진다. 둘째 줄부터 N줄에 걸쳐 N개씩 동전들의 초기 상태가 주어진다. 각 줄에는 한 행에 놓인 N개의 동전의 상태가 왼쪽부터 차례대로 주어지는데, 앞면이 위

www.acmicpc.net

 

 


 

 

  • 풀이

 

열만 backtracking하면서 메소드를 돌려주고 메소드 안에서 행도 돌려주면서 T의 최소 개수를 찾아준다.

 

 

 

  • 코드
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.List;
import java.util.PriorityQueue;

public class Main {
	static int N, answer;
	static char[][] 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();
		answer = Integer.MAX_VALUE;
		array = new char[N][N];
		
        for(int i = 0; i < N ; i ++){
            array[i] = in.nextLine().toCharArray();
        }
		
        solve(0);
	}
	
    public static void solve(int row){
        if(row == N){
            int count = 0;
            for(char[] i : array){
                int temp = 0;
                for(char j : i){
                    if(j == 'T'){
                        temp ++;
                    }
                }
                count = count + Math.min(temp,N-temp);
            }
            answer = Math.min(count,answer);
            return;
        }
        solve(row+1);
        for(int i = 0 ; i < N; i ++){
            array[i][row] = array[i][row] == 'H'?'T':'H';
        }
        solve(row+1);
    }
}

class Delivery implements Comparable<Delivery> {
	int from;
	int to;
	int weight;

	public Delivery(int from, int to, int weight) {
		this.from = from;
		this.to = to;
		this.weight = weight;
	}

	@Override
	public int compareTo(Delivery o) {
		if (this.to < o.to) {
			return -1;
		} else if (this.to == o.to) {
			if (this.from < o.from) {
				return -1;
			}
		}
		return 1;
	}
}

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;
	}
}

 

8980번: 택배

입력의 첫 줄은 마을 수 N과 트럭의 용량 C가 빈칸을 사이에 두고 주어진다. N은 2이상 2,000이하 정수이고, C는 1이상 10,000이하 정수이다. 다음 줄에, 보내는 박스 정보의 개수 M이 주어진다. M은 1이

www.acmicpc.net

 

 

 


 

 

 

  • 풀이

 

1. 우선순위 큐에 넣으면서 정렬을 시켜줍니다.

2. weight이란 int 배열을 활용해서 모든 마을에 최대로 보낼 수 있는 만큼 택배를 싫어보냅니다.

3. 보낼 때 최대 박스 개수는 answer이란 변수에 추가시켜줍니다.

 

참고) 시간을 좀 더 빨리하기 위해 우선순위 큐를 사용했습니다.

 

 

 

 

  • 반례

 

5 4
5
2 4 1
4 5 3
1 5 1
3 4 2
1 2 2
correct = 9

6 5
6
5 6 2
4 5 3
1 2 2
3 6 2
3 4 3
2 6 1
correct = 12

4 5
4
3 4 1
2 3 4
1 2 1
1 4 4
correct = 7

5 2
6
3 5 1
1 4 1
4 5 1
2 3 1
1 2 1
1 5 2
correct = 5

5 5
4
2 3 2
2 5 3
3 4 1
2 4 1
correct = 6

5 4
7
2 5 4
3 4 1
1 4 4
1 5 3
3 5 1
2 3 3
1 2 3
correct = 9

6 3
8
2 6 3
5 6 1
4 5 3
4 6 2
1 2 1
1 4 1
2 3 2
3 5 2
correct = 8

6 4
12
3 6 4
3 4 3
5 6 4
3 5 4
4 5 4
2 5 4
4 6 3
1 4 4
1 5 1
2 6 3
2 3 3
1 2 3
correct = 18

5 3
3
2 3 2
3 4 1
2 5 2
correct = 4

 

 

 

  • 코드

 

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

public class Main {
	static int C, answer;
	static int[] weight;
	static PriorityQueue<Delivery> queue;

	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);

		int N = in.nextInt();
		C = in.nextInt();
		weight = new int[N + 1];
		int countOfDelivery = in.nextInt();
		answer = 0;
		queue = new PriorityQueue<>();

		for (int i = 0; i < countOfDelivery; i++) {
			queue.add(new Delivery(in.nextInt(), in.nextInt(), in.nextInt()));
		}

		move();
	}

	private static void move() {
		while (!queue.isEmpty()) {
			Delivery delivery = queue.poll();
			
			int temp, max = 0;
			for (int i = delivery.from; i < delivery.to; i++) {
				max = Math.max(max, weight[i]);
			}

			answer += (temp = Math.min(delivery.weight, C - max));

			for (int i = delivery.from; i < delivery.to; i++) {
				weight[i] += temp;
			}
		}
	}
}

class Delivery implements Comparable<Delivery> {
	int from;
	int to;
	int weight;

	public Delivery(int from, int to, int weight) {
		this.from = from;
		this.to = to;
		this.weight = weight;
	}

	@Override
	public int compareTo(Delivery o) {
		if (this.to < o.to) {
			return -1;
		} else if (this.to == o.to) {
			if (this.from < o.from) {
				return -1;
			}
		}
		return 1;
	}
}

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;
	}
}

 

20183번: 골목 대장 호석 - 효율성 2

첫 줄에 교차로 개수 N, 골목 개수 M, 시작 교차로 번호 A, 도착 교차로 번호 B, 가진 돈 C 가 공백으로 구분되어 주어진다. 이어서 M 개의 줄에 걸쳐서 각 골목이 잇는 교차로 2개의 번호와, 골목의

www.acmicpc.net

 

 

 

 


 

 

 

 

  • 풀이

 

아마 생각한대로 풀면 시간초과때문에 많이 애먹는 문제일 것이다.

 

해결 방법은 이분 탐색 + 다익스트라 알고리즘이다.

 

이분 탐색

- 길목 중 가장 높은 값을 갖고 있는 변수를 가장 오른쪽으로 더 빠른 시간내로 돌릴 수 있다.

 

 

  • 코드

 

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.PriorityQueue;

public class Main {
	static int A, B, N, M;
	static long answer, C;
	static long[] dist;
	static ArrayList<Edge>[] 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();
		A = in.nextInt();
		B = in.nextInt();
		C = in.nextLong();
		dist = new long[N + 1];
		array = new ArrayList[N + 1];

		for (int i = 0; i <= N; i++) {
			array[i] = new ArrayList<Edge>();
		}
		Long max = Long.MIN_VALUE;
		
		for (int i = 0; i < M; i++) {
			int a = in.nextInt();
			int b = in.nextInt();
			long c = in.nextLong();
			max = Math.max(max, c);

			array[a].add(new Edge(b,c));
			array[b].add(new Edge(a,c));
		}

		answer = binary(max);
	}

	static private long binary(long max) {
		long answer = -1;
		long l = 0, r = max;
		while (l <= r) {
			long mid = (l + r) / 2;
			if (!Dijkstra(A, mid))
				l = mid + 1;
			else {
				answer = mid;
				r = mid - 1;
			}
		}
		return answer;
	}

	static private boolean Dijkstra(int x, long cost) {
		Arrays.fill(dist, Long.MAX_VALUE);

		PriorityQueue<Edge> pq = new PriorityQueue<>();
		pq.add(new Edge(x,0));
		dist[x] = 0;
		while (!pq.isEmpty()) {
			Edge now = pq.poll();

			if (dist[(int) now.to]<now.weight)
				continue;

			 for (Edge next : array[now.to]) {
				if (cost >= next.weight && dist[next.to] > dist[now.to] + next.weight) {
					dist[next.to] = dist[now.to] + next.weight;
					pq.add(new Edge(next.to, dist[next.to]));
				}
			}
		}

		return dist[B] <= C;
	}

}

class Edge implements Comparable<Edge> {
    int to;
    long weight;

    public Edge(int x, long weight) {
        this.to = x;
        this.weight = weight;
    }

    @Override
    public int compareTo(Edge o) {
        // TODO Auto-generated method stub
        return Long.compare(this.weight, o.weight);
    }
}

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;
	}
}

 

20164번: 홀수 홀릭 호석

호석이는 짝수랑 홀수 중에서 이니셜이 같은 홀수를 더 좋아한다. 운전을 하던 호석이는 앞차의 번호판이 홀수로 가득할 때 사랑스러움을 느낄 정도이다. 전화번호도 홀수만 있고 싶다. 그렇게

www.acmicpc.net

 

 

 

 


 

 

 

  • 풀이

 

숫자를 자르면서 홀수의 수를 구하는 문제이다.

 

1. 숫자가 1자리인 경우 홀수의 개수를 종이에 적고 종료. (basecase이다.)

2. 숫자가 2자리인 경우 2개로 나눠서 합을 구하여 새로운 수로 재귀를 돌린다.

3. 숫자가 3자리 이상인 경우 임의의 위치에서 끊어서 3개의 수로 분할하고, 3개를 더한 값을 새로운 수로 재귀를 돌린다.

 

 

  • 코드

 

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

public class Main {
	static int max, min;

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

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

		String N = in.nextLine();
		max = Integer.MIN_VALUE;
		min = Integer.MAX_VALUE;
		
		Recursion(N, 0);
	}
	
	private static void Recursion(String s, int count) {
		count += getCountOfDecimal(s);
		
		// baseacse
		if(s.length() == 1) {
			max = Math.max(max, count);
			min = Math.min(min, count);
			return;
		}
		
		if(s.length() == 2) {
			Recursion(Integer.toString(Integer.parseInt(s.substring(0,1)) + 
					Integer.parseInt(s.substring(1,2))), count);
			return;
		}
		
		for(int i = 1; i < s.length(); i++) {
			for(int j = i + 1; j < s.length(); j++) {
				Recursion(getSubString(s,i,j), count);
			}
		}
	}
	
	private static int getCountOfDecimal(String s) {
		int count = 0;
		
		for(int i = 0; i < s.length(); i++) {
			if(s.charAt(i) != '0' && (s.charAt(i) - '0') % 2 != 0) {
				count++;
			}
		}
		return count;
	}
	
	private static String getSubString(String s, int a, int b) {
		return Integer.toString(Integer.parseInt(s.substring(0,a)) + 
				Integer.parseInt(s.substring(a,b)) + Integer.parseInt(s.substring(b,s.length())));
	}
}

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;
	}
}

 

1744번: 수 묶기

길이가 N인 수열이 주어졌을 때, 그 수열의 합을 구하려고 한다. 하지만, 그냥 그 수열의 합을 모두 더해서 구하는 것이 아니라, 수열의 두 수를 묶으려고 한다. 어떤 수를 묶으려고 할 때, 위치에

www.acmicpc.net

 

 

 

 


 

 

 

 

  • 풀이

 

1. 먼저 수를 오름차순 or 내림차순으로 정렬한다. (작업을 하는 이유 : 수를 묶어주기 편해짐)

2. 양수는 양수끼리, 음수는 음수끼리 묶어주면 합이 커진다. 또한, 음수는 0이랑도 곱해주고 양수는 곱해줄 때 1을 곱하지 않는다.

 

 

 

  • 참고 반례

 

--------------------------------------------------------------------

case1. 양수기준 - (양수가 짝수개일때) 내림차순으로 정렬했을때 큰값 2개씩 곱해서 답을 도출하는가

input : 4 9 4 2 7
output : 71

--------------------------------------------------------------------

case2. 양수기준 - (양수가 홀수개일때) 내림차순으로 정렬했을 때 큰값 2개씩 곱한 후 마지막에 숫자를 더해서 답을 도출하는가
input : 7 9 7 4 2 8 8 7
output : 158

--------------------------------------------------------------------

case3. 음수기준 - 오름차순으로 정렬했을때 작은값 2개씩 묶어서 답을 도출하는가 (이유 : 음수는 작을수록 두 수를 곱했을때 커지므로)
input : 4 -9 -11 -2 -4
output : 107

--------------------------------------------------------------------

case4. 0이 존재하면서 음수의 개수가 홀수개 일때 마지막 음수를 0으로 처리하는지
input : 8 -10 -5 0 0 0 -11 -9 -2
output : 155

--------------------------------------------------------------------

case5. 1이 존재할때 1은 다른수와 곱하지 않고 바로 더하는지 (이유 : 1보다 큰 수 x와 1이 주어진다면 두수를 곱하는것보다 따로 더해주는게 더 크다)
input : 5 5 4 1 1 1
output : 23

 

 

  • 코드

 

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

public class Main {
	static int N;
	static long 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();
		array = new int[N];
		answer = 0;

		for (int i = 0; i < N; i++)
			array[i] = in.nextInt();

		Arrays.sort(array);
		SaveMaxValue();
	}

	private static void SaveMaxValue() {
		for(int i = N - 2; i >= 0; i-=2) {
			if(array[i] <= 0 || array[i + 1] <= 0) break;
			
			if(array[i] > 1 && array[i + 1] > 1) {
				array[i] *= array[i+1];
				array[i+1] = 0;
			}
		}
		
		for(int i = 1; i < N; i+=2) {
			if(array[i] > 0 || array[i-1] > 0) break;
			
			if(array[i] <= 0 && array[i-1] <= 0) {
				array[i] *= array[i-1];
				array[i-1] = 0;
			}
		}
		
		for(int i = 0; i < N; i++) 
			answer += array[i];
		
	}
}

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;
	}
}

 

1715번: 카드 정렬하기

정렬된 두 묶음의 숫자 카드가 있다고 하자. 각 묶음의 카드의 수를 A, B라 하면 보통 두 묶음을 합쳐서 하나로 만드는 데에는 A+B 번의 비교를 해야 한다. 이를테면, 20장의 숫자 카드 묶음과 30장

www.acmicpc.net

 

 

 


 

 

  • 생각

 

PriorityQueue를 이용하면 쉽게 풀 수 있는 문제이다.

 

1) 카드 묶음을 PriorityQueue에 담는다.

2) 카드 묶음이 1개 이면 0을 출력한다.

3) 카드 묶음이 2개 이상이면 두 카드를 출력 변수에 더 해주고 queue에도 추가시켜준다.

 

 

  • 코드

 

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;

public class Main {
	static int N;
	static PriorityQueue<Long> queue;
	static long answer;

	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();
		queue = new PriorityQueue<Long>();
		answer = 0;
		
		for(int i = 0; i < N; i++)
			queue.add(in.nextLong());
		
		TurnQueue();
	}
	
	private static void TurnQueue() {
		while (queue.size() > 1) {
			long firstCard = queue.poll();
			long secondCard = queue.poll();
			
			answer += firstCard + secondCard;
			queue.add(firstCard + secondCard);
		}
	}
}

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;
	}
}

 

4179번: 불!

입력의 첫째 줄에는 공백으로 구분된 두 정수 R과 C가 주어진다. 단, 1 ≤ R, C ≤ 1000 이다. R은 미로 행의 개수, C는 열의 개수이다. 다음 입력으로 R줄동안 각각의 미로 행이 주어진다.  각각의 문

www.acmicpc.net

 

 


 

 

 

  • 풀이

 

 

DFS

1. 불을 퍼뜨린다.

2. 지훈이가 이동한다.

 

 

 

  • 코드

 

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

public class Main {
	static int N, M;
	static char[][] array;
	static Queue<int[]> jihoon, fire;
	static int[] x = { -1, 0, 1, 0 };
	static int[] y = { 0, 1, 0, -1 };

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

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

		N = in.nextInt();
		M = in.nextInt();
		array = new char[N][M];
		jihoon = new LinkedList<>();
		fire = new LinkedList<>();

		for (int i = 0; i < N; i++) {
			String s = in.nextLine();
			for (int j = 0; j < M; j++) {
				array[i][j] = s.charAt(j);
				if (array[i][j] == 'F')
					fire.add(new int[] { i, j });
				if (array[i][j] == 'J')
					jihoon.add(new int[] { i, j, 0 });
			}
		}

		bfs();
	}

	private static void bfs() {
		while (!jihoon.isEmpty()) {
			// 불이 먼저 퍼진다.
			int size = fire.size();
			for (int i = 0; i < size; i++) {
				int[] fireLocation = fire.poll();

				for (int direction = 0; direction < 4; direction++) {
					int r = fireLocation[0] + x[direction];
					int c = fireLocation[1] + y[direction];

					if (r < 0 || c < 0 || r >= N || c >= M)
						continue;
					if (array[r][c] == '#' || array[r][c] == 'F')
						continue;

					array[r][c] = 'F';
					fire.add(new int[] { r, c });
				}
			}

			size = jihoon.size();
			for (int i = 0; i < size; i++) {
				int[] jihoonLocation = jihoon.poll();
				for (int direction = 0; direction < 4; direction++) {
					int r = jihoonLocation[0] + x[direction];
					int c = jihoonLocation[1] + y[direction];

					// 나가는 경우
					if (r < 0 || c < 0 || r >= N || c >= M) {
						System.out.println(jihoonLocation[2] + 1);
						System.exit(0);
					}

					if (array[r][c] == '#' || array[r][c] == 'F' || array[r][c] == 'J')
						continue;

					array[r][c] = 'J';
					jihoon.add(new int[] { r, c, jihoonLocation[2] + 1 });
				}
			}
		}
	}
}

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;
	}
}

 

14888번: 연산자 끼워넣기

첫째 줄에 수의 개수 N(2 ≤ N ≤ 11)가 주어진다. 둘째 줄에는 A1, A2, ..., AN이 주어진다. (1 ≤ Ai ≤ 100) 셋째 줄에는 합이 N-1인 4개의 정수가 주어지는데, 차례대로 덧셈(+)의 개수, 뺄셈(-)의 개수, 

www.acmicpc.net

 

 

 


 

 

 

  • 생각

 

 

dfs ,백트래킹 방식으로 모든 방법을 확인하였다.

 

DFS

1. basecase는 index가 N인 경우로 입력한 숫자를 다 도는 경우를 말한다.

2. 연산자 4개를 하나씩 도는데 여기서 백트래킹 방식으로 작업을 한 뒤 작업이 끝나면 다시 되돌려주는 작업을 한다.

 

 

  • 코드

 

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

public class Main {
	static int N, max, min;
	static int[] array, mathSymbol;

	public static void main(String[] args) throws Exception {
		SetData();
		System.out.println(max + "\n" + min);
	}

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

		N = in.nextInt();
		array = new int[N];
		mathSymbol = new int[4];
		max = Integer.MIN_VALUE;
		min = Integer.MAX_VALUE;
		
		for(int i = 0; i < N; i++)
			array[i] = in.nextInt();
		
		for(int i = 0 ; i < 4; i++) {
			mathSymbol[i] = in.nextInt();
		}
		
		dfs(1,  array[0]);
	}
	
	private static void dfs(int index, int value) {
		if(index == N) {
			max = Math.max(max, value);
			min = Math.min(min, value);
		}
		
		for(int j = 0; j < 4; j++) {
			if(mathSymbol[j] == 0)		continue;
				
			mathSymbol[j]--;
			dfs(index + 1, calculate(value, array[index], j));
			mathSymbol[j]++;
		}		
	}
	
	private static int calculate(int a, int b, int symbol) {
		if(symbol == 0)
			return a + b;
		else if(symbol == 1)
			return a - b;
		else if(symbol == 2)
			return a * b;
		else
			return 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;
	}
}

+ Recent posts