• 풀이

 

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

 

 

예제 입력 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;
    }
}

 

17143번: 낚시왕

낚시왕이 상어 낚시를 하는 곳은 크기가 R×C인 격자판으로 나타낼 수 있다. 격자판의 각 칸은 (r, c)로 나타낼 수 있다. r은 행, c는 열이고, (R, C)는 아래 그림에서 가장 오른쪽 아래에 있는 칸이다.

www.acmicpc.net

 

 

 

 


 

 

 

  • 풀이

 

문제 설명대로 구현하면되는 문제이다.

키는 s를 s %= ((가로 or 세로) x 2 -2)로 시간을 줄이는 것이다.

 

 

  • 코드
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 R, C, M, answer;
	static ArrayList<Shark> sharks;
	static int[] dx = { 0, -1, 1, 0, 0 };
	static int[] dy = { 0, 0, 0, 1, -1 };

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

		R = in.nextInt();
		C = in.nextInt();
		M = in.nextInt();
		answer = 0;
		sharks = new ArrayList<>();

		int r,c,s,d,z;
		for(int i = 0 ; i < M; i++) {
			r = in.nextInt();
			c = in.nextInt();
			s = in.nextInt();
			d = in.nextInt();
			z = in.nextInt();
			
			if(d == 1 || d == 2) s = s % (R*2-2);
			if(d == 3 || d == 4) s = s % (C*2-2);
			sharks.add(new Shark(r,c,s,d,z));
		}

		solve();
	}
	
	private static void solve() {
		for(int person = 1; person <= C; person++) {
			Collections.sort(sharks);
			
			// 잡아먹음
			int r = -1, c = -1;
			for(int i = 0; i < sharks.size(); i++) {
				int tempR = sharks.get(i).r;
				int tempC = sharks.get(i).c;
				
				if(r == tempR && c == tempC) {
					sharks.remove(i--);
				} else {
					r = tempR;
					c = tempC;
				}
			}
			
			for(int i = 0; i < sharks.size(); i++) {
				if(sharks.get(i).c > person)
					break;
				// 낚시
				if(sharks.get(i).c == person) {
					answer += sharks.get(i).z;
					sharks.remove(i);
					break;
				}
			}
			
			for(int i = 0; i < sharks.size(); i++) {
				r = sharks.get(i).r;
				c = sharks.get(i).c;
				int s = sharks.get(i).s;
				int d = sharks.get(i).d;
				
				// 물고기 이동
				for(int j = 0; j < s; j++) {					
					if(r + dx[d] <= 0 || c + dy[d] <= 0 || r + dx[d] >= R + 1 || c + dy[d] >= C+1) {
						if(d % 2 == 0)
							d--;
						else
							d++;
					}
					
					r += dx[d];
					c += dy[d];
				}

				sharks.get(i).SetR(r);
				sharks.get(i).SetC(c);
				sharks.get(i).SetD(d);					
			}
		}
	}
	
}

class Shark implements Comparable<Shark> {
	int r, c, s, d, z;

	public Shark(int r, int c, int s, int d, int z) {
		this.r = r;
		this.c = c;
		this.s = s;
		this.d = d;
		this.z = z;
	}
	
	public void SetR(int r) {
		this.r = r;
	}
	
	public void SetC(int c) {
		this.c = c;
	}
	
	public void SetD(int d) {
		this.d = d;
	}

	@Override
	public int compareTo(Shark o) {
		if(this.c == o.c) {
			if(this.r == o.r)			
				return -Integer.compare(this.z, o.z);
			else
				return Integer.compare(this.r, o.r);
		} else
			return Integer.compare(this.c, o.c);
	}
}

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

 

16236번: 아기 상어

N×N 크기의 공간에 물고기 M마리와 아기 상어 1마리가 있다. 공간은 1×1 크기의 정사각형 칸으로 나누어져 있다. 한 칸에는 물고기가 최대 1마리 존재한다. 아기 상어와 물고기는 모두 크기를 가

www.acmicpc.net

 

 


 

 

  • 풀이

 

우선순위큐 + bfs로 풀었다.

 

해당 문제는 상어가 왼쪽, 위쪽에 있으면 먼저 탐색해야 되기때문에 그냥 bfs로는 탐색이 불가하지만 우선순위큐로 거리, x, y를 고려해서 큐정렬을 해준다면 bfs로 풀 수 있다.

 

정렬 기준은 거리가 다르다면 거리 순으로 오름차순, y축 좌표가 다르다면 y축 좌표로 오름차순 모두 같다면 x축 좌표로 오름차순 정렬했다.

 

 

  • 코드

 

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

