13335번: 트럭

입력 데이터는 표준입력을 사용한다. 입력은 두 줄로 이루어진다. 입력의 첫 번째 줄에는 세 개의 정수 n (1 ≤ n ≤ 1,000) , w (1 ≤ w ≤ 100) and L (10 ≤ L ≤ 1,000)이 주어지는데, n은 다리를 건너는 트

www.acmicpc.net

 

 

 

 


 

 

 

  • 풀이

 

 

Queue를 이용해서 다리의 무게를 더해가면서 time을 늘려주었다.

 

 

  • 코드

 

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

public class Main {
	static int N,W,L,answer;
	static Queue<Integer> truck;

	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();
		W = in.nextInt();
		L = in.nextInt();
		answer = 0;
		truck = new LinkedList<Integer>();
		
		for(int i = 0; i < N; i++) {
			truck.add(in.nextInt());
		}
		answer = SaveAnswer();
	}
	
	private static int SaveAnswer() {
		int count = 0; 
		int bridgeWeight=0;
		
		Queue<Integer> bridge = new LinkedList<Integer>();
		for(int i =0; i<W ; i++) {
			bridge.add(0);
		}
		
		while(!bridge.isEmpty()) {
			count++;
			bridgeWeight-=bridge.poll();
			if(!truck.isEmpty()) {				
				if(truck.peek()+bridgeWeight<=L) {
					bridgeWeight+=truck.peek();
					bridge.offer(truck.poll());
				}else {
					bridge.offer(0);
				}
			}
		}
		return count;
	}
	
}

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

 

18428번: 감시 피하기

NxN 크기의 복도가 있다. 복도는 1x1 크기의 칸으로 나누어지며, 특정한 위치에는 선생님, 학생, 혹은 장애물이 위치할 수 있다. 현재 몇 명의 학생들은 수업시간에 몰래 복도로 빠져나왔는데, 복

www.acmicpc.net

 

 

 


 

 

  • 풀이

 

모든 X를 O개로 번갈아가면서 모든 경우의 수를 바꿔주면서 백트래킹을 했다.

 

 

 

  • 참고

 

		/*
		for(int i = index; i < empty.size(); i++) {
	        array[empty.get(i)[0]][empty.get(i)[1]] = 'O'; 
	        SaveAnswer(count + 1, index + 1);
	        array[empty.get(i)[0]][empty.get(i)[1]] = 'X';
		}*/
		int r = index / N;
		int c = index % N;
		if(array[r][c] == 'X') {
			array[r][c] = 'O';
			SaveAnswer(count+1, index+1);
			array[r][c] = 'X';
		}

 

주석 처리된 부분으로하면 틀렸다고 떠서 바꾼 부분이다.

 

주석 처리된 부분이 왜 틀렸는지 아직 잘 모르겠음... 

empty는 ArrayList로 X의 index만 저장해놓은 데이터다.

 

  • 코드

 

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

public class Main {
	static int N;
	static char[][] array;
	static ArrayList<int []> teachers;
	static ArrayList<int []> empty;

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

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

		N = in.nextInt();
		array = new char[N][N];
		teachers = new ArrayList<>();
		empty = new ArrayList<>();
		
		for(int i = 0; i < N; i++) {
			String temp = in.nextLine();
			for(int j = 0; j < N; j++) {
				array[i][j] = temp.charAt(j*2);
				if(array[i][j] == 'T')
					teachers.add(new int[] {i,j});
				if(array[i][j] == 'X')
					empty.add(new int[] {i,j});
			}
		}
		
