[Java]알고리즘 기초

박진우·2022년 11월 15일
0

알고리즘 기초

목록 보기
29/29

2250 트리의 높이와 너비

문제

이진트리를 다음의 규칙에 따라 행과 열에 번호가 붙어있는 격자 모양의 틀 속에 그리려고 한다. 이때 다음의 규칙에 따라 그리려고 한다.

이진트리에서 같은 레벨(level)에 있는 노드는 같은 행에 위치한다.
한 열에는 한 노드만 존재한다.
임의의 노드의 왼쪽 부트리(left subtree)에 있는 노드들은 해당 노드보다 왼쪽의 열에 위치하고, 오른쪽 부트리(right subtree)에 있는 노드들은 해당 노드보다 오른쪽의 열에 위치한다.
노드가 배치된 가장 왼쪽 열과 오른쪽 열 사이엔 아무 노드도 없이 비어있는 열은 없다.
이와 같은 규칙에 따라 이진트리를 그릴 때 각 레벨의 너비는 그 레벨에 할당된 노드 중 가장 오른쪽에 위치한 노드의 열 번호에서 가장 왼쪽에 위치한 노드의 열 번호를 뺀 값 더하기 1로 정의한다. 트리의 레벨은 가장 위쪽에 있는 루트 노드가 1이고 아래로 1씩 증가한다.

아래 그림은 어떤 이진트리를 위의 규칙에 따라 그려 본 것이다. 첫 번째 레벨의 너비는 1, 두 번째 레벨의 너비는 13, 3번째, 4번째 레벨의 너비는 각각 18이고, 5번째 레벨의 너비는 13이며, 그리고 6번째 레벨의 너비는 12이다.

우리는 주어진 이진트리를 위의 규칙에 따라 그릴 때에 너비가 가장 넓은 레벨과 그 레벨의 너비를 계산하려고 한다. 위의 그림의 예에서 너비가 가장 넓은 레벨은 3번째와 4번째로 그 너비는 18이다. 너비가 가장 넓은 레벨이 두 개 이상 있을 때는 번호가 작은 레벨을 답으로 한다. 그러므로 이 예에 대한 답은 레벨은 3이고, 너비는 18이다.

임의의 이진트리가 입력으로 주어질 때 너비가 가장 넓은 레벨과 그 레벨의 너비를 출력하는 프로그램을 작성하시오

입력

첫째 줄에 노드의 개수를 나타내는 정수 N(1 ≤ N ≤ 10,000)이 주어진다. 다음 N개의 줄에는 각 줄마다 노드 번호와 해당 노드의 왼쪽 자식 노드와 오른쪽 자식 노드의 번호가 순서대로 주어진다. 노드들의 번호는 1부터 N까지이며, 자식이 없는 경우에는 자식 노드의 번호에 -1이 주어진다.

출력

첫째 줄에 너비가 가장 넓은 레벨과 그 레벨의 너비를 순서대로 출력한다. 너비가 가장 넓은 레벨이 두 개 이상 있을 때에는 번호가 작은 레벨을 출력한다.


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

public class B2250 {
	static Node[]tree;
	static int[] min,max;
	static int nodeidx = 1;
	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());
		tree = new Node[n+1];
		min = new int[n+1];
		max = new int[n+1];
		int root = 0;
		for(int i = 0;i<=n;i++) {
			tree[i] = new Node(i,-1,-1);
			min[i] = n;
			max[i] = 0;
		}
		for(int i = 1;i<=n;i++) {
			StringTokenizer st = new StringTokenizer(br.readLine());
			int num = Integer.parseInt(st.nextToken());
			int left = Integer.parseInt(st.nextToken());
			int right = Integer.parseInt(st.nextToken());
			
			tree[num].left = left;
			tree[num].right = right;
            
			if(left != -1) tree[left].parent = num;
			if(right != -1) tree[right].parent = num;
		}
		for(int i = 1;i<=n;i++) {
			if(tree[i].parent == -1) {
				root = i;
				break;
			}
	
		}
		inorder(root, 1);
		int level = 1;
		int width = 0;
		for(int i = 0;i<=n;i++) {
			int tmp = max[i]-min[i];
			if(width<tmp) {
				level = i;
				width = tmp;
			}
		}
		System.out.println(level+" "+(width+1));
	}
	static class Node{
		int num;
		int parent;
		int left;
		int right;
		public Node(int num,int left,int right) {
			this.num = num;
			this.parent = -1;
			this.left = left;
			this.right = right;
			
		}
	}
	static void inorder(int root,int level) {
		Node cur = tree[root];
		if(cur.left!=-1) {
			inorder(cur.left, level+1);
		}
		min[level] = Math.min(min[level], nodeidx);
		max[level] = Math.max(max[level], nodeidx);
		nodeidx++;
		if(cur.right!=-1) {
			inorder(cur.right,level+1);
		}
	}

}