public class Main {
	static int N, x, y, answer;
	static int[][] array;
	static Shark shark;
	static int[] dx = { 0, -1, 1, 0 };
	static int[] dy = { 1, 0, 0, -1 };

	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][N];
		answer = 0;

		for (int i = 0; i < N; i++) {
			for (int j = 0; j < N; j++) {
				array[i][j] = in.nextInt();
				if (array[i][j] == 9) {
					shark = new Shark(i,j,0);
					array[i][j] = 0;
				}
			}
		}

		bfs();
	}

	private static void bfs() {
		int size = 2;
		int eat = 0; // 먹은 물고기 수

		while (true) {
			PriorityQueue<Shark> queue = new PriorityQueue<>();
			boolean[][] check = new boolean[N][N];

			queue.add(new Shark(shark.x, shark.y, 0)); // x좌표, y좌표, 이동한 거리
			check[shark.x][shark.y] = true;

			boolean sharkEat = false;

			while (!queue.isEmpty()) {
				shark = queue.poll();

				if (array[shark.x][shark.y] != 0 && array[shark.x][shark.y] < size) { // 먹이가 있으면서 상어의
					array[shark.x][shark.y] = 0; // 물고기 제거
					eat++;
					answer += shark.distance; // 움직인 거리를 총 움직인 거리에 추가
					sharkEat = true;
					break;
				}

				for (int direction = 0; direction < 4; direction++) {
					int r = shark.x + dx[direction];
					int c = shark.y + dy[direction];

					if (r < 0 || c < 0 || c >= N || r >= N || check[r][c] || array[r][c] > size)
						continue;

					queue.add(new Shark(r, c, shark.distance + 1));
					check[r][c] = true;
				}
			}

			if (!sharkEat) // 큐가 비워질 때까지 먹이를 먹은적이 없다면, 더 이상 먹은 물고기가 없으므로 탈출
				break;

			if (size == eat) { // 사이즈와 먹이를 먹은 수가 동일하다면 상어의 크기를 증가
				size++;
				eat = 0;
			}
		}

	}
}

class Shark implements Comparable<Shark> {
	int x;
	int y;
	int distance;

	public Shark(int x, int y, int distance) {
		this.x = x;
		this.y = y;
		this.distance = distance;
	}

	@Override
	public int compareTo(Shark o) {
		if(this.distance != o.distance)
			return Integer.compare(this.distance, o.distance);
		else {
			if(this.x != o.x)
				return Integer.compare(this.x, o.x);
			else
				return Integer.compare(this.y, o.y);
		}
	}
}

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

 

 

16235번: 나무 재테크

부동산 투자로 억대의 돈을 번 상도는 최근 N×N 크기의 땅을 구매했다. 상도는 손쉬운 땅 관리를 위해 땅을 1×1 크기의 칸으로 나누어 놓았다. 각각의 칸은 (r, c)로 나타내며, r은 가장 위에서부터

www.acmicpc.net

 

 

 


 

 

 

  • 풀이

 

문제 설명대로 봄, 여름, 가을, 겨울에 해야될 일들을 메소드로 나누어서 풀었다.

 

 

 

  • 코드

 

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, M, K;
	static int[][] array, foodForTree;
	static ArrayList<Tree> tree;
	static ArrayList<Tree> livedTree;
	static ArrayList<Tree> deadTree;
	static int[] dx = { -1, -1, -1, 0, 0, 1, 1, 1 };
	static int[] dy = { -1, 0, 1, -1, 1, -1, 0, 1 };

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

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

		N = in.nextInt();
		M = in.nextInt();
		K = in.nextInt();
		array = new int[N + 1][N + 1];
		tree = new ArrayList<>();
		foodForTree = new int[N + 1][N + 1];

		for (int i = 1; i <= N; i++) {
			for (int j = 1; j <= N; j++) {
				foodForTree[i][j] = in.nextInt();
				array[i][j] = 5;
			}
		}

		for(int i = 0; i < M; i++)
			tree.add(new Tree(in.nextInt(), in.nextInt(), in.nextInt()));

		Solve();
	}

	private static void Solve() {
		while (K-- > 0) {
			livedTree = new ArrayList<>();
			deadTree = new ArrayList<>();
			Collections.sort(tree);	// 정렬
			ComeSpring();
			ComeSummer();
			ComeFall();
			ComeWinter();
		}
	}

	private static void ComeSpring() {
		for (int i = 0; i < tree.size(); i++) {			
			Tree t = tree.get(i);
			
			// 양분이 충분한 경우 양분을 먹는다.
			if(array[t.x][t.y] >= t.age) {
				array[t.x][t.y] -= t.age;
				t.age++;				
				livedTree.add(t);
			} else {
				// 그렇지 못한 경우 죽음
				deadTree.add(t);
			}
		}
		tree.clear();
		tree.addAll(livedTree);
	}

	private static void ComeSummer() {
		// 죽은 나무 양분
		for (int i = 0; i < deadTree.size(); i++) {
			Tree t = deadTree.get(i);
			array[t.x][t.y] += t.age / 2;
		}
	}

	private static void ComeFall() {
		for (int i = 0; i < tree.size(); i++) {
			if(tree.get(i).age % 5 != 0) continue;
			
			int x = tree.get(i).x;
			int y = tree.get(i).y;
			
			for(int direction = 0; direction < 8; direction++) {
				int r = x + dx[direction];
				int c = y + dy[direction];
				if(r <= 0 || c <= 0 || r > N || c > N) continue;
				
				tree.add(new Tree(r, c, 1));
			}
		}
	}

	private static void ComeWinter() {
		for (int i = 1; i <= N; i++) {
			for (int j = 1; j <= N; j++) {
				array[i][j] += foodForTree[i][j];
			}
		}
	}
}

