https://www.acmicpc.net/problem/14267
14267๋ฒ: ํ์ฌ ๋ฌธํ 1
์์ ํ์ฌ์๋ ๋งค์ฐ ์ข์ ๋ฌธํ๊ฐ ์๋๋ฐ, ๋ฐ๋ก ์์ฌ๊ฐ ์ง์ ๋ถํ๋ฅผ ์นญ์ฐฌํ๋ฉด ๊ทธ ๋ถํ๊ฐ ๋ถํ์ ์ง์ ๋ถํ๋ฅผ ์ฐ์์ ์ผ๋ก ์นญ์ฐฌํ๋ ๋ด๋ฆฌ ์นญ์ฐฌ์ด ์๋ค. ์ฆ, ์์ฌ๊ฐ ํ ์ง์ ๋ถํ๋ฅผ ์นญ์ฐฌํ๋ฉด ๊ทธ ๋ถํ
www.acmicpc.net
import java.util.*;
import java.io.*;
public class Main {
static List<Integer>[] t;
static int[] p;
static boolean[] v;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
t = new ArrayList[n + 1]; // idx=1์ ์ฌ์ฅ์ด๋๊น -1๋ค์ด๊ฐ.
// -1 1 2 3 4
// 1์ ์ฌ์ฅ์ด๋ ์ง์ ์์ฌ๊ฐ ์์ผ๋ฏ๋ก -1
// 2๋ ์ง์, ์ฌ์ฅ์ด ์ง์์์ฌ.
p = new int[n + 1];
int sajang = sc.nextInt();
for (int i = 1; i <= n; i++) {
t[i] = new ArrayList<>();
}
for (int i = 2; i <= n; i++) {
int sup = sc.nextInt(); // i๋ฒ ์ง์์ ์์ฌ๊ฐ tmp๋ค.
t[sup].add(i);
}
for (int i = 1; i <= m; i++) {
int idx = sc.nextInt();
int w = sc.nextInt();
v = new boolean[n + 1];
f(idx, w);
}
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= n; i++) {
sb.append(p[i]).append(" ");
}
System.out.println(sb);
}
public static void f(int target, int appr) {
v[target] = true;
if (p[target] == 0) {
p[target] = appr;
} else {
p[target] += appr;
}
for (int i = 0; i < t[target].size(); i++) {
int child = t[target].get(i);
if(!v[child]) {
f(child, appr);
}
// ์์์ ๊บผ๋ด์, ๊ฑ๋ ๋ฃ์ด์ค.
// p[target] += appr; <- ์ด ๋ฐฉ์์ด๋ฉด leaf ๋
ธ๋๋ ์์์ด ์์ด์ ๋ํด์ง ์ผ์ด ์๋ค..
}
}
}
์ค๋ต๋ ธํธ(ํธ๋ ๋์ ์ฌ๊ณ ๊ณผ์ ๋ฐ ๊ฐ์ ์ )
์๊ฐ ์ด๊ณผ๊ฐ ๋๋ ์ฝ๋๋ค. ์ ๋ ฅ์ด 10๋ง์ธ๋ฐ for๋ฌธ์์ for๋ฅผ ๋๋ฆฌ๋ ์ฌ๊ทํจ์๋ฅผ ๋ฃ์ด๋ฒ๋ ธ์ผ๋ ๋น์ฐํ ์๊ฐ์ด๊ณผ๊ฐ ๋๋ค..
์นญ์ฐฌ์ ๊ณ์ฐํ ๋ฐฐ์ด์ ๋ฐ๋ก ๋นผ์ ๊ด๋ฆฌํด์ผ o(n)์ผ๋ก ๊ฐ๋ฅํ๋ค...!
visited๋ฐฐ์ด์ด ํ์๊ฐ ์์๋ ๋ฌธ์ !
์ ๋ต์ฝ๋
public class Main {
static List<Integer>[] t;
static int[] p;
static int[] like;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
t = new ArrayList[n + 1]; // idx=1์ ์ฌ์ฅ์ด๋๊น -1๋ค์ด๊ฐ.
// -1 1 2 3 4
// 1์ ์ฌ์ฅ์ด๋ ์ง์ ์์ฌ๊ฐ ์์ผ๋ฏ๋ก -1
// 2๋ ์ง์, ์ฌ์ฅ์ด ์ง์์์ฌ.
p = new int[n + 1];
like = new int[n + 1];
int sajang = sc.nextInt();
for (int i = 1; i <= n; i++) {
t[i] = new ArrayList<>();
}
for (int i = 2; i <= n; i++) {
int sup = sc.nextInt(); // i๋ฒ ์ง์์ ์์ฌ๊ฐ tmp๋ค.
t[sup].add(i);
}
for (int i = 1; i <= m; i++) {
int idx = sc.nextInt();
int w = sc.nextInt();
like[idx] += w;
}
f(1);
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= n; i++) {
sb.append(like[i]).append(" ");
}
System.out.println(sb);
}
public static void f(int target) {
for (int i = 0; i < t[target].size(); i++) {
int child = t[target].get(i);
like[child] += like[target];
f(child);
}
}
}
๋์์ด ๋๋ค๋ฉด ๋๊ธ์ด๋ ๊ณต๊ฐ ๋ฒํผ ํ ๋ฒ์ฉ ๋๋ฅด๊ณ ๊ฐ์ฃผ์ธ์! ๋ก๊ทธ์ธ ์ํด๋ ๋ฉ๋๋ค ^_^
๋ฐ์ํ
'OJ๐ผ > ์ค๋ต๋ ธํธ๐' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[BOJ][JAVA] 14502: ์ฐ๊ตฌ์ (0) | 2024.03.01 |
---|---|
[BOJ][JAVA] 1918๋ฒ: ํ์ ํ๊ธฐ์ (0) | 2024.02.17 |
[BOJ][JAVA] 11725๋ฒ: ํธ๋ฆฌ์ ๋ถ๋ชจ์ฐพ๊ธฐ (0) | 2024.02.10 |
[BOJ][JAVA] 1012๋ฒ: ์ ๊ธฐ๋ ๋ฐฐ์ถ (0) | 2024.02.07 |
[BOJ][JAVA] 15988: 1, 2, 3 ๋ํ๊ธฐ 3 (0) | 2024.01.28 |