Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

Life Engineering

[BOJ 2565] 전깃줄 (Java) 본문

Problem Solving

[BOJ 2565] 전깃줄 (Java)

흑개 2022. 3. 17. 23:48

https://www.acmicpc.net/problem/2565

 

2565번: 전깃줄

첫째 줄에는 두 전봇대 사이의 전깃줄의 개수가 주어진다. 전깃줄의 개수는 100 이하의 자연수이다. 둘째 줄부터 한 줄에 하나씩 전깃줄이 A전봇대와 연결되는 위치의 번호와 B전봇대와 연결되는

www.acmicpc.net

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Main_BOJ_2565 {
	static class Line implements Comparable<Line>{
		int left, right;
		public Line(int left, int right) {
			this.left = left;
			this.right = right;
		}
		@Override
		public int compareTo(Line l) {
			return this.left-l.left;
		}
	}
	static int N;
	static int[] dp;
	static Line[] lines;
	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=null;
		N=Integer.parseInt(br.readLine());
		lines=new Line[N];
		dp=new int[N];
		for (int i=0; i<N; i++) {
			st=new StringTokenizer(br.readLine());
			int left=Integer.parseInt(st.nextToken());
			int right=Integer.parseInt(st.nextToken());
			lines[i]=new Line(left, right);
		}
		Arrays.sort(lines);
		for (int i=0; i<N; i++) {
			int maxLength=0;
			for (int j=0; j<i; j++) {
				if (lines[j].right<lines[i].right) {
					maxLength=Math.max(maxLength, dp[j]);
				}
			}
			dp[i]=maxLength+1;
		}
		int max=0;
		for (int i = 0; i < N; i++) {
			if (max<dp[i]) max=dp[i];
		}
		System.out.println(N-max);
	}

}

전깃줄이 꼬이지 않는 경우=>

 

전깃줄을 왼쪽의 순서대로 오름차순으로 정렬한다 =>

그 후 오른쪽 위치에 한해, 가장 긴 증가하는 부분 수열이 되는지 dp를 통해 구한다.

 

for(int j = 0; j < i; j++) {
    if(wire[i][1] > wire[j][1]) {
        dp[i] = Math.max(dp[i], dp[j] + 1);
    }
}

(출처: https://st-lab.tistory.com/138 님)

 

dp는 이런식으로 써야 더 가독성이 좋은 듯.