class Tree implements Comparable<Tree>{
	int x;
	int y;
	int age;

	public Tree(int x, int y, int age) {
		this.x = x;
		this.y = y;
		this.age = age;
	}
	
	@Override
	public int compareTo(Tree t) {
		return this.age - t.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;
	}
}

 

 

 

  • 시간초과 났던 코드

달라진점 : queue 부분을 arraylist로 고쳐줌

 

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

public class Main {
	static int N, M, K;
	static int[][] array, foodForTree;
	static ArrayList<Tree> tree;
	static Queue<Tree> diedTree;
	static int[] dx = { -1, -1, -1, 0, 0, 1, 1, 1 };
	static int[] dy = { -1, 0, 1, -1, 1, -1, 0, 1 };

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

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

		N = in.nextInt();
		M = in.nextInt();
		K = in.nextInt();
		array = new int[N + 1][N + 1];
		tree = new ArrayList<>();
		diedTree = new LinkedList<>();
		foodForTree = new int[N + 1][N + 1];

		for (int i = 1; i <= N; i++) {
			for (int j = 1; j <= N; j++) {
				foodForTree[i][j] = in.nextInt();
				array[i][j] = 5;
			}
		}

		for(int i = 0; i < M; i++)
			tree.add(new Tree(in.nextInt(), in.nextInt(), in.nextInt()));

		Solve();
	}

	private static void Solve() {
		while (K-- > 0) {
			Collections.sort(tree);	// 정렬
			ComeSpring();
			ComeSummer();
			ComeFall();
			ComeWinter();
		}
	}

	private static void ComeSpring() {
		for (int i = 0; i < tree.size(); i++) {			
			int x = tree.get(i).x;
			int y = tree.get(i).y;
			int age = tree.get(i).age;
			// 양분이 충분한 경우 양분을 먹는다.
			if(array[x][y] >= age) {
				array[x][y] -= age;
				tree.get(i).age++;
			} else {
				// 그렇지 못한 경우 죽음
				diedTree.add(new Tree(x,y,age));
				tree.remove(i);
				i--;
			}
		}
	}

	private static void ComeSummer() {
		// 죽은 나무가 양분으로 변함
		while(!diedTree.isEmpty()) {
			Tree temp = diedTree.poll();
			array[temp.x][temp.y] += temp.age /2;
		}
	}

	private static void ComeFall() {
		for (int i = 0; i < tree.size(); i++) {
			if(tree.get(i).age % 5 != 0) continue;
			
			int x = tree.get(i).x;
			int y = tree.get(i).y;
			
			for(int direction = 0; direction < 8; direction++) {
				int r = x + dx[direction];
				int c = y + dy[direction];
				if(r <= 0 || c <= 0 || r > N || c > N) continue;
				
				tree.add(new Tree(r, c, 1));
			}
		}
	}

	private static void ComeWinter() {
		for (int i = 1; i <= N; i++) {
			for (int j = 1; j <= N; j++) {
				array[i][j] += foodForTree[i][j];
			}
		}
	}
}

class Tree implements Comparable<Tree>{
	int x;
	int y;
	int age;

	public Tree(int x, int y, int age) {
		this.x = x;
		this.y = y;
		this.age = age;
	}
	
	@Override
	public int compareTo(Tree t) {
		return this.age - t.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;
	}
}

 

 

 

런타임 에러 도움말

