diff --git a/daeun/boj1043.java b/daeun/boj1043.java new file mode 100644 index 0000000..10b1afe --- /dev/null +++ b/daeun/boj1043.java @@ -0,0 +1,91 @@ +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Queue; +import java.util.Scanner; + +public class Main { + + static boolean visited[]; + + public static void main(String[] args) { + Scanner sc= new Scanner(System.in); + int N= sc.nextInt(); //총 사람 수 (1부터)(노드 번호) + int M = sc.nextInt();//파티 수(간선 수) + int K = sc.nextInt();//진실아는 사람 수 + + visited = new boolean[N+1]; + ArrayList[] graph = new ArrayList[N+1]; + + for(int i=1; i<=N; i++) { + graph[i] = new ArrayList<>(); + } + + boolean[] knowT = new boolean[N+1]; + for(int i=0; i[] parties = new ArrayList[M]; + for(int i=0; i(); + for(int j=0; j[] graph, int num) { + Queueq = new LinkedList<>(); + q.add(num); + visited[num] = true; + + while(!q.isEmpty()) { + int curr =q.poll();//현재 사람 + for(int next: graph[curr]) { + if(!visited[next]) { + visited[next] = true; + q.add(next); + } + } + } + + } + +} diff --git a/daeun/boj1068.java b/daeun/boj1068.java new file mode 100644 index 0000000..b2a71fe --- /dev/null +++ b/daeun/boj1068.java @@ -0,0 +1,4 @@ + +public class boj1068 { + +} diff --git a/daeun/boj1707.java b/daeun/boj1707.java new file mode 100644 index 0000000..f89e071 --- /dev/null +++ b/daeun/boj1707.java @@ -0,0 +1,76 @@ +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Queue; +import java.util.Scanner; + +public class 이분그래프 { + + static int visited[]; + static int V, E; + static boolean isgraph; + + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + int K = sc.nextInt(); + + + + for(int i=0; i[] graph = new ArrayList[V+1]; + for(int j=1; j<=V; j++) { + graph[j] = new ArrayList<>(); + } + + for(int j=0; j[] graph, int num) { + Queue q = new LinkedList<>(); + q.add(num); + visited[num]=1; + while(!q.isEmpty()) { + int curr = q.poll(); + + for(int next: graph[curr]) { + if(visited[next]==0) { + visited[next] =(visited[curr]==1)? 2:1; + q.add(next); + }else if(visited[next]==visited[curr]) { + return false; + } + } + } + + return true; + + } + +} diff --git a/daeun/boj1967.java b/daeun/boj1967.java new file mode 100644 index 0000000..d68aae6 --- /dev/null +++ b/daeun/boj1967.java @@ -0,0 +1,74 @@ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; + +public class boj1967 { + + static class Node { + int num; + int cost; + + public Node(int num, int cost) { + this.num = num;//번호 + this.cost = cost;//가중치 + } + + + } + + static boolean visited[]; + static int sum; + static List[] tree; + + + 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 ArrayList[N+1]; + + for(int i=1; i<=N; i++) { + tree[i] = new ArrayList<>(); + }//트리 초기화 + + + for(int i=1; i[] heavy = new ArrayList[N+1]; + ArrayList[] light = new ArrayList[N+1]; + + for(int i=1; i<=N; i++){ + heavy[i] = new ArrayList<>(); + light[i] = new ArrayList<>(); + } + + for (int i = 0; i < M; i++) { + int H = sc.nextInt(); // 무거운거 + int L = sc.nextInt(); // 가벼운거 + heavy[H].add(L); + light[L].add(H); + } + int margino = (N + 1) / 2; + int notmiddle=0; + + for (int i = 1; i <= N; i++) { + visited = new boolean[N + 1]; + int hcnt = bfs(heavy, i); + int lcnt = bfs(light, i); + + if (hcnt >= margino || lcnt >= margino) { + notmiddle++; + } + } + System.out.println(notmiddle); + + }// main + + static int bfs(ArrayList[] list, int num) { + Queue q = new LinkedList<>(); + q.add(num); + visited[num] = true; + int cnt = 0; + while (!q.isEmpty()) { + int curr = q.poll(); + cnt++; + for (int next : list[curr]) { + if (!visited[next]) { + visited[next] = true; + q.add(next); + } + } + } + return cnt-1; + } +} diff --git a/doa/boj1043.java b/doa/boj1043.java new file mode 100644 index 0000000..13fe6f4 --- /dev/null +++ b/doa/boj1043.java @@ -0,0 +1,92 @@ +package 알고리즘; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; +import java.util.Scanner; +import java.util.Set; + +public class boj1043 { + + static int M; + static int N; + static Set cantLie; + static List> party; + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + party = new ArrayList<>(); + + N = sc.nextInt(); + M = sc.nextInt(); + + int N1 = sc.nextInt(); + cantLie = new HashSet<>(); + + for(int i=0;i parties = new HashSet<>(); + for(int j=0;j queue = new LinkedList<>(); + + //특정 수만큼 + boolean[] visitedPeople = new boolean[N+1]; + boolean[] visitedParty = new boolean[M+1]; + + for(int a : cantLie) { + visitedPeople[a]=true; + } + + queue.addAll(cantLie); + + while(!queue.isEmpty()) { + + int now = queue.poll(); + int idx =0; + + for(Set a : party) { + idx++; + + if(visitedParty[idx]) continue; + + if(a.contains(now)) { + count++; + visitedParty[idx]=true; + cantLie.addAll(a); + + for(int c : a) { + if(!visitedPeople[c]) { + queue.add(c); + visitedPeople[c]=true; + } + } + } + } + + } + + return count; + } + + } + diff --git a/doa/boj1707.java b/doa/boj1707.java new file mode 100644 index 0000000..453d5fa --- /dev/null +++ b/doa/boj1707.java @@ -0,0 +1,87 @@ +package 알고리즘; +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; +import java.util.Scanner; + +public class boj1707 { + + static int V; + static List> graph; + static int[] color; + static String answer; + + public static void main(String[] args) throws IOException { + Scanner sc = new Scanner(System.in); + + int T = sc.nextInt(); + + for (int tc = 0; tc < T; tc++) { + V = sc.nextInt(); + int E = sc.nextInt(); + answer = "YES"; + graph = new ArrayList<>(); + color = new int[V+1]; + + for (int i = 0; i <= V; i++) { + graph.add(new ArrayList<>()); + } + + for (int i = 0; i < E; i++) { + int A = sc.nextInt(); + int B = sc.nextInt(); + + graph.get(A).add(B); + graph.get(B).add(A); + } + + bfs(); + + System.out.println(answer); + } + } + public static void bfs() { + + Queue queue = new LinkedList<>(); + queue.add(1); + + + for(int i=1; i<=V ;i++) { + + if(queue.isEmpty()) { + for(int j=2; j<=V ;j++) { + if(color[j]==0) { + queue.add(j); + break; + } + } + + } + + int now = queue.poll(); + if(color[now]==0) color[now]=1; + + for(int a : graph.get(now)) { + + if(color[a]==color[now]) { + answer ="NO"; + return; + } + + if(color[a]==0 &&color[now]==1 ) { + color[a]=2; + queue.add(a); + } + else if(color[a]==0 &&color[now]==2) { + color[a]=1; + queue.add(a); + } + + } + } + } + + +} diff --git a/doa/boj2617.java b/doa/boj2617.java new file mode 100644 index 0000000..758dc2e --- /dev/null +++ b/doa/boj2617.java @@ -0,0 +1,81 @@ +package 알고리즘; +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; +import java.util.Scanner; + +public class boj2617 { + + static int V; + //가벼운게 0 무거운게 1 + static List> lighter; + static List> heavyer; + static int[] color; + static String answer; + + public static void main(String[] args) throws IOException { + Scanner sc = new Scanner(System.in); + + V = sc.nextInt(); + int E = sc.nextInt(); + lighter = new ArrayList<>(); + heavyer = new ArrayList<>(); + // Initialize the adjacency list + + int standard = V/2; + + for (int i = 0; i <= V; i++) { + lighter.add(new ArrayList<>()); + heavyer.add(new ArrayList<>()); + } + for (int i = 0; i < E; i++) { + int A = sc.nextInt(); + int B = sc.nextInt(); + + lighter.get(A).add(B); + heavyer.get(B).add(A); + //나보다 가벼운 애를 담기 + + } + + + int answer =0; + for(int i=1 ; i<=V; i++) { + + // i보다 가벼운 애들을 담기 + if(bfs(i, lighter)>standard) answer ++; + if(bfs(i, heavyer)>standard) answer ++; + //i보다 무거운 애들의 수를 담기 + } + + System.out.println(answer); + } + + public static int bfs(int i, List> list) { + + int count=0; + Queue queue = new LinkedList<>(); + boolean visited[] = new boolean[V+1]; + visited[i]=true; + queue.add(i); + + while(!queue.isEmpty()) { + int now = queue.poll(); + + for(int a : list.get(now)) { + if(!visited[a]) { + queue.add(a); + count++; + visited[a]=true; + } + } + + } + + return count; + + } + +} diff --git a/doa/boj5214.java b/doa/boj5214.java new file mode 100644 index 0000000..b322c13 --- /dev/null +++ b/doa/boj5214.java @@ -0,0 +1,95 @@ +package 알고리즘; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; +import java.util.Scanner; +import java.util.Set; + +public class boj5214 { + + //N이 전체 역 개수, K가 연결하는 역 개서, M이 하이퍼튜브의 개수 + static int N; + static int K; + static int M; + + + static List hipertube; + static Queue queue = new LinkedList<>(); + + public static void main(String[] args) { + + Scanner sc = new Scanner(System.in); + + + N = sc.nextInt(); + K = sc.nextInt(); + M = sc.nextInt(); + int[][] arr = new int[K][M]; + hipertube= new ArrayList<>(); + + + for(int i =0 ;i list = new HashSet<>(); + for(int j=0 ; j a : hipertube) { + idx++; + + if(visitedConnection[idx]) continue; + + if(a.contains(now)) { + + visitedConnection[idx]=true; + + for(int c : a) { + if(!visitedStation[c]) { + if(c==1) return ++count; + queue.add(c); + visitedStation[c]=true; + } + } + } + } + + } + + count++; + } + + return -1; + } + + } + diff --git a/hyunyong/BOJ_2617.java b/hyunyong/BOJ_2617.java new file mode 100644 index 0000000..f093a86 --- /dev/null +++ b/hyunyong/BOJ_2617.java @@ -0,0 +1,71 @@ +import java.util.ArrayList; +import java.util.Scanner; + +public class BOJ_2617 { + static int N, M; + static int[] compare; + static ArrayList[] arr; + static boolean[][] visited; + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + N = sc.nextInt(); + M = sc.nextInt(); + + arr = new ArrayList[N+1]; + + for(int i=0 ; i<=N ; i++) { + + arr[i] = new ArrayList<>(); + } + + for(int i=0 ; iN/2 || compare[1]>N/2) ans++; + } + + System.out.println(ans); + + } + + static void dfs(int[] node) { + for(int[] next : arr[node[0]]) { + if(next[1]==node[1] && !visited[next[0]][node[1]]) { + visited[next[0]][node[1]] = true; + compare[node[1]]++; + if(compare[node[1]]>N/2) return; + dfs(next); + } + + } + } +} diff --git a/jiseung/boj1043.java b/jiseung/boj1043.java new file mode 100644 index 0000000..ef8204b --- /dev/null +++ b/jiseung/boj1043.java @@ -0,0 +1,88 @@ +import java.util.*; +import java.io.*; + +public class Main { + static int[] parents; + static List truth; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + StringBuilder sb = new StringBuilder(); + + st = new StringTokenizer(br.readLine()); + int N = Integer.parseInt(st.nextToken()); + int M = Integer.parseInt(st.nextToken()); + + parents = new int[N + 1]; + for (int i = 1; i < N + 1; i++) { + parents[i] = i; + } + + st = new StringTokenizer(br.readLine()); + int num = Integer.parseInt(st.nextToken()); + truth = new ArrayList<>(); + + int result = M; + + if (num > 0) { + result = 0; + for (int i = 0; i < num; i++) { + truth.add(Integer.parseInt(st.nextToken())); + } + + List[] party = new ArrayList[M]; + + for (int i = 0; i < M; i++) { + party[i] = new ArrayList<>(); + } + + for (int i = 0; i < M; i++) { + st = new StringTokenizer(br.readLine()); + int count = Integer.parseInt(st.nextToken()); + + int x = Integer.parseInt(st.nextToken()); + party[i].add(x); + for (int j = 1; j < count; j++) { + int y = Integer.parseInt(st.nextToken()); + union(x, y); + party[i].add(y); + } + } + for (int i = 0; i < M; i++) { + boolean flag = true; + for (int people : party[i]) { + if (truth.contains(find(parents[people]))) { + flag = false; + break; + } + } + if (flag) { + result++; + } + } + } + sb.append(result); + System.out.println(sb); + + } + + static int find(int x) { + if (x != parents[x]) { + parents[x] = find(parents[x]); + } + return parents[x]; + } + + static void union(int x, int y) { + int px = find(x); + int py = find(y); + if (truth.contains(py)) { + int tmp = px; + px = py; + py = tmp; + } + + parents[py] = px; + } +} \ No newline at end of file diff --git a/jiseung/boj1068.java b/jiseung/boj1068.java new file mode 100644 index 0000000..a4bcfaa --- /dev/null +++ b/jiseung/boj1068.java @@ -0,0 +1,64 @@ +import java.io.*; +import java.util.*; + +public class Main { + static class Node { + int num; + List list = new ArrayList<>(); + + Node(int num) { + this.num = num; + } + void insert(Node child) { + list.add(child); + } + } + + static Node[] tree; + static int remove; + static int answer; + + public static void main(String[] args) throws IOException { + // 입력 + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + int N = Integer.parseInt(br.readLine()); + StringTokenizer st = new StringTokenizer(br.readLine()); + remove = Integer.parseInt(br.readLine()); + + tree = new Node[N]; + for (int i = 0; i < N; i++) { + tree[i] = new Node(i); + } + + int root = 0; + for (int i = 0; i < N; i++) { + int num = Integer.parseInt(st.nextToken()); + if (num == -1) { + root = i; + continue; + } + tree[num].insert(tree[i]); + } + + if (root != remove) + search(tree[root]); + + System.out.println(answer); + + } + + public static void search(Node curr) { + int size = curr.list.size(); + for (Node next : curr.list) { + if (next.num == remove) { + size--; + continue; + } + search(next); + } + + if (size == 0) + answer++; + } +} \ No newline at end of file diff --git a/jiseung/boj1167.java b/jiseung/boj1167.java new file mode 100644 index 0000000..15f9861 --- /dev/null +++ b/jiseung/boj1167.java @@ -0,0 +1,65 @@ +import java.util.*; +import java.io.*; + +public class Main { + + static class Edge { + int num; + int w; + + Edge(int num, int w) { + this.num = num; + this.w = w; + } + } + + static List[] list; + static boolean[] visited; + static int maxDistance; + static int farthestNode; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + + int N = Integer.parseInt(br.readLine()); + list = new ArrayList[N + 1]; + for (int i = 0; i <= N; i++) { + list[i] = new ArrayList<>(); + } + + for (int i = 1; i < N; i++) { + st = new StringTokenizer(br.readLine()); + int start = Integer.parseInt(st.nextToken()); + int end = Integer.parseInt(st.nextToken()); + int w = Integer.parseInt(st.nextToken()); + list[start].add(new Edge(end, w)); + list[end].add(new Edge(start,w)); + } + + // Step 1: 임의의 노드(1번 노드)에서 가장 먼 노드를 찾음 + visited = new boolean[N + 1]; + maxDistance = 0; + DFS(1, 0); + + // Step 2: 가장 먼 노드에서 다시 DFS를 수행하여 트리의 지름 구하기 + visited = new boolean[N + 1]; + maxDistance = 0; + DFS(farthestNode, 0); + + System.out.println(maxDistance); + } + + static void DFS(int num, int sum) { + if (sum > maxDistance) { + maxDistance = sum; + farthestNode = num; + } + visited[num] = true; + for (Edge edge : list[num]) { + if (!visited[edge.num]) { + DFS(edge.num, sum + edge.w); + } + } + } +} \ No newline at end of file diff --git a/jiseung/boj15681.java b/jiseung/boj15681.java new file mode 100644 index 0000000..8b549c4 --- /dev/null +++ b/jiseung/boj15681.java @@ -0,0 +1,69 @@ +import java.io.*; +import java.util.*; + +public class Main { + static List[] list, tree; + static int[] p, size; + + + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + StringBuilder sb = new StringBuilder(); + + st = new StringTokenizer(br.readLine()); + + int N = Integer.parseInt(st.nextToken()); + int R = Integer.parseInt(st.nextToken()); + int Q = Integer.parseInt(st.nextToken()); + + p = new int[N+1]; + size = new int[N+1]; + list = new ArrayList[N+1]; + tree = new ArrayList[N+1]; + + + for(int i=0;i(); + tree[i] = new ArrayList<>(); + } + + for(int i=1;i> adjList; + static int[] color; + static boolean bipartite; + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringBuilder sb = new StringBuilder(); + StringTokenizer st; + + int T = Integer.parseInt(br.readLine()); + + for (int tc = 1; tc <= T; tc++) { + + st = new StringTokenizer(br.readLine()); + + int V = Integer.parseInt(st.nextToken()); + int E = Integer.parseInt(st.nextToken()); + + adjList = new ArrayList<>(); + color = new int[V + 1]; // 각 정점의 색을 구분 + bipartite = true; // 초기: 이분 그래프이다. + + for(int i=0;i<=V;i++) { + adjList.add(new ArrayList<>()); + color[i]=0; + } + + + for(int i=0;i queue = new ArrayDeque<>(); + queue.add(start); + color[start]=nextColor; + + while(!queue.isEmpty()) { + int v = queue.poll(); + for(int adjV : adjList.get(v)) { + if(color[adjV]==0) { + queue.offer(adjV); + color[adjV]= -color[v]; + } + else if(color[v]+color[adjV]!=0) { + bipartite=false; + return; + } + } + } + } +} \ No newline at end of file diff --git a/jiseung/boj1967.java b/jiseung/boj1967.java new file mode 100644 index 0000000..15f9861 --- /dev/null +++ b/jiseung/boj1967.java @@ -0,0 +1,65 @@ +import java.util.*; +import java.io.*; + +public class Main { + + static class Edge { + int num; + int w; + + Edge(int num, int w) { + this.num = num; + this.w = w; + } + } + + static List[] list; + static boolean[] visited; + static int maxDistance; + static int farthestNode; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + + int N = Integer.parseInt(br.readLine()); + list = new ArrayList[N + 1]; + for (int i = 0; i <= N; i++) { + list[i] = new ArrayList<>(); + } + + for (int i = 1; i < N; i++) { + st = new StringTokenizer(br.readLine()); + int start = Integer.parseInt(st.nextToken()); + int end = Integer.parseInt(st.nextToken()); + int w = Integer.parseInt(st.nextToken()); + list[start].add(new Edge(end, w)); + list[end].add(new Edge(start,w)); + } + + // Step 1: 임의의 노드(1번 노드)에서 가장 먼 노드를 찾음 + visited = new boolean[N + 1]; + maxDistance = 0; + DFS(1, 0); + + // Step 2: 가장 먼 노드에서 다시 DFS를 수행하여 트리의 지름 구하기 + visited = new boolean[N + 1]; + maxDistance = 0; + DFS(farthestNode, 0); + + System.out.println(maxDistance); + } + + static void DFS(int num, int sum) { + if (sum > maxDistance) { + maxDistance = sum; + farthestNode = num; + } + visited[num] = true; + for (Edge edge : list[num]) { + if (!visited[edge.num]) { + DFS(edge.num, sum + edge.w); + } + } + } +} \ No newline at end of file diff --git a/jiseung/boj2617.java b/jiseung/boj2617.java new file mode 100644 index 0000000..1336ef8 --- /dev/null +++ b/jiseung/boj2617.java @@ -0,0 +1,62 @@ +import java.io.*; +import java.util.*; + +public class Main { + static int[][] adj; + static int N; + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + + st = new StringTokenizer(br.readLine()); + N = Integer.parseInt(st.nextToken()); + int M = Integer.parseInt(st.nextToken()); + + adj = new int[N + 1][N + 1]; + + for (int i = 0; i < M; i++) { + st = new StringTokenizer(br.readLine()); + int a = Integer.parseInt(st.nextToken()); + int b = Integer.parseInt(st.nextToken()); + adj[a][b] = 1; + } + + int result = 0; + int limit = N / 2 + 1; + + for (int i = 1; i <= N; i++) { + int heavyCount = bfs(i, true); + int lightCount = bfs(i, false); + if (heavyCount >= limit || lightCount >= limit) { + result++; + } + } + + System.out.println(result); + } + + private static int bfs(int start, boolean heavier) { + Queue queue = new ArrayDeque<>(); + boolean[] visited = new boolean[N + 1]; + queue.offer(start); + visited[start] = true; + int count = 0; + + while (!queue.isEmpty()) { + int current = queue.poll(); + for (int next = 1; next <= N; next++) { + if (heavier && adj[next][current] == 1 && !visited[next]) { // 무거운 구슬 찾기 + visited[next] = true; + queue.offer(next); + count++; + } else if (!heavier && adj[current][next] == 1 && !visited[next]) { // 가벼운 구슬 찾기 + visited[next] = true; + queue.offer(next); + count++; + } + } + } + + return count; + } +} \ No newline at end of file diff --git a/jiseung/boj2887.java b/jiseung/boj2887.java new file mode 100644 index 0000000..2b1b664 --- /dev/null +++ b/jiseung/boj2887.java @@ -0,0 +1,118 @@ +import java.util.*; +import java.io.*; + +public class Main { + + static class Edge implements Comparable { + int to, weight; + + public Edge(int to, int weight) { + this.to = to; + this.weight = weight; + } + + @Override + public int compareTo(Edge other) { + return Integer.compare(this.weight, other.weight); + } + } + + static class Planet { + int id, x, y, z; + + public Planet(int id, int x, int y, int z) { + this.id = id; + this.x = x; + this.y = y; + this.z = z; + } + } + + static int N; + static Planet[] planets; + static List[] adjList; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + + int N = Integer.parseInt(br.readLine()); + + planets = new Planet[N]; + + for (int i = 0; i < N; i++) { + st = new StringTokenizer(br.readLine()); + int x = Integer.parseInt(st.nextToken()); + int y = Integer.parseInt(st.nextToken()); + int z = Integer.parseInt(st.nextToken()); + planets[i] = new Planet(i, x, y, z); + } + + adjList = new ArrayList[N]; + for (int i = 0; i < N; i++) { + adjList[i] = new ArrayList<>(); + } + // x기준 정렬 후 간선 연결 + Arrays.sort(planets, new Comparator() { + @Override + public int compare(Planet p1, Planet p2) { + return Integer.compare(p1.x, p2.x); + } + }); + for (int i = 0; i < N - 1; i++) { + Planet p1 = planets[i]; + Planet p2 = planets[i + 1]; + int dist = Math.abs(p1.x - p2.x); + adjList[p1.id].add(new Edge(p2.id, dist)); + adjList[p2.id].add(new Edge(p1.id, dist)); + } + // y 정렬 + Arrays.sort(planets, new Comparator() { + @Override + public int compare(Planet p1, Planet p2) { + return Integer.compare(p1.y, p2.y); + } + }); + for (int i = 0; i < N - 1; i++) { + Planet p1 = planets[i]; + Planet p2 = planets[i + 1]; + int dist = Math.abs(p1.y - p2.y); + adjList[p1.id].add(new Edge(p2.id, dist)); + adjList[p2.id].add(new Edge(p1.id, dist)); + } + + // z기준 정렬 후 간선 연결 + Arrays.sort(planets, new Comparator() { + @Override + public int compare(Planet p1, Planet p2) { + return Integer.compare(p1.z, p2.z); + } + }); + for (int i = 0; i < N - 1; i++) { + Planet p1 = planets[i]; + Planet p2 = planets[i + 1]; + int dist = Math.abs(p1.z - p2.z); + adjList[p1.id].add(new Edge(p2.id, dist)); + adjList[p2.id].add(new Edge(p1.id, dist)); + } + + // prim + boolean[] visited = new boolean[N]; + PriorityQueue pq = new PriorityQueue<>(); + pq.addAll(adjList[0]); + visited[0] = true; + int pick = 0; + long ans = 0; + + while (pick < N - 1) { + Edge e = pq.poll(); + if (visited[e.to]) + continue; + visited[e.to] = true; + pick++; + ans += e.weight; + pq.addAll(adjList[e.to]); + } + System.out.println(ans); + } +} diff --git a/jiseung/boj5214.java b/jiseung/boj5214.java new file mode 100644 index 0000000..49d9494 --- /dev/null +++ b/jiseung/boj5214.java @@ -0,0 +1,64 @@ +import java.io.*; +import java.util.*; + +public class Main { + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + + st = new StringTokenizer(br.readLine()); + int N = Integer.parseInt(st.nextToken()); + int M = Integer.parseInt(st.nextToken()); + int K = Integer.parseInt(st.nextToken()); + + List> nodeAdjList = new ArrayList<>(); + List> tubeAdjList = new ArrayList<>(); + + for (int i = 0; i <= N; i++) { + nodeAdjList.add(new ArrayList<>()); + } + for (int i = 0; i < K; i++) { + tubeAdjList.add(new ArrayList<>()); + st = new StringTokenizer(br.readLine()); + for (int j = 0; j < M; j++) { + int node = Integer.parseInt(st.nextToken()); + nodeAdjList.get(node).add(i); + tubeAdjList.get(i).add(node); + } + } + + Queue queue = new ArrayDeque<>(); + boolean[] visitedNode = new boolean[N + 1]; + boolean[] visitedTube = new boolean[K]; + int result = -1; + + queue.add(new int[] {1, 1}); + visitedNode[1] = true; + + while (!queue.isEmpty()) { + int[] current = queue.poll(); + int node = current[0]; + int distance = current[1]; + + if (node == N) { + result = distance; + break; + } + + for (int tube : nodeAdjList.get(node)) { + if (visitedTube[tube]) continue; + visitedTube[tube] = true; + + for (int nextNode : tubeAdjList.get(tube)) { + if (!visitedNode[nextNode]) { + queue.add(new int[] {nextNode, distance + 1}); + visitedNode[nextNode] = true; + } + } + } + } + + System.out.println(result); + } +} \ No newline at end of file diff --git a/jongwon/boj1043.java b/jongwon/boj1043.java new file mode 100644 index 0000000..98e7918 --- /dev/null +++ b/jongwon/boj1043.java @@ -0,0 +1,54 @@ +package P_1031; + +import java.util.Scanner; + +public class boj1043 { + static int N, M; + static boolean[] know; + static boolean[][] adj; + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + N = sc.nextInt(); + M = sc.nextInt(); + know = new boolean[N + 1]; + int len = sc.nextInt(); + for (int i = 0; i < len; i++) + know[sc.nextInt()] = true; + int[][] party = new int[M][]; + + adj = new boolean[N + 1][N + 1]; + + for (int i = 0; i < M; i++) { + int partyPersonCount = sc.nextInt(); + party[i] = new int[partyPersonCount]; + party[i][0] = sc.nextInt(); + for (int j = 1; j < partyPersonCount; j++) { + party[i][j] = sc.nextInt(); + adj[party[i][j]][party[i][j - 1]] = true; + adj[party[i][j - 1]][party[i][j]] = true; + } + } + + for (int i = 1; i <= N; i++) + if (know[i]) + dfs(i); + + int cnt = 0; + for (int i = 0; i < M; i++) + if (!know[party[i][0]]) + cnt++; + + System.out.println(cnt); + + } + + static void dfs(int n) { + for (int i = 1; i <= N; i++) { + if (adj[n][i] && !know[i]) { + know[i] = true; + dfs(i); + } + } + } +} \ No newline at end of file diff --git a/jongwon/boj1707.java b/jongwon/boj1707.java new file mode 100644 index 0000000..71abccb --- /dev/null +++ b/jongwon/boj1707.java @@ -0,0 +1,62 @@ +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; +import java.util.Scanner; + +public class boj1707 { + + static List> graph; + static String answer; + public static void main(String[] args) { + Scanner sc= new Scanner(System.in); + int times = sc.nextInt(); + + for(int t = 0 ; t < times; t++) { + answer = "YES"; + int V = sc.nextInt(); + int E = sc.nextInt(); + graph = new ArrayList(); + for(int i = 0 ; i < V ; i++) { + graph.add(new ArrayList<>()); + } + + for(int i = 0 ; i < E ; i++) { + int p1 = sc.nextInt() - 1; + int p2 = sc.nextInt() - 1; + + graph.get(p1).add(p2); + graph.get(p2).add(p1); + } + set = new int[V]; + for(int i = 0 ; i < V ; i++) { + if(set[i] == 0) { + if(!bfs(i)) break; + } + } + System.out.println(answer); + } + } + static int[] set; + public static boolean bfs(int n) { + Queue que = new LinkedList<>(); + + que.add(n); + set[n] = 1; + + while(!que.isEmpty()) { + n = que.poll(); + for(Integer i : graph.get(n)) { + if(set[n] == set[i]) { + answer = "NO"; + return false; + } + if(set[i] == 0) { + set[i] = set[n]* -1; + que.add(i); + } + } + } + return true; + } +} diff --git a/jongwon/boj2617.java b/jongwon/boj2617.java new file mode 100644 index 0000000..3f975fb --- /dev/null +++ b/jongwon/boj2617.java @@ -0,0 +1,52 @@ +package P_1031; + +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + +public class boj2617 { + static boolean[] visited; + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + int n = sc.nextInt(); //총 숫자의 갯수를 받아 + int m = sc.nextInt(); //쌍의 갯수를 받아. + List> parentList = new ArrayList<>(); + List> childList = new ArrayList<>(); + for(int i = 0 ; i < n ; i++) { + parentList.add(new ArrayList<>()); //부모 리스트 + childList.add(new ArrayList<>()); // 애기 리스트 + } + + for(int i = 0 ; i < m ; i++) { + int bigger = sc.nextInt() - 1; + int smaller = sc.nextInt() - 1 ; + parentList.get(smaller).add(bigger); + childList.get(bigger).add(smaller); + } + int realAnswer = 0 ; + // 방문했더라면 안들어가도 괜찮아가 필요해. + visited = new boolean[n]; + for(int i = 0 ; i < n ; i++) { + for(int j = 0 ; j < n ; j++) { + visited[j] = false; + } + int upAnswer = dfs(i,parentList,0); + int downAnswer = dfs(i,childList,0); + if(upAnswer > n/2 || downAnswer > n/2) { + realAnswer++; + } + } + System.out.println(realAnswer); + } + + static int dfs(int x, List> arrayList, int cnt) { + for (int i = 0; i < arrayList.get(x).size(); i++) { + if (!visited[arrayList.get(x).get(i)]) { + visited[arrayList.get(x).get(i)] = true; + cnt += dfs(arrayList.get(x).get(i), arrayList, 1); + } + } + return cnt; + } +} \ No newline at end of file diff --git a/jongwon/boj5214.java b/jongwon/boj5214.java new file mode 100644 index 0000000..720ee2d --- /dev/null +++ b/jongwon/boj5214.java @@ -0,0 +1,68 @@ +package P_1031; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; +import java.util.Scanner; + +public class boj5214 { + static HashMap> hashMap; + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + int n = sc.nextInt(); // 역의 수 + int k = sc.nextInt(); // 하나의 하이퍼튜브가 서로 연결하는 역의 수 + int m = sc.nextInt(); // 하이퍼튜브 수 + + hashMap = new HashMap<>(); + for (int i = 0; i < n; i++) { + hashMap.put(i, new HashSet<>()); + } + + // m개를 연결 할 것인데 총 몇개? + for (int i = 0; i < m; i++) { + List tempList = new ArrayList<>(); + for (int j = 0; j < k; j++) { + tempList.add(sc.nextInt() - 1); + } + for (int l = 0; l < k - 1; l++) { + for (int o = l + 1; o < k; o++) { + hashMap.get(tempList.get(l)).add(tempList.get(o)); + hashMap.get(tempList.get(o)).add(tempList.get(l)); + } + } + } + //각각에 다 넣어주고 이제 bfs돌려버려 + + + //체크해라 마지막역까지 갈 수 있는지? + Queue que = new LinkedList<>(); + boolean[] visited= new boolean[n]; + + + que.add(new int[] {0,1}); + visited[0] = true; + int answer = -1; + while(!que.isEmpty()) { + int[] pollItem = que.poll(); + + if(pollItem[0] == n-1) { + answer = pollItem[1]; + System.out.println(answer); + break; + } + //만약 꺼내진게 조건에 맞으면 그냥 털어버려 + HashSet set = hashMap.get(pollItem[0]); + Integer[] arr = set.toArray(new Integer[0]); + + for(int i = 0 ; i < arr.length; i++) { + if(!visited[arr[i]]) { + que.add(new int[] {arr[i] ,pollItem[1] +1}); + } + } + } + } +} \ No newline at end of file diff --git a/minkyu/boj1043.java b/minkyu/boj1043.java new file mode 100644 index 0000000..659621a --- /dev/null +++ b/minkyu/boj1043.java @@ -0,0 +1,65 @@ +import java.util.*; +import java.io.*; + +public class Main { + static int[] p = {}; + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + int peopleCnt = Integer.parseInt(st.nextToken()); + int partyCnt = Integer.parseInt(st.nextToken()); + + p = new int[peopleCnt + 1]; + for (int i = 1; i <= peopleCnt; i++) + p[i] = i; + st = new StringTokenizer(br.readLine()); + Set trueSet = new HashSet<>(); + int trueCnt = Integer.parseInt(st.nextToken()); + for (int i = 0; i < trueCnt; i++) + trueSet.add(Integer.parseInt(st.nextToken())); + + int[][] parties = new int[partyCnt][]; + + // 각 파티별로 합치기 + for (int i = 0; i < partyCnt; i++) { + st = new StringTokenizer(br.readLine()); + int curCnt = Integer.parseInt(st.nextToken()); + int[] curParty = new int[curCnt]; + int first = Integer.parseInt(st.nextToken()); + curParty[0] = first; + int x = findSet(first); + for (int j = 1; j < curCnt; j++) { + curParty[j] = Integer.parseInt(st.nextToken()); + int y = findSet(curParty[j]); + if (x != y) + union(x, y); + } + parties[i] = curParty; + } + // 파인드셋으로 엮인 참 그룹의 대리자가 어떤 것인지 파악 + Set trulySet = new HashSet<>(); + for (int i : trueSet) + trulySet.add(findSet(i)); + + int cnt = 0; + // 각 파티별로 참인 그룹에 속하는 것이 있는지 파악 + main : for (int i = 0; i < partyCnt; i++) { + for (int j = 0; j < parties[i].length; j++) { + if (trulySet.contains(findSet(parties[i][j]))) + continue main; + } + cnt++; + } + System.out.println(cnt); + } + + public static int findSet(int x) { + if (p[x] != x) + p[x] = findSet(p[x]); + return p[x]; + } + + public static void union(int x, int y) { + p[y] = x; + } +} \ No newline at end of file diff --git a/minkyu/boj1068.java b/minkyu/boj1068.java new file mode 100644 index 0000000..c50ba30 --- /dev/null +++ b/minkyu/boj1068.java @@ -0,0 +1,61 @@ +import java.io.*; +import java.util.*; + + +public class Main { + static Node[] tree; + static int remove; + static int answer; + public static void main(String[] args) throws IOException { + //입력 + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + int N = Integer.parseInt(in.readLine()); + StringTokenizer st = new StringTokenizer(in.readLine()); + remove = Integer.parseInt(in.readLine()); + + //초기화 + tree = new Node[N]; + for(int i=0;i list = new ArrayList<>(); + Node(int idx){ + this.idx = idx; + } + void addChild(Node child){ + list.add(child); + } + } +} \ No newline at end of file diff --git a/minkyu/boj1167.java b/minkyu/boj1167.java new file mode 100644 index 0000000..54c07ad --- /dev/null +++ b/minkyu/boj1167.java @@ -0,0 +1,76 @@ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.*; + +public class Main { + static List[] map = null; + static boolean[] visited = null; + static int[] dist = null; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + int N = Integer.parseInt(br.readLine()); + + map = new ArrayList[N + 1]; + for (int i = 1; i <= N; i++) + map[i] = new ArrayList<>(); + + for (int i = 0; i < N; i++) { + st = new StringTokenizer(br.readLine()); + + int U = Integer.parseInt(st.nextToken()); + while(true) { + int V = Integer.parseInt(st.nextToken()); + if (V == - 1) break; + int dist = Integer.parseInt(st.nextToken()); + map[U].add(new Node(V, dist)); + map[V].add(new Node(U, dist)); + } + } + + visited = new boolean[N + 1]; + dist = new int[N + 1]; + // 임의의 지점에서 가장 먼 노드를 찾음 + bfs(1); + int node = 1; + for (int i = 2; i <= N; i++) { + if (dist[node] < dist[i]) + node = i; + } + + visited = new boolean[N + 1]; + dist = new int[N + 1]; + bfs(node); + int diameter = Arrays.stream(dist).max().getAsInt(); + System.out.println(diameter); + } + + public static void bfs(int start) { + Queue q = new ArrayDeque<>(); + visited[start] = true; + q.add(start); + + while (!q.isEmpty()) { + int tmp = q.poll(); + for (Node p : map[tmp]) { + if (!visited[p.no]) { + visited[p.no] = true; + dist[p.no] = dist[tmp] + p.dist; + q.add(p.no); + } + } + } + } + + static class Node { + int no; + int dist; + + public Node(int node, int dist) { + this.no = node; + this.dist = dist; + } + } +} \ No newline at end of file diff --git a/minkyu/boj15681.java b/minkyu/boj15681.java new file mode 100644 index 0000000..8917dc4 --- /dev/null +++ b/minkyu/boj15681.java @@ -0,0 +1,47 @@ +import java.util.*; +import java.io.*; + +public class Main { + static int[] childCnt; + static List[] list; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + + int N = Integer.parseInt(st.nextToken()); + int R = Integer.parseInt(st.nextToken()); + int Q = Integer.parseInt(st.nextToken()); + + list = new ArrayList[N + 1]; + for (int i = 1; i < N + 1; i++) + list[i] = new ArrayList<>(); + + childCnt = new int[N + 1]; + Arrays.fill(childCnt, 1); + + for (int i = 0; i < N - 1; i++) { + st = new StringTokenizer(br.readLine()); + int U = Integer.parseInt(st.nextToken()); + int V = Integer.parseInt(st.nextToken()); + + list[U].add(V); + list[V].add(U); + } + recur(R, -1); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < Q; i++) { + int idx = Integer.parseInt(br.readLine()); + sb.append(childCnt[idx]).append("\n"); + } + System.out.println(sb); + } + + static void recur(int idx, int parent) { + for (int i = 0; i < list[idx].size(); i++) + if (parent != list[idx].get(i)) recur(list[idx].get(i), idx); + + if (parent != -1) + childCnt[parent] += childCnt[idx]; + } +} \ No newline at end of file diff --git a/minkyu/boj1707.java b/minkyu/boj1707.java new file mode 100644 index 0000000..8ac6115 --- /dev/null +++ b/minkyu/boj1707.java @@ -0,0 +1,60 @@ +import java.util.*; +import java.io.*; + +public class Main { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + int T = Integer.parseInt(br.readLine()); + for (int tc = 0; tc < T; tc++) { + st = new StringTokenizer(br.readLine()); + int V = Integer.parseInt(st.nextToken()); + int E = Integer.parseInt(st.nextToken()); + + // 인접리스트 목록 정리 + List[] adjList = new ArrayList[V + 1]; + for (int i = 1; i <= V; i++) + adjList[i] = new ArrayList<>(); + + for (int i = 0; i < E; i++) { + st = new StringTokenizer(br.readLine()); + int a = Integer.parseInt(st.nextToken()); + int b = Integer.parseInt(st.nextToken()); + adjList[a].add(b); + adjList[b].add(a); + } + + int[] color = new int[V + 1]; + Queue q = new ArrayDeque<>(); + boolean isBinary = true; + main : for (int j = 1; j <= V; j++) { + if (color[j] == 0) { + q.offer(new int[] {j,1}); + color[j] = 1; + while(!q.isEmpty()) { + int[] tmp = q.poll(); + for (int i = 0; i < adjList[tmp[0]].size(); i++) { + int nextVal = adjList[tmp[0]].get(i); + // 다음 번 색상이 비어있는 경우 + if (color[nextVal] == 0) { + // 전의 값과 반대되는 색상을 넣는다. + color[nextVal] = -tmp[1]; + q.offer(new int[] {nextVal, -tmp[1]}); + // 전과 색상이 같은 곳이 존재하면 이분 그래프가 아니다. + }else if (color[nextVal] == tmp[1]) { + isBinary = false; + break main; + } + } + } + } + } + + + if (isBinary) + System.out.println("YES"); + else + System.out.println("NO"); + } + } +} \ No newline at end of file diff --git a/minkyu/boj1967.java b/minkyu/boj1967.java new file mode 100644 index 0000000..c2a0f57 --- /dev/null +++ b/minkyu/boj1967.java @@ -0,0 +1,72 @@ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.*; + +public class Main { + static List[] map = null; + static boolean[] visited = null; + static int[] dist = null; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + int n = Integer.parseInt(st.nextToken()); + + map = new ArrayList[n + 1]; + for (int i = 1; i <= n; i++) + map[i] = new ArrayList<>(); + + for (int i = 0; i < n - 1; i++) { + st = new StringTokenizer(br.readLine()); + int U = Integer.parseInt(st.nextToken()); + int V = Integer.parseInt(st.nextToken()); + int dist = Integer.parseInt(st.nextToken()); + map[U].add(new Node(V, dist)); + map[V].add(new Node(U, dist)); + } + + visited = new boolean[n + 1]; + dist = new int[n + 1]; + // 임의의 지점에서 가장 먼 노드를 찾음 + bfs(1); + int node = 1; + for (int i = 2; i <= n; i++) { + if (dist[node] < dist[i]) + node = i; + } + + visited = new boolean[n + 1]; + dist = new int[n + 1]; + bfs(node); + int diameter = Arrays.stream(dist).max().getAsInt(); + System.out.println(diameter); + } + + public static void bfs(int start) { + Queue q = new ArrayDeque<>(); + visited[start] = true; + q.add(start); + + while (!q.isEmpty()) { + int tmp = q.poll(); + for (Node p : map[tmp]) { + if (!visited[p.no]) { + visited[p.no] = true; + dist[p.no] = dist[tmp] + p.dist; + q.add(p.no); + } + } + } + } + + static class Node { + int no; + int dist; + + public Node(int node, int dist) { + this.no = node; + this.dist = dist; + } + } +} \ No newline at end of file diff --git a/minkyu/boj2617.java b/minkyu/boj2617.java new file mode 100644 index 0000000..f0cfb4e --- /dev/null +++ b/minkyu/boj2617.java @@ -0,0 +1,61 @@ +import java.util.*; +import java.io.*; + +public class Main { + static int N, M; + static List[] adjList; + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + N = Integer.parseInt(st.nextToken()); + M = Integer.parseInt(st.nextToken()); + // 인접 리스트 추가 + adjList = new ArrayList[N + 1]; + for (int i = 1; i<=N; i++) + adjList[i] = new ArrayList<>(); + for (int i = 0; i < M; i++) { + st = new StringTokenizer(br.readLine()); + int heavy = Integer.parseInt(st.nextToken()); + int light = Integer.parseInt(st.nextToken()); + adjList[heavy].add(new Marble(light, false)); + adjList[light].add(new Marble(heavy, true)); + } + + int cnt = 0; + for (int i = 1; i <= N; i++) { + int heavyCnt = bfs(i, true); + int lightCnt = bfs(i, false); + if (Math.max(heavyCnt, lightCnt) > (N / 2)) + cnt++; + } + System.out.println(cnt); + } + + public static int bfs(int s, boolean finder) { + int cnt = 0; + boolean[] visited = new boolean[N + 1]; + Queue q = new ArrayDeque<>(); + q.offer(s); + visited[s] = true; + while(!q.isEmpty()) { + int tmp = q.poll(); + for (int i = 0; i < adjList[tmp].size(); i++) { + Marble m = adjList[tmp].get(i); + if (visited[m.from] || m.isHeavy != finder) continue; + q.offer(m.from); + visited[m.from] = true; + cnt++; + } + } + return cnt; + } +} + +class Marble{ + int from; + boolean isHeavy; + public Marble(int from, boolean isHeavy) { + this.from = from; + this.isHeavy = isHeavy; + } +} \ No newline at end of file diff --git a/minkyu/boj2887.java b/minkyu/boj2887.java new file mode 100644 index 0000000..6fc1bca --- /dev/null +++ b/minkyu/boj2887.java @@ -0,0 +1,79 @@ +import java.util.*; +import java.io.*; + +public class Main { + static int[] p = {}; + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + int N = Integer.parseInt(br.readLine()); + + // 서로소 집합 구현용 + p = new int[N]; + // 초기화 + for (int i = 0; i < N; i++) + p[i] = i; + + List xList = new ArrayList<>(); + List yList = new ArrayList<>(); + List zList = new ArrayList<>(); + for (int i = 0; i < N; i++) { + st = new StringTokenizer(br.readLine()); + xList.add(new int[] {i, Integer.parseInt(st.nextToken())}); + yList.add(new int[] {i, Integer.parseInt(st.nextToken())}); + zList.add(new int[] {i, Integer.parseInt(st.nextToken())}); + } + + // 오름 차순으로 정렬해서 인접한 것의 행성끼리만 간선을 생성해서 비교해주면 된다. + Collections.sort(xList, (o1,o2) -> { + return Integer.compare(o1[1], o2[1]); + }); + Collections.sort(yList, (o1,o2) -> { + return Integer.compare(o1[1], o2[1]); + }); + Collections.sort(zList, (o1,o2) -> { + return Integer.compare(o1[1], o2[1]); + }); + + List tunnels = new ArrayList<>(); + for (int i = 0; i < N - 1; i++) { + tunnels.add(new int[] {xList.get(i)[0], xList.get(i + 1)[0], Math.abs(xList.get(i)[1] - xList.get(i+1)[1])}); + tunnels.add(new int[] {yList.get(i)[0], yList.get(i + 1)[0], Math.abs(yList.get(i)[1] - yList.get(i+1)[1])}); + tunnels.add(new int[] {zList.get(i)[0], zList.get(i + 1)[0], Math.abs(zList.get(i)[1] - zList.get(i+1)[1])}); + } + // 걸리는 비용에 대해 오름차순 정렬 + Collections.sort(tunnels, (o1,o2) ->{ + return Integer.compare(o1[2], o2[2]); + }); + + int cnt = 0; + long sum = 0; + for (int i = 0; i < tunnels.size(); i++) { + int x = findSet(tunnels.get(i)[0]); + int y = findSet(tunnels.get(i)[1]); + int cost = tunnels.get(i)[2]; + if (x != y) { + union(x, y); + sum += cost; + cnt++; + } + + if (cnt == N - 1) + break; + } + + System.out.println(sum); + } + + // 서로소 집합 대표자 확인 + public static int findSet(int x) { + if (p[x] != x) + p[x] = findSet(p[x]); + return p[x]; + } + + // 서로소 집합 병합 + public static void union(int x, int y) { + p[y] = x; + } +} \ No newline at end of file diff --git a/minkyu/boj5214.java b/minkyu/boj5214.java new file mode 100644 index 0000000..8f1e919 --- /dev/null +++ b/minkyu/boj5214.java @@ -0,0 +1,55 @@ +import java.util.*; +import java.io.*; + +public class Main { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + int N = Integer.parseInt(st.nextToken()); + int K = Integer.parseInt(st.nextToken()); + int M = Integer.parseInt(st.nextToken()); + Set[] tubes = new HashSet[M]; + for (int i = 0; i < M; i++) + tubes[i] = new HashSet<>(); + + // 하이퍼 튜브를 하나의 노드로 생성 + for (int i = 0; i < M; i++) { + st = new StringTokenizer(br.readLine()); + for (int j = 0; j < K; j++) { + int curVal = Integer.parseInt(st.nextToken()); + tubes[i].add(curVal); + } + } + + + int minWay = -1; + // 추가가 완료된 행렬에서 bfs를 통해 1번역에서 N번역으로 갈 수 있는 역의 개수 최솟값을 출력할 것 + boolean[] visitedTube = new boolean[M]; + boolean[] visited = new boolean[N + 1]; + + Queue q = new ArrayDeque<>(); + q.offer(new int[] {1,1}); + visited[1] = true; + while(!q.isEmpty()) { + int[] tmp = q.poll(); + if (tmp[0] == N) { + minWay = tmp[1]; + break; + } + for (int i = 0; i < M; i++) { + if (visitedTube[i]) continue; + if (tubes[i].contains(tmp[0])) { + // 갈 수 있는 곳 지정 + for (int k : tubes[i]) { + if (visited[k]) continue; + q.offer(new int[] {k,tmp[1] + 1}); + visited[k] = true; + } + visitedTube[i] = true; + } + } + } + + System.out.println(minWay); + } +} \ No newline at end of file diff --git a/minsung/S2_Graph/BOJ_1707_BipartiteGraph.java b/minsung/S2_Graph/BOJ_1707_BipartiteGraph.java new file mode 100644 index 0000000..2e5e5b9 --- /dev/null +++ b/minsung/S2_Graph/BOJ_1707_BipartiteGraph.java @@ -0,0 +1,64 @@ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.*; + +public class BOJ_1707_BipartiteGraph { + public static void main(String[] args) throws NumberFormatException, IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringBuilder sb = new StringBuilder(); + int T = Integer.parseInt(br.readLine()); + + for (int t = 1; t <= T; t++) { + StringTokenizer st = new StringTokenizer(br.readLine()); + int V = Integer.parseInt(st.nextToken()); + int E = Integer.parseInt(st.nextToken()); + + // LinkedList -> ArrayList로 변경 + List> adjList = new ArrayList<>(); + + for (int i = 0; i <= V; i++) { + adjList.add(new ArrayList<>()); + } + + for (int i = 0; i < E; i++) { + st = new StringTokenizer(br.readLine()); + int a = Integer.parseInt(st.nextToken()); + int b = Integer.parseInt(st.nextToken()); + adjList.get(a).add(b); + adjList.get(b).add(a); + } + + Queue queue = new LinkedList<>(); + int[] colors = new int[V + 1]; + boolean flag = false; + + out: for (int i = 1; i <= V; i++) { + if (colors[i] == 0) { + colors[i] = 1; + queue.add(i); + + while (!queue.isEmpty()) { + int tmp = queue.poll(); + + for (int vertex : adjList.get(tmp)) { + if (colors[vertex] == 0) { + colors[vertex] = -colors[tmp]; + queue.add(vertex); + } else if (colors[vertex] == colors[tmp]) { + flag = true; + break out; + } + } + } + } + } + + // println 대신 StringBuilder 사용 + sb.append(flag ? "NO" : "YES").append("\n"); + } + + // 한 번에 출력 + System.out.print(sb); + } +} \ No newline at end of file diff --git a/minsung/S2_Graph/BOJ_2617_FindGusel.java b/minsung/S2_Graph/BOJ_2617_FindGusel.java new file mode 100644 index 0000000..74a7c96 --- /dev/null +++ b/minsung/S2_Graph/BOJ_2617_FindGusel.java @@ -0,0 +1,71 @@ +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 BOJ_2617_FindGusel { + static List> leAdjList = new ArrayList<>(); + static List> grAdjList = new ArrayList<>(); + static int V, E; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + + V = Integer.parseInt(st.nextToken()); + E = Integer.parseInt(st.nextToken()); + + for (int i = 0; i <= V; i++) { + grAdjList.add(new ArrayList<>()); + leAdjList.add(new ArrayList<>()); + } + + for (int i = 0; i < E; i++) { + st = new StringTokenizer(br.readLine()); + int a = Integer.parseInt(st.nextToken()); + int b = Integer.parseInt(st.nextToken()); + + grAdjList.get(b).add(a); + leAdjList.get(a).add(b); + } + + int mid = (V + 1) / 2; + int ans = 0; + int bigger, less; + + for (int i = 1; i <= V; i++) { + less = bfs(i, leAdjList); + bigger = bfs(i, grAdjList); + if (bigger >= mid || less >= mid) + ans++; + } + + System.out.println(ans); + } + + static int bfs(int start, List> adjList) { + boolean[] visited = new boolean[V + 1]; + int count = 0; + Queue queue = new LinkedList<>(); + + visited[start] = true; + queue.offer(start); + + while (!queue.isEmpty()) { + int curr = queue.poll(); + for (int i : adjList.get(curr)) { + if (!visited[i]) { + visited[i] = true; + count++; + queue.offer(i); + } + } + } + + return count; + } +} \ No newline at end of file diff --git a/minsung/S2_Tree/BOJ_15681 b/minsung/S2_Tree/BOJ_15681 new file mode 100644 index 0000000..b33414a --- /dev/null +++ b/minsung/S2_Tree/BOJ_15681 @@ -0,0 +1,70 @@ +import java.util.*; + +public class Main { + static ArrayList> tree; + static ArrayList> children; + static int[] parent; + static int[] size; // 각 노드를 루트로 하는 서브트리의 크기 + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + int N = sc.nextInt(); + int R = sc.nextInt(); + int Q = sc.nextInt(); + + + tree = new ArrayList<>(); + children = new ArrayList<>(); + for(int i = 0; i <= N; i++) { + tree.add(new ArrayList<>()); + children.add(new ArrayList<>()); + } + + parent = new int[N + 1]; + size = new int[N + 1]; + + + for(int i = 0; i < N-1; i++) { + int U = sc.nextInt(); + int V = sc.nextInt(); + + tree.get(U).add(V); + tree.get(V).add(U); + } + + + makeTree(R, -1); + + + countSubtreeSize(R); + + + for(int i = 0; i < Q; i++) { + int U = sc.nextInt(); + System.out.println(size[U]); + } + } + + + static void makeTree(int current, int prev) { + for(int next : tree.get(current)) { + if(next != prev) { + children.get(current).add(next); + parent[next] = current; + makeTree(next, current); + } + } + } + + + static int countSubtreeSize(int node) { + size[node] = 1; + + for(int child : children.get(node)) { + size[node] += countSubtreeSize(child); + } + + return size[node]; + } +} diff --git a/minsung/Week1_Stack/BOJ_10799_Stick.java b/minsung/Week1_Stack/BOJ_10799_Stick.java new file mode 100644 index 0000000..e4f029a --- /dev/null +++ b/minsung/Week1_Stack/BOJ_10799_Stick.java @@ -0,0 +1,35 @@ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Stack; + +public class BOJ_10799_Stick { + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String str = br.readLine(); + + Stack laser = new Stack<>(); + Stack stick = new Stack<>(); + + int[] laserP = new int[str.length()]; + int index = 0; + for (int i = 0; i < str.length(); i++) { + if (str.charAt(i) == '(') { + if (laser.empty()) { + laser.push(1); + } + + } else if (str.charAt(i) == ')') { + if (!laser.empty()) { + laserP[index++] = i; + laser.pop(); + } + } + } + + + + } + +} diff --git a/minsung/Week1_Stack/BOJ_10799_stick.java b/minsung/Week1_Stack/BOJ_10799_stick.java new file mode 100644 index 0000000..aea20c0 --- /dev/null +++ b/minsung/Week1_Stack/BOJ_10799_stick.java @@ -0,0 +1,36 @@ +package Stack; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Stack; + +public class BOJ_10799_stick { + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String str = br.readLine(); + Stack stick = new Stack<>(); + int result = 0; + for (int i = 0; i < str.length(); i++) { + if (str.charAt(i) == '(') { + // 막대 또는 레이저 시작 + stick.push(str.charAt(i)); + + } else if (str.charAt(i) == ')' && str.charAt(i - 1) == '(') { + // 레이저 -> 현재 막대 개수만큼 result 에 추가 + stick.pop(); + result += stick.size(); + } else if (str.charAt(i) == ')' && str.charAt(i - 1) == ')') { + // 막대의 끝. 막대 개수 1개 추가. + stick.pop(); + result += 1; + } + } + + System.out.println(result); + + br.close(); + } + +} diff --git a/nayeon/boj/boj1043.java b/nayeon/boj/boj1043.java new file mode 100644 index 0000000..75efd59 --- /dev/null +++ b/nayeon/boj/boj1043.java @@ -0,0 +1,72 @@ +import java.util.*; +import java.lang.*; +import java.io.*; + +public class Main { + public static void main(String[] args) { + // input + Scanner sc = new Scanner(System.in); + + int peopleNum = sc.nextInt(); // 총 사람 수 + int partyNum = sc.nextInt(); // 총 파티 수 + + int knowingPeopleNum = sc.nextInt(); // 진실을 아는 사람의 수 + + // 진실을 아는 사람이 아무도 없으면, 모든 파티에서 비밀 유지 가능 + if(knowingPeopleNum == 0){ + System.out.println(partyNum); + return; + } + + // 진실을 아는 사람들의 리스트 + List knowingPeople = new ArrayList<>(); + for(int i = 0; i < knowingPeopleNum; i++){ + knowingPeople.add(sc.nextInt()); + } + + // 파티 리스트 -> 각 파티는 참석자의 리스트로 구성 + List> partyGraph = new ArrayList<>(); + for(int i = 0; i < partyNum; i++){ + int num = sc.nextInt(); // 현재 파티에 참석하는 사람 수 + List row = new ArrayList<>(); + + for(int j = 0; j < num; j++){ + row.add(sc.nextInt()); + } + + partyGraph.add(row); + } + // 입력 완료 + + int idx = 0; + + // 알고 있는 사람 리스트가 업데이트되는 동안 반복 + while(knowingPeople.size() > idx && partyGraph.size() != 0){ + int nowKnowingPerson = knowingPeople.get(idx); // 현재 알고 있는 사람 + int size = partyGraph.size(); + + // 파티 리스트를 순회하면서 진실을 아는 사람이 포함된 파티를 찾음 + for(Iterator> pgItr = partyGraph.iterator(); pgItr.hasNext();){ + List nowParty = pgItr.next(); + // 현재 파티에 진실을 아는 사람이 있으면 + if(nowParty.contains(nowKnowingPerson)){ + pgItr.remove(); // 비밀이 밝혀질 수 있는 파티는 제거 + + // 파티의 모든 참석자를 순회하여 진실을 아는 사람 리스트에 추가 + Iterator npItr = nowParty.iterator(); + while(npItr.hasNext()){ + int element = npItr.next(); + + // 아직 진실을 모르는 사람만 리스트에 추가 + if(!knowingPeople.contains(element)) + knowingPeople.add(element); + } + } + } + idx++; + } + + System.out.println(partyGraph.size()); + } // main +} // class + diff --git a/nayeon/boj/boj1068.java b/nayeon/boj/boj1068.java new file mode 100644 index 0000000..85eaa19 --- /dev/null +++ b/nayeon/boj/boj1068.java @@ -0,0 +1,69 @@ +import java.util.LinkedList; +import java.util.Queue; +import java.util.Scanner; + +public class Main { + static int N, D; + static int[] parentsNode; + static boolean[] visited; + static Queue q = new LinkedList<>(); + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + N = sc.nextInt(); + + parentsNode = new int[N]; + visited = new boolean[N]; + + for (int i = 0; i < N; i++) { + parentsNode[i] = sc.nextInt(); + } + + D = sc.nextInt(); + + // 노드 먼저 삭제 진행 (true로 표시 = 삭제 의미) + dfs(D); + + // 리드노프 수 계산 + int count = 0; + for (int i = 0; i < N; i++) { + // 현재 노드가 리프 노드인지 확인 check + boolean check = false; + + // 노드가 삭제되지 않은 경우에만 검사 + if (!visited[i]) { + check = true; // 리프 노드라고 가정 + + // 현재 노드가 삭제되지 않은 자식을 가지고 있는지 검사 + for (int j = 0; j < N; j++) { + // 자식이 있는 경우 + if (!visited[j] && parentsNode[j] == i) { + check = false; // 리프 노드 X + } + } + } + // 리프 노드일 경우 count 증가 + if (check) + count++; + } + System.out.println(count); + + } // main + + public static void dfs(int num) { + // 큐에는 삭제가 필요한 노드들이 들어오게 된다 ! + // 여기서는 true로 표시된 노드들이 확인할 필요가 없는 노드임을 의미 + q.add(num); + + while (!q.isEmpty()) { + int cur = q.poll(); + visited[cur] = true; + + for (int i = 0; i < N; i++) { + if (parentsNode[i] == cur) { // 부모 노드가 확인할 필요가 없다면 해당 자식 노드도 필요없음 ! + q.offer(i); + } + } + } + } // dfs +} // class diff --git a/nayeon/boj/boj1167.java b/nayeon/boj/boj1167.java new file mode 100644 index 0000000..cfb28a1 --- /dev/null +++ b/nayeon/boj/boj1167.java @@ -0,0 +1,94 @@ +import java.io.IOException; +import java.util.ArrayList; +import java.util.Scanner; + +// 간선 정보 저장 +class edge { + int childNode; // 자식 노드 번호 + int weight; // 가중치 + + public edge(int childNode, int weight) { + this.childNode = childNode; + this.weight = weight; + } +} + +public class Main { + static int V; + static ArrayList[] tree; + static boolean[] visited; // 노드 방문 여부 + static int maxDistance = 0; // 트리의 지름 저장 + static int farthestNode = 0; // 가장 먼 노드 저장 + + public static void main(String[] args) throws IOException { + Scanner sc = new Scanner(System.in); + + // 노드 개수 입력 + V = sc.nextInt(); + tree = new ArrayList[V + 1]; // 노드 번호가 1부터 시작 -> N + 1 크기의 배열 생성 + + // 인접 리스트 초기화 + for (int i = 1; i <= V; i++) { + tree[i] = new ArrayList<>(); + } + +// // V이 1인 경우, 트리의 지름은 0으로 출력 +// if (V == 1) { +// System.out.println(0); +// return; +// } + + // 트리의 간선 정보 입력 + for (int i = 1; i <= V; i++) { + int p = sc.nextInt(); // 부모 노드 + while (true) { + int c = sc.nextInt(); // 자식 노드 + if (c == -1) { + break; + } + int w = sc.nextInt(); // 간선의 가중치 + + // 무방향 그래프 : 양방향으로 간선 추가 + tree[p].add(new edge(c, w)); + tree[c].add(new edge(p, w)); + } + + } + + // 첫 번째 DFS : 1번 노드에서 가장 먼 노드 찾기 + visited = new boolean[V + 1]; + dfs(1, 0); + + // 두 번째 DFS : 첫 번째 DFS에서 찾은 가장 먼 노드에서 시작하여 트리의 지름 계산 + maxDistance = 0; // 최대 거리 초기화 + visited = new boolean[V + 1]; // 방문 배열 초기화 + dfs(farthestNode, 0); + + // 결과 출력 + System.out.println(maxDistance); + + } // main + + // 현재 노드에서 최대 거리와 가장 먼 노드를 찾기 + public static void dfs(int node, int distance) { + visited[node] = true; // 현재 노드 방문 처리 + + // 최대 거리와 가장 먼 노드 갱신 + if (distance > maxDistance) { + maxDistance = distance; + farthestNode = node; + } + + // 현재 노드에 연결된 모든 간선을 탐색 + for (edge edge : tree[node]) { + int nextNode = edge.childNode; + int weight = edge.weight; + + // 아직 방문하지 않은 노드라면 재귀 호출 + if (!visited[nextNode]) { + dfs(nextNode, distance + weight); + } + } + } // dfs + +} // class diff --git a/nayeon/boj/boj15681.java b/nayeon/boj/boj15681.java new file mode 100644 index 0000000..6293e54 --- /dev/null +++ b/nayeon/boj/boj15681.java @@ -0,0 +1,59 @@ +import java.util.*; + +public class Main { + + static int N, R, Q; + static ArrayList[] tree; + static boolean[] visited; + static int[] dp; + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + N = sc.nextInt(); + R = sc.nextInt(); + Q = sc.nextInt(); + + tree = new ArrayList[N + 1]; + + for (int i = 0; i <= N; i++) { + tree[i] = new ArrayList<>(); + } + + for (int i = 0; i < N - 1; i++) { + int a = sc.nextInt(); + int b = sc.nextInt(); + // 무방향 + tree[a].add(b); + tree[b].add(a); + } + + dp = new int[N + 1]; + + visited = new boolean[N + 1]; + + // 루트 노드 R에서 서브트리 크기 계산 + find(R); + + // 쿼리 수 만큼 반복 + for (int i = 0; i < Q; i++) { + int t = sc.nextInt(); + System.out.println(dp[t]); + } + } // main + + static int find(int v) { + visited[v] = true; // 현재 정점 v를 방문 처리 + int ret = 1; // 현재 정점을 포함하여 서브트리 크기 초기화 + + // 현재 정점과 연결된 모든 자식 노드에 대해 반복 + for (int child : tree[v]) { + // 아직 방문하지 않은 자식 노드인 경우 + if (!visited[child]) { + ret += find(child); // 자식 노드의 서브트리 크기 추가 + } + } + + dp[v] = ret; // 현재 정점 v의 서브트리 크기를 dp에 저장 + return ret; // 서브트리 크기 반환 + } // find +} // class diff --git a/nayeon/boj/boj1707.java b/nayeon/boj/boj1707.java new file mode 100644 index 0000000..dc2438a --- /dev/null +++ b/nayeon/boj/boj1707.java @@ -0,0 +1,76 @@ +import java.util.*; + +// 이분 그래프로 나누기 위해서는 각 정점을 두 가지 색 중 하나로 구분하는 작업이 필요 +// -> "색칠"이라고 표현 + +// 이분 그래프는 인접한 정점끼리 서로 다른 색을 가져야 하는데 +// 이를 위해 하나의 색상(0 또는 1)을 각 정점에 할당해 +// 인접한 두 정점이 서로 다른 색을 가지도록 설정 +public class Main { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + // 테케 입력 + int K = scanner.nextInt(); + for (int k = 0; k < K; k++) { + int V = scanner.nextInt(); // 정점 수 + int E = scanner.nextInt(); // 간선 수 + + List[] list = new ArrayList[V + 1]; + for (int i = 1; i <= V; i++) { + list[i] = new ArrayList<>(); + } + + // 간선 정보 입력 + for (int i = 0; i < E; i++) { + int v1 = scanner.nextInt(); + int v2 = scanner.nextInt(); + // v1-v2와 v2-v1 모두 간선으로 저장 + list[v1].add(v2); + list[v2].add(v1); + } + + boolean result = true; + Integer[] draw = new Integer[V + 1]; + + // 모든 정점을 순회 + for (int i = 1; i <= V; i++) { + if (!result) // 결과가 false이면 반복 종료 + break; + + // 현재 정점이 아직 색칠되지 않았다면 색칠 + if (draw[i] == null) + result = check(list, draw, i, 0); // 0번 색으로 시작 + else + check(list, draw, i, draw[i]); // 이미 색칠된 정점은 그 색으로 체크 + } + + System.out.println(result ? "YES" : "NO"); + } // k번 반복 + } // main + + // 어떤 정점과 그 인접 정점이 같은 색을 가지게 된다면, 이분 그래프가 될 수 없다고 판단 -> false + public static boolean check(List[] list, Integer[] draw, int v, int color) { + // 현재 정점이 이미 색칠되어 있고 색상이 일치하면 true + if (draw[v] != null && draw[v] == color) + return true; + // 현재 정점이 이미 색칠되어 있고 색상이 불일치하면 false + if (draw[v] != null && draw[v] != color) + return false; + + boolean isTwoGraph = true; // 이분 그래프 여부 초기화 + draw[v] = color; // 현재 정점에 색상 칠하기 + + // 인접 정점에 대해 재귀적으로 색칠 시도 + for (Integer i : list[v]) { + if (!isTwoGraph) // 이분 그래프가 아닌 경우 반복 종료 + break; + + // 인접 정점의 색상을 현재 정점과 다르게 칠하기 + if (color == 0) + isTwoGraph = check(list, draw, i, 1); // 현재 정점이 0이라면 인접 정점은 1로 + else + isTwoGraph = check(list, draw, i, 0); // 현재 정점이 1이라면 인접 정점은 0으로 + } + return isTwoGraph; // 이분 그래프 여부 반환 + } // check +} // class diff --git a/nayeon/boj/boj1967.java b/nayeon/boj/boj1967.java new file mode 100644 index 0000000..2949391 --- /dev/null +++ b/nayeon/boj/boj1967.java @@ -0,0 +1,98 @@ +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.StringTokenizer; + +// 간선 정보 저장 +class Edge { + int childNode; // 자식 노드 번호 + int weight; // 가중치 + + public Edge(int childNode, int weight) { + this.childNode = childNode; + this.weight = weight; + } +} + +public class Main { + static int N; + static ArrayList[] tree; + static boolean[] visited; // 노드 방문 여부 + static int maxDistance = 0; // 트리의 지름 저장 + static int farthestNode = 0; // 가장 먼 노드 저장 + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); + + // 노드 개수 입력 + N = Integer.parseInt(br.readLine()); + tree = new ArrayList[N + 1]; // 노드 번호가 1부터 시작 -> N + 1 크기의 배열 생성 + + // 인접 리스트 초기화 + for (int i = 1; i <= N; i++) { + tree[i] = new ArrayList<>(); + } + + // N이 1인 경우, 트리의 지름은 0으로 출력 + if (N == 1) { + bw.write("0\n"); + bw.flush(); + bw.close(); + return; + } + + // 트리의 간선 정보 입력 + for (int i = 1; i < N; i++) { + StringTokenizer st = new StringTokenizer(br.readLine()); + int p = Integer.parseInt(st.nextToken()); // 부모 노드 + int c = Integer.parseInt(st.nextToken()); // 자식 노드 + int w = Integer.parseInt(st.nextToken()); // 간선의 가중치 + + // 무방향 그래프 : 양방향으로 간선 추가 + tree[p].add(new Edge(c, w)); + tree[c].add(new Edge(p, w)); + } + + // 첫 번째 DFS : 1번 노드에서 가장 먼 노드 찾기 + visited = new boolean[N + 1]; + dfs(1, 0); + + // 두 번째 DFS : 첫 번째 DFS에서 찾은 가장 먼 노드에서 시작하여 트리의 지름 계산 + maxDistance = 0; // 최대 거리 초기화 + visited = new boolean[N + 1]; // 방문 배열 초기화 + dfs(farthestNode, 0); + + // 결과 출력 + bw.write(maxDistance + "\n"); + bw.flush(); + bw.close(); + + } // main + + // 현재 노드에서 최대 거리와 가장 먼 노드를 찾기 + public static void dfs(int node, int distance) { + visited[node] = true; // 현재 노드 방문 처리 + + // 최대 거리와 가장 먼 노드 갱신 + if (distance > maxDistance) { + maxDistance = distance; + farthestNode = node; + } + + // 현재 노드에 연결된 모든 간선을 탐색 + for (Edge edge : tree[node]) { + int nextNode = edge.childNode; + int weight = edge.weight; + + // 아직 방문하지 않은 노드라면 재귀 호출 + if (!visited[nextNode]) { + dfs(nextNode, distance + weight); + } + } + } // dfs + +} // class diff --git a/nayeon/boj/boj2617.java b/nayeon/boj/boj2617.java new file mode 100644 index 0000000..2bbe32b --- /dev/null +++ b/nayeon/boj/boj2617.java @@ -0,0 +1,62 @@ +import java.util.Scanner; + +public class Main { + static int N, M; + static boolean[][] heavy; + static boolean[][] light; + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + N = sc.nextInt(); // 구슬 개수 + M = sc.nextInt(); // 비교 횟수 + + heavy = new boolean[N + 1][N + 1]; // 무거운 구슬 관계 + light = new boolean[N + 1][N + 1]; // 가벼운 구슬 관계 + + // 모든 관계 초기화 -> 자기 자신과의 관계는 제외 + for (int i = 1; i <= N; i++) { + heavy[i][i] = true; + light[i][i] = true; + } + + // 입력된 구슬 비교 정보 처리 + for (int i = 0; i < M; i++) { + int a = sc.nextInt(); // 구슬 a + int b = sc.nextInt(); // 구슬 b + heavy[a][b] = true; // a가 b보다 무겁다 + light[b][a] = true; // b가 a보다 가볍다 + } + + // 모든 구슬 간의 관계 계산 -> 관계가 있으면 true, 없으면 false + for (int k = 1; k <= N; k++) { + for (int i = 1; i <= N; i++) { + for (int j = 1; j <= N; j++) { + heavy[i][j] = heavy[i][j] || (heavy[i][k] && heavy[k][j]); + light[i][j] = light[i][j] || (light[i][k] && light[k][j]); + } + } + } + + int mid = (N + 1) / 2; // 중간 구슬의 기준 + int result = 0; + + // 각 구슬에 대해 무거운 구슬과 가벼운 구슬의 개수 확인 + for (int i = 1; i <= N; i++) { + int heavyCount = 0; + int lightCount = 0; + + // i번 구슬보다 무거운 구슬, 가벼운 구슬 개수 세기 + for (int j = 1; j <= N; j++) { + if (heavy[i][j]) heavyCount++; // i번 구슬보다 무거운 구슬 + if (light[i][j]) lightCount++; // i번 구슬보다 가벼운 구슬 + } + + // 중간 순서보다 무겁거나 가벼운 구슬이 있으면 결과에 카운트 + if (heavyCount > mid || lightCount > mid) { + result++; + } + } + + System.out.println(result); + } +}