目录
G. Vlad and Trouble at MIT
题目大意:
思路解析:
题目大意是如果两个房间之间相连,那么其中一个房间只要能听到音乐就可以将这个状态传下去,但是我们可以通过在某个点放墙来阻断音乐的传播,但是经费有限,只能放尽量少的墙,请问最少需要多少堵墙。
P的房间可以传出音乐,C的房间可以是任意状态(他既可以接受音乐,也可以不听音乐),S的房间是不能拥有音乐。
所以我们可以想到此种情况下房间只有两种状态,要么作为P,要么作为S。(P房间只能作为P状态,S房间只能作为S状态)
则设计dp状态为 dp[x][1] 表示当前X结点作为S房间时,其结点和其子树满足题目要求最少需要多少堵墙, dp[x][0] 表示当前X结点作为P房间时,其结点和其子树满足题目要求最少需要多少堵墙。则跑一个树型dp即可。
代码实现:
import java.io.*;
import java.util.*;
public class Main {
static int mod = (int) 1e9 + 7;
static int mod9 = 998244353;
static Vector<Integer> g[];
static char[] a;
static int[][] dp;
static long res = 0;
static int INF = (int) 1e9;
public static void main(String[] args) throws IOException {
int t = input.nextInt();
for (int o = 0; o < t; o++) {
int n = input.nextInt();
g = new Vector[n + 1];
dp = new int[n + 1][2];
for (int i = 0; i < n + 1; i++) {
g[i] = new Vector<>();
}
for (int i = 2; i <= n; i++) {
int num = input.nextInt();
g[num].add(i);
g[i].add(num);
}
a = input.next().toCharArray();
dfs(1, 0);
out.println(Math.min(dp[1][0], dp[1][1]));
}
out.flush();
out.close();
br.close();
}
public static void dfs(int x, int fa) {
// dp[x][0] 表示当前点作为P点时的最小方案数 dp[x][1] 当前点作为S点时的最小方案数。
if (a[x - 1] == 'S') dp[x][0] = INF;
if (a[x - 1] == 'P') dp[x][1] = INF;
for (int i = 0; i < g[x].size(); i++) {
int y = g[x].get(i);
if (y == fa) continue;
dfs(y, x);
dp[x][0] += Math.min(dp[y][0], dp[y][1] + 1);
dp[x][1] += Math.min(dp[y][1], dp[y][0] + 1);
}
}
// -------------------------------- 模板 ---------------------------
public static long gcd(long a, long b) {
if (a == 0) return b;
if (b == 0) return a;
return gcd(b, a % b);
}
public static int gcd(int a, int b) {
if (a == 0) return b;
if (b == 0) return a;
return gcd(b, a % b);
}
public static long pow(long a, long b, long mod) {
long res = 1;
while (b > 0) {
if ((b & 1) == 1) res = (res * a) % mod;
a = (a * a) % mod;
b >>= 1;
}
return res;
}
//
static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
static Input input = new Input(System.in);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static class Input {
public BufferedReader reader;
public StringTokenizer tokenizer;
public Input(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}