C/C++ (gcc) 언어: C99, C11, C90, C2x, C++98, C++11, C++14, C++17, C++20 런타임 에러 이유설명AssertionFailedassert함수가 실패SegfaultSegmentation faultBusErrorBus errorInvalidPointermunmap_chunk(): invalid pointerOutOfBounds컨테이너 또

www.acmicpc.net

 

return 0부분이 잘못되었다고하는데 잘 모르겠다..

 

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

public class Main {
	static int N, M, K;
	static int[][] array, foodForTree;
	static ArrayList<Tree> tree;
	static Queue<int []> diedTree;
	static int[] dx = { -1, -1, -1, 0, 0, 1, 1, 1 };
	static int[] dy = { -1, 0, 1, -1, 1, -1, 0, 1 };

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

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

		N = in.nextInt();
		M = in.nextInt();
		K = in.nextInt();
		array = new int[N + 1][N + 1];
		tree = new ArrayList<>();
		diedTree = new LinkedList<>();
		foodForTree = new int[N + 1][N + 1];

		for (int i = 1; i <= N; i++) {
			for (int j = 1; j <= N; j++) {
				foodForTree[i][j] = in.nextInt();
				array[i][j] = 5;
			}
		}

		for(int i = 0; i < M; i++)
			tree.add(new Tree(in.nextInt(), in.nextInt(), in.nextInt()));

		Solve();
	}

	private static void Solve() {
		while (K-- > 0) {
			Collections.sort(tree, new TreeCompare());	// 정렬
			ComeSpring();
			ComeSummer();
			ComeFall();
			ComeWinter();
		}
	}

	private static void ComeSpring() {
		for (int i = 0; i < tree.size(); i++) {
			int x = tree.get(i).x;
			int y = tree.get(i).y;
			int age = tree.get(i).age;
			// 양분이 충분한 경우 양분을 먹는다.
			if(array[x][y] >= age) {
				array[x][y] -= age;
				tree.get(i).age++;
			} else {
				// 그렇지 못한 경우 죽음
				diedTree.add(new int[] {x,y,age});
				tree.remove(i);
				i--;
			}
		}
	}

	private static void ComeSummer() {
		// 죽은 나무가 양분으로 변함
		while(!diedTree.isEmpty()) {
			int[] temp = diedTree.poll();
			array[temp[0]][temp[1]] += temp[2] /2;
		}
	}

	private static void ComeFall() {
		for (int i = 0; i < tree.size(); i++) {
			if(tree.get(i).age % 5 != 0) continue;
			
			int x = tree.get(i).x;
			int y = tree.get(i).y;
			int age = tree.get(i).age;
			for(int direction = 0; direction < 8; direction++) {
				int r = x + dx[direction];
				int c = y + dy[direction];
				if(r <= 0 || c <= 0 || r > N || c > N) continue;
				
				tree.add(new Tree(r, c, 1));
			}
		}
	}

	private static void ComeWinter() {
		for (int i = 1; i <= N; i++) {
			for (int j = 1; j <= N; j++) {
				array[i][j] += foodForTree[i][j];
			}
		}
	}
}

class Tree{
	int x;
	int y;
	int age;

	public Tree(int x, int y, int age) {
		this.x = x;
		this.y = y;
		this.age = age;
	}
}

class TreeCompare implements Comparator<Tree> {
	int ret = 0;

	@Override
	public int compare(Tree t1, Tree t2) {
		if (t1.x == t2.x && t1.y == t2.y) {
			if (t1.age < t2.age) {
				ret = -1;
			} else
				ret = 1;
		}
		return ret;
	}
}

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

 

16234번: 인구 이동

N×N크기의 땅이 있고, 땅은 1×1개의 칸으로 나누어져 있다. 각각의 땅에는 나라가 하나씩 존재하며, r행 c열에 있는 나라에는 A[r][c]명이 살고 있다. 인접한 나라 사이에는 국경선이 존재한다. 모

www.acmicpc.net

 

 

 

 


 

 

 

 

  • 풀이

 

1. 연합을 할 수 있는 나라가 있는지 찾는다.

2. 찾으면 인구를 (연합 나라 인구수 합) / (연합 나라 수) 나누어 준다.

3. 없으면 종료하고 있으면 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.List;
import java.util.Queue;

public class Main {
	static int N, L, R, answer;
	static int[][] array;
	static boolean[][] check;
	static Queue<int []> queue;
	static ArrayList<int []> union;
	static int[] dx = {1, -1, 0, 0};
	static int[] dy = {0, 0, 1, -1}; 
	
	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();
		L = in.nextInt();
		R = in.nextInt();
		array = new int[N][N];
		queue = new LinkedList<>();
		union = new ArrayList<int []>();
		answer = 0;
		