		SaveAnswer(0, 0);
	}
	
	private static void SaveAnswer(int count, int index) {
		// basecase
		if(count == 3) {			
			if(NotMeet()) {
				System.out.println("YES");
				System.exit(0);
			}			
			return;
		}
		if(index >=N*N) return;
        
		int r = index / N;
		int c = index % N;
		if(array[r][c] == 'X') {
			array[r][c] = 'O';
			SaveAnswer(count+1, index+1);
			array[r][c] = 'X';
		}
		SaveAnswer(count, index+1);
	}
	
	private static boolean NotMeet() {
		for(int t = 0; t < teachers.size(); t++) {
			int i = teachers.get(t)[0];
			int j = teachers.get(t)[1];
			
			// 왼
			for(int directon = j-1; directon >= 0; directon--) {
				if(array[i][directon] == 'S')
					return false;
				if(array[i][directon] == 'O')
					break;
			}
			
			// 오른
			for(int directon = j+1; directon < N; directon++) {
				if(array[i][directon] == 'S')
					return false;
				if(array[i][directon] == 'O')
					break;
			}
			
			// 위
			for(int directon = i-1; directon >= 0; directon--) {
				if(array[directon][j] == 'S')
					return false;
				if(array[directon][j] == 'O')
					break;
			}
			
			// 아래
			for(int directon = i+1; directon < N; directon++) {
				if(array[directon][j] == 'S')
					return false;
				if(array[directon][j] == 'O')
					break;
			}
		}
		
		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;
	}
}

 

14569번: 시간표 짜기

연세대학교 수강신청 기간이 시작되었다. 많은 친구들은 비어 있는 시간에 어떤 과목을 추가로 신청할 수 있는지를 궁금해 한다. 이 친구들이 비어 있는 시간에 추가로 신청할 수 있는 과목의

www.acmicpc.net

 

 

 


 

 

 

  • 풀이

 

비트마스킹 공부를 위해 푼 문제.

문제를 읽고 코드를 봤는데 사실 아직 이해를 잘 못했다. (왜 써야 하는거지..?를 알아보자)

 

(참고) 비트마스크 공부한 사이트

 

비트마스크(BitMask) 는 무엇인가? :: 마이구미

이 글은 비트마스크(BitMask) 기법에 대해 다룬다. 특정 알고리즘이 아닌, bit 를 활용한 테크닉이라고 할 수 있다. bit 는 low level 이 아닌 경우에는 크게 비트를 다룰 일은 없어보이지만, 분명 이해

mygumi.tistory.com

 

 

 

  • 코드

 

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

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

		int N = in.nextInt();
		sb = new StringBuilder();
		Long[] t = new Long[N];
		
		for (int i = 0; i < N; i++) {
			int p, q;
			t[i] = 0L;
			p = in.nextInt();
			for (int j = 0; j < p; j++) {
				q = in.nextInt(); 
				t[i] |= (1L << q);
				
			}
		}
		
		int M = in.nextInt();
		
		for (int i = 0; i < M; i++) {
			int p, q, count = 0;
			Long tmp = 0L;
			p = in.nextInt();
			for (int j = 0; j < p; j++) {
				q= in.nextInt(); 
				tmp |= (1L << q);
			}
			tmp = ~tmp;
			for (int j = 0; j < N; j++) {
				if (((tmp & t[j]) == 0L)) count++;
			}
			sb.append(count).append("\n");
		}
	}
}

class Node implements Comparable<Node> {
	long age;
	int index;

	public Node(long age, int index) {
		this.age= age;
		this.index = index;
	}

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

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

 

1303번: 전쟁 - 전투

첫째 줄에는 전쟁터의 가로 크기 N, 세로 크기 M(1 ≤ N, M ≤ 100)이 주어진다. 그 다음 두 번째 줄에서 M+1번째 줄에는 각각 (X, Y)에 있는 병사들의 옷색이 띄어쓰기 없이 주어진다. 모든 자리에는

www.acmicpc.net

 

 

 


 

 

  • 풀이

 

배열을 인덱스(i, j)부터 연결된 상, 하, 좌, 우로 탐색한다는 점에서 bfs방식으로 풀면 된다고 판단했다.

 

 

  • 코드

 

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

public class Main {
	static char[][] array;
	static boolean[][] check;
	static int N, M, friendly, enemy;
	static int[] x = { -1, 1, 0, 0 };
	static int[] y = { 0, 0, -1, 1 };

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

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

		M = in.nextInt();
		N = in.nextInt();
		array = new char[N][M];
		check = new boolean[N][M];
		friendly = 0;
		enemy = 0;
		