11725 트리의 부모 찾기

문제

루트 없는 트리가 주어진다. 이때, 트리의 루트를 1이라고 정했을 때, 각 노드의 부모를 구하는 프로그램을 작성하시오.

입력

첫째 줄에 노드의 개수 N (2 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N-1개의 줄에 트리 상에서 연결된 두 정점이 주어진다.

출력

첫째 줄부터 N-1개의 줄에 각 노드의 부모 노드 번호를 2번 노드부터 순서대로 출력한다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.StringTokenizer;

public class B11725 {
	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int N = Integer.parseInt(br.readLine());
		List<Integer> list[] = new ArrayList [N+1];
		for(int i = 0;i<list.length;i++) {
			list[i] = new ArrayList<Integer>();
		}
		for(int i = 0;i<N-1;i++) {
			StringTokenizer st = new StringTokenizer(br.readLine());
			int a = Integer.parseInt(st.nextToken());
			int b = Integer.parseInt(st.nextToken());
			list[a].add(b);
			list[b].add(a);
		}
		boolean V[] = new boolean[N+1];
		int ans[] = new int[N+1];
		Queue<Integer> q = new LinkedList<Integer>();
		q.add(1);
		V[1] = true;
		while(!q.isEmpty()) {
			int num = q.poll();
			for(Integer i : list[num]) {
				if(!V[i]) {
					V[i] = true;
					ans[i] = num;
					q.add(i);
				}
			}
		}
		for(int i = 2;i<ans.length;i++) {
			System.out.println(ans[i]);
		}
	}
}

1167 트리의 지름

문제

트리의 지름이란, 트리에서 임의의 두 점 사이의 거리 중 가장 긴 것을 말한다. 트리의 지름을 구하는 프로그램을 작성하시오.

입력

트리가 입력으로 주어진다. 먼저 첫 번째 줄에서는 트리의 정점의 개수 V가 주어지고 (2 ≤ V ≤ 100,000)둘째 줄부터 V개의 줄에 걸쳐 간선의 정보가 다음과 같이 주어진다. 정점 번호는 1부터 V까지 매겨져 있다.

먼저 정점 번호가 주어지고, 이어서 연결된 간선의 정보를 의미하는 정수가 두 개씩 주어지는데, 하나는 정점번호, 다른 하나는 그 정점까지의 거리이다. 예를 들어 네 번째 줄의 경우 정점 3은 정점 1과 거리가 2인 간선으로 연결되어 있고, 정점 4와는 거리가 3인 간선으로 연결되어 있는 것을 보여준다. 각 줄의 마지막에는 -1이 입력으로 주어진다. 주어지는 거리는 모두 10,000 이하의 자연수이다.

출력

첫째 줄에 트리의 지름을 출력한다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class B1167 {

	static class tree{
		int to,D;
		public tree(int to, int D) {
			this.to = to;
			this.D = D;
		}
	}
	static int T;
	static ArrayList<tree>[] list;
	static int[]dist;
	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		T = Integer.parseInt(br.readLine());
		list = new ArrayList[T+1];
		for(int i = 0;i<=T;i++) {
			list[i] = new ArrayList<tree>();
		}
		for(int i = 0;i<T;i++) {
			StringTokenizer st = new StringTokenizer(br.readLine());
			int node = Integer.parseInt(st.nextToken());
			String s;
			while(!(s = st.nextToken()).equals("-1")) {
				int to = Integer.parseInt(s);
				int D = Integer.parseInt(st.nextToken());
			list[node].add(new tree(to,D));
			}
		}
		int a = bfs(1);

		int b = bfs(a);

		System.out.println(dist[b]);
	}
	static int bfs(int start) {
		Queue<tree>q = new LinkedList<tree>();
		int max = 0;
		dist = new int[T+1];
		boolean V[] = new boolean[T+1];
		q.offer(new tree(start,0));
		while(!q.isEmpty()) {
			tree t = q.poll();
			if(!V[t.to]) {
				V[t.to] = true;
				for(tree next : list[t.to]) {
					if(!V[next.to]) {
						q.offer(next);
						dist[next.to] = dist[t.to]+next.D;
						max = Math.max(max, dist[next.to]);
					}
				}
			}
		}
		int maxIdx = 0;
		for(int i = 1;i<=T;i++) {
			if(dist[i] == max) {
				maxIdx = i;
				break;
			}
		}
		return maxIdx;
	}
	
}