		for(int i = 0; i < N; i++) {
			for(int j = 0; j < N; j++) {
				array[i][j] = in.nextInt();
			}
		}
		
		MovePopulation();
	}
	
	private static void MovePopulation() {
		while(PossibleMovePopulition()) {
			answer++;
		}
	}
	
	private static boolean PossibleMovePopulition() {
		boolean possible = false;
		check = new boolean[N][N];
		
		for(int i = 0 ; i < N; i++) {
			for(int j = 0 ; j < N; j++) {
				if(!check[i][j] && FindUnion(i,j)) {
					possible = true;
				}
			}
		}		
		return possible;
	}
	
	private static boolean FindUnion(int i, int j) {
		boolean possible = false;
		queue.add(new int[] {i,j});
		check[i][j] = true;
		int sum = array[i][j];
		union.add(new int[] {i,j});
		
		while(!queue.isEmpty()) {
			int[] location = queue.poll();
			
			for(int direction = 0; direction < 4; direction++) {
				int r = location[0] + dx[direction];
				int c = location[1] + dy[direction];
				
				if(r < 0 || c < 0 || r >= N || c >= N || check[r][c]) continue;
				int gap = Math.abs(array[location[0]][location[1]] - array[r][c]);
				
				if(L <= gap && gap <= R) {
					union.add(new int[] {r,c});
					check[r][c] = true;
					queue.add(new int[] {r,c});
					sum += array[r][c];
				}
			}
		}
		
		if(sum > array[i][j]) {
			SharePopulation(sum);
			possible = true;
		}
		
		return possible;
	}
	
	private static void SharePopulation(int sum) {
		for(int index = 0; index < union.size(); index++) {
			array[union.get(index)[0]][union.get(index)[1]] = sum / union.size();
		}
		union.clear();
	}
}

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

 

14499번: 주사위 굴리기

첫째 줄에 지도의 세로 크기 N, 가로 크기 M (1 ≤ N, M ≤ 20), 주사위를 놓은 곳의 좌표 x y(0 ≤ x ≤ N-1, 0 ≤ y ≤ M-1), 그리고 명령의 개수 K (1 ≤ K ≤ 1,000)가 주어진다. 둘째 줄부터 N개의 줄에 지도

www.acmicpc.net

 

 

 


 

 

 

  • 풀이

 

 

주사위 위쪽면을 1 아래쪽면을6 오른쪽 3 왼쪽 2  앞면 5 뒷면 4로 두고 조건대로 풀었다.

 

 

  • 코드

 

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

public class Main {
	static int N, M, x, y, K;
	static int[][] array;
	static int[] dice;
	static int dx[] = { 0, 0, -1, 1 };
	static int dy[] = { 1, -1, 0, 0 };
	static StringBuilder sb;
	static Queue<Integer> queue;

	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();
		M = in.nextInt();
		x = in.nextInt();
		y = in.nextInt();
		K = in.nextInt();
		array = new int[N][M];
		sb = new StringBuilder();
		queue = new LinkedList<>();
		dice = new int[7];

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

		for (int i = 0; i < K; i++) {
			queue.add(in.nextInt());
		}

		direction();
	}

	private static void direction() {
		while (!queue.isEmpty()) {
			int d = queue.poll();
			int r = x + dx[d - 1];
			int c = y + dy[d - 1];

			if (r < 0 || c < 0 || r >= N || c >= M)
				continue;

			RollDice(d);
			
			if (array[r][c] == 0) {
				array[r][c] = dice[6];
			} else {
				dice[6] = array[r][c];
				array[r][c] = 0;
			}
			x = r;
			y = c;

			sb.append(dice[1]).append("\n");
		}
	}

	private static void RollDice(int direction) {
		int[] temp = new int[7];
		for (int i = 1; i <= 6; i++) {
			temp[i] = dice[i];
		}

		switch (direction) {
		case 1: // 동
			dice[1] = temp[2];
			dice[3] = temp[1];
			dice[6] = temp[3];
			dice[2] = temp[6];
			break;
		case 2: // 서
			dice[1] = temp[3];
			dice[2] = temp[1];
			dice[6] = temp[2];
			dice[3] = temp[6];
			break;
		case 3: // 북
			dice[4] = temp[1];
			dice[6] = temp[4];
			dice[5] = temp[6];
			dice[1] = temp[5];
			break;
		case 4: // 남
			dice[5] = temp[1];
			dice[6] = temp[5];
			dice[4] = temp[6];
			dice[1] = temp[4];
			break;
		}

	}
}

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