		for(int i = 0; i < N; i++) {
			String s = in.nextLine();
			for(int j = 0 ; j < M; j++) {
				array[i][j] = s.charAt(j);
			}
		}
		
		for(int i = 0; i < N; i++) {
			for(int j = 0 ; j < M; j++) {
				if(check[i][j])  continue;
				
				if(array[i][j] == 'W')
					friendly += bfs(i, j, 'W');
				else if(array[i][j] == 'B')
					enemy += bfs(i, j, 'B');
			}
		}
	}
	
	private static int bfs(int i, int j, char peerIdentification) {
		Queue<int[]> queue = new LinkedList<>();
		queue.offer(new int[] { i, j });
		check[i][j] = true;
		int count = 1;

		while (!queue.isEmpty()) {
			int location[] = queue.poll();

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

				if (r >= 0 && c >= 0 && r < N && c < M) {
					if (array[r][c] == peerIdentification && !check[r][c]) {
						queue.offer(new int[] { r, c });
						check[r][c] = true;
						count++;
					}
				}
			}
		}
		
		return count*count;
	}
	
	/*
	private static int SaveAnswer(int index, char c) {
		if(s.length() <= index)
			return 0;
		
		if(c == '(') {
			if(s.charAt(index) == ')')
				return 2;
			else if(s.charAt(index) == '(')
				return 2 * SaveAnswer(index + 1, '(');
			else if(s.charAt(index) == '[')
				return 2 * SaveAnswer(index + 1, '[');
			else 
				return 0;
		}
		else if(c == '[') {
			if(s.charAt(index) == ']')
				return 3;
			else if(s.charAt(index) == '(')
				return 3 * SaveAnswer(index + 1, '(');
			else if(s.charAt(index) == '[')
				return 3 * SaveAnswer(index + 1, '[');
			else
				return 0;
		} else {
			if(s.charAt(index) == '(')
				return SaveAnswer(index + 1, '(');
			else if(s.charAt(index) == '[')
				return SaveAnswer(index + 1, '[');
		}
		
		return 0;
	}*/
}

class Node implements Comparable<Node> {
	long age;
	int index;

	public Node(long age, int index) {
		this.age= age;
		this.index = index;
	}

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

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

 

2504번: 괄호의 값

4개의 기호 ‘(’, ‘)’, ‘[’, ‘]’를 이용해서 만들어지는 괄호열 중에서 올바른 괄호열이란 다음과 같이 정의된다. 한 쌍의 괄호로만 이루어진 ‘()’와 ‘[]’는 올바른 괄호열이다.  만일

www.acmicpc.net

 

 

 

 


 

 

  • 풀이

 

(이면 2, [이면 3으로 temp에 곱해주면서 닫힌괄호가 나올 시 temp를 더 해주고 닫힌 괄호의 값을 temp에서 다시 나눠주는 방식을 사용했다.

 

  • 코드

 

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

public class Main {
	static String s;
	static int 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);

		s = in.nextLine();
		answer = 0;
		SaveAnswer();		
	}
	
	private static void SaveAnswer() {
		Stack<Integer> stack=new Stack<>();
		int temp=1;
		for (int i = 0; i < s.length(); i++) {
			if(s.charAt(i)=='(') {
				stack.add(2);
				temp*=2;
			}else if(s.charAt(i)=='[') {
				stack.add(3);
				temp*=3;
			}else {
				// 여는 괄호 X
				if(stack.size()==0) {
					answer=0;
					break;
				}
				
				// 여는 괄호 X && 닫는 괄호 X
				if(s.charAt(i)!=']' && s.charAt(i)!=')') {
					answer=0;
					break;
				}
				
				// 괄호 매칭 X
				if((s.charAt(i)==']' && stack.peek()==2) || (s.charAt(i)==')' && stack.peek()==3)) {
					answer=0;
					break;
				}

				if((s.charAt(i-1)=='(' && s.charAt(i) == ')') || (s.charAt(i-1)=='[' && s.charAt(i) == ']')) {
					answer+=temp;
				}
				temp/=stack.pop();
			}
			
		}
		
		if(stack.size()!=0) {
			answer=0;
		}
	}
}

class Node implements Comparable<Node> {
	long age;
	int index;