1967 트리의 지름

문제

트리(tree)는 사이클이 없는 무방향 그래프이다. 트리에서는 어떤 두 노드를 선택해도 둘 사이에 경로가 항상 하나만 존재하게 된다. 트리에서 어떤 두 노드를 선택해서 양쪽으로 쫙 당길 때, 가장 길게 늘어나는 경우가 있을 것이다. 이럴 때 트리의 모든 노드들은 이 두 노드를 지름의 끝 점으로 하는 원 안에 들어가게 된다.

이런 두 노드 사이의 경로의 길이를 트리의 지름이라고 한다. 정확히 정의하자면 트리에 존재하는 모든 경로들 중에서 가장 긴 것의 길이를 말한다.

입력으로 루트가 있는 트리를 가중치가 있는 간선들로 줄 때, 트리의 지름을 구해서 출력하는 프로그램을 작성하시오. 아래와 같은 트리가 주어진다면 트리의 지름은 45가 된다.

트리의 노드는 1부터 n까지 번호가 매겨져 있다.

입력

파일의 첫 번째 줄은 노드의 개수 n(1 ≤ n ≤ 10,000)이다. 둘째 줄부터 n-1개의 줄에 각 간선에 대한 정보가 들어온다. 간선에 대한 정보는 세 개의 정수로 이루어져 있다. 첫 번째 정수는 간선이 연결하는 두 노드 중 부모 노드의 번호를 나타내고, 두 번째 정수는 자식 노드를, 세 번째 정수는 간선의 가중치를 나타낸다. 간선에 대한 정보는 부모 노드의 번호가 작은 것이 먼저 입력되고, 부모 노드의 번호가 같으면 자식 노드의 번호가 작은 것이 먼저 입력된다. 루트 노드의 번호는 항상 1이라고 가정하며, 간선의 가중치는 100보다 크지 않은 양의 정수이다.

출력

첫째 줄에 트리의 지름을 출력한다.


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.StringTokenizer;

public class B1967 {
	static class Node{
		int num,cost;
		public Node(int num,int cost) {
			this.num = num;
			this.cost = cost;
		}
	}
	static int dist[],max,idx;
	static boolean V[];
	static LinkedList<Node>tree[];
	 public static void main(String[] args) throws Exception {
	        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	        StringTokenizer stz;
	        int n = Integer.parseInt(br.readLine());
	        tree = new LinkedList[10001];
	        dist = new int[10001];
	        V = new boolean[10001];
	        for(int i = 1; i <= 10000; i++)
	            tree[i] = new LinkedList<>();
	        for(int i = 0; i < n-1; i++) {
	            stz = new StringTokenizer(br.readLine());
	            int p = Integer.parseInt(stz.nextToken());
	            int c = Integer.parseInt(stz.nextToken());
	            int w = Integer.parseInt(stz.nextToken());
	            tree[p].add(new Node(c, w));
	            tree[c].add(new Node(p, w));
	        }
	        if(n > 1) {
	            dfs(1, 0);
	            V = new boolean[10001];
	            dist = new int[10001];
	            
	            dfs(idx, 0);
	            System.out.println(max);
	        }
	        else
	            System.out.println(0);
	    }
	
	static void dfs(int node,int weight) {
		dist[node] = weight;
		V[node] = true;
		if(weight>max) {
			max = weight; 
			idx = node;
		}
		for(Node next : tree[node]) {
			if(!V[next.num]) {
				dfs(next.num,weight+next.cost);
			}
		}
	}
}
profile
개발자를 꿈꾸는 사람입니다

0개의 댓글