	public Node(long age, int index) {
		this.age= age;
		this.index = index;
	}

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

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

 

 


 

  • 풀이

 

왼쪽으로 오른쪽으로 가면서 현재까지의 주유소 중 리터당 가장 적은 가격을 요구하는 주유소의 가격을 더한다.

 

 

예제 입력 1)로 예시를 들면,

 

2km를 가야하기 때문에 최소 2리터의 기름이 필요하다.

주유소는 리터당 5를 요구하는 주유소밖에 없으므로 1리터당 5원을 내고 주유를 한다.

그 후 3km를 가야하는데 그 전의 리터당 5원을 요구하는 주유소보다 더 적은 값을 요구하는 리터당 2원을 요구하는 주유소가 있으므로 리터당 2원의 주유소에서 3리터를 주유한다.

마지막으로 1km를 가야한다. 현재 도착한 주유소는 리터당 4원을 요구한다. 도착한 주유소보다 리터당 2원이라는 적은 금액을 요구하는 주유소가 있으므로 더 적은 금액을 요구하는 주유소에서 주유한다.

 

최종적으로 5*2 + 2*3 + 2*1 = 18 이라는 가장 적은 금액으로 맨 오른쪽까지 갈 수 있다.

 

이러한 알고리즘은 왼쪽에서 오른쪽으로가며 리터당 가장적은 주유소 가격을 유지하고 있으면 된다.

 

 

  • 코드

 

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

public class Main {
	static int N;
	static long answer;
	static long[] gasStation, distance;

	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 = 0;
		distance = new long[N-1];
		gasStation = new long[N];
		
		for(int i = 0; i < N-1; i++) {
			distance[i] = in.nextLong();
		}
		
		for(int i = 0 ; i < N; i++)
			gasStation[i] = in.nextLong();
		
		SaveAnswer();
	}
	
	private static void SaveAnswer() {
		long minGasStation = gasStation[0];	// 이전 까지의 과정 중 주유 최소 비용 
 
		for(int i = 0; i < N - 1; i++) {
			
			if(gasStation[i] < minGasStation) {
				minGasStation = gasStation[i];
			}
			
			answer += (minGasStation * distance[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;
	}
}

 

 

  • 시간초과 났던 잘못 짠 코드

모든 방법을 체크하는 브루트포스 형식의 알고리즘으로 짜보았다. N이 10만까지라 시간초과가 날 것 같았고, 시간초과는 역시나 났다.

 

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

public class Main {
	static int N, answer;
	static int[] gasStation, distance;

	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;
		distance = new int[N-1];
		gasStation = new int[N];
		int totalDistance = 0;
		
		for(int i = 0; i < N-1; i++) {
			distance[i] = in.nextInt();
			totalDistance += distance[i];
		}
		
		for(int i = 0 ; i < N; i++)
			gasStation[i] = in.nextInt();
		
		SaveAnswer(totalDistance, 0, 0);
	}
	
	private static void SaveAnswer(int remainDistance, int nowIndex, int usingGas) {
		if(remainDistance == 0) {
			answer = Math.min(answer, usingGas);
			return;
		}
		
		int now = nowIndex;
		for(int i = nowIndex ; i < N-1; i++) {
			usingGas += distance[i] * gasStation[now];
			remainDistance -= distance[i];
			nowIndex++;
			SaveAnswer(remainDistance, nowIndex, usingGas);
		}
	}
	
}

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;
	}
}
  • 문제 링크
 

코딩테스트 연습 - 문자열 압축

데이터 처리 전문가가 되고 싶은 "어피치"는 문자열을 압축하는 방법에 대해 공부를 하고 있습니다. 최근에 대량의 데이터 처리를 위한 간단한 비손실 압축 방법에 대해 공부를 하고 있는데, 문

programmers.co.kr

 

 

  • 설명

 i개의 갯수만큼 문자열을 잘라 현재 문자열과 전 문자열을 비교하여 압축

 

 

  • 코드
public class Solution {
    public int solution(String s) {
      int answer = s.length();

      for (int i = 1; i <= s.length() / 2; i++) {
        int compLength = compression(s, i).length();
        answer = Math.min(answer, compLength);
      }

      return answer;
    }

    private String compression(String string, int i) {

      int count = 1;
      String compression = "";
      String pattern = "";

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

        String nowString;

        // 전 문자열과 비교할 현재 문자열
        if (j >= string.length()) { // 현재 문자열이 없을 때
          nowString = "";
        } else if (string.length() < j + i) { // 마지막 현재 문자열일 때
          nowString = string.substring(j);
        } else {
          nowString = string.substring(j, j + i);
        }

        // 1. 전 문자열이랑 똑같은지 비교한다. (맨 처음이면 비교 X)
        if (j != 0) {
          if (nowString.equals(pattern)) { // 같으면
            count++;
          } else if (count >= 2) { // 다르고 count가 2회 이상
            compression += count + pattern;
            count = 1;
          } else { // 압축 불가능
            compression += pattern;
          }
        }
        pattern = nowString;
      }

      return compression;
    }
}
  • 문제 링크
 

코딩테스트 연습 - 신규 아이디 추천

카카오에 입사한 신입 개발자 네오는 "카카오계정개발팀"에 배치되어, 카카오 서비스에 가입하는 유저들의 아이디를 생성하는 업무를 담당하게 되었습니다. "네오"에게 주어진 첫 업무는 새로

programmers.co.kr

 

  • 설명

1단계 new_id의 모든 대문자를 대응되는 소문자로 치환합니다.
2단계 new_id에서 알파벳 소문자, 숫자, 빼기(-), 밑줄(_), 마침표(.)를 제외한 모든 문자를 제거합니다.
3단계 new_id에서 마침표(.)가 2번 이상 연속된 부분을 하나의 마침표(.)로 치환합니다.
4단계 new_id에서 마침표(.)가 처음이나 끝에 위치한다면 제거합니다.
5단계 new_id가 빈 문자열이라면, new_id에 "a"를 대입합니다.
6단계 new_id의 길이가 16자 이상이면, new_id의 첫 15개의 문자를 제외한 나머지 문자들을 모두 제거합니다.
만약 제거 후 마침표(.)가 new_id의 끝에 위치한다면 끝에 위치한 마침표(.) 문자를 제거합니다.
7단계 new_id의 길이가 2자 이하라면, new_id의 마지막 문자를 new_id의 길이가 3이 될 때까지 반복해서 끝에 붙입니다.


  • 코드
class Solution {
	public String solution(String new_id) {
		String answer = new_id;
        
		// 1단계
		answer = answer.toLowerCase();
        
		// 2단계
		answer = answer.replaceAll("[^0-9a-z-_.]", "");
        
		// 3단계
		answer = answer.replaceAll("[.]{2,}",".");
        
		// 4단계
		answer = answer.replaceAll("^[.]|[.]$", "");
        
		// 5단계
		if(answer.length() == 0) {
			answer = "aaa";
		}
		// 6단계
		else if(answer.length() >= 16) {
		answer = answer.substring(0, 15).replaceAll("[.]$", "");
		}
		else if(answer.length() <= 2) {
			// 7단계
			while(answer.length() < 3) {
				answer += answer.charAt(answer.length() -1);
		    }
	    }   
		return answer;
	}
}

 

 

 

  • 다른 사람 코드 (정규식)
class Solution {
    public String solution(String new_id) {
        new_id = new_id.toLowerCase() // 1번
                        .replaceAll("[^\\w-\\.]", "") // 2번
                        .replaceAll("[\\.]{2,}", ".") // 3번
                        .replaceAll("^\\.|\\.$", ""); // 4번

        if (new_id.length() == 0) new_id = "a"; // 5번

        if (new_id.length() > 15)
            new_id = new_id.substring(0, 15).replaceAll("\\.$",""); // 6번

        if (new_id.length() <= 2)
            new_id += new String(new_id.charAt(new_id.length() - 1) + "").repeat(3 - new_id.length()); // 7번

        return new_id;
    }
}

+ Recent posts