結果
| 問題 |
No.439 チワワのなる木
|
| ユーザー |
|
| 提出日時 | 2020-04-04 17:07:58 |
| 言語 | Java (openjdk 23) |
| 結果 |
AC
|
| 実行時間 | 1,292 ms / 5,000 ms |
| コード長 | 1,275 bytes |
| コンパイル時間 | 2,691 ms |
| コンパイル使用メモリ | 79,536 KB |
| 実行使用メモリ | 91,696 KB |
| 最終ジャッジ日時 | 2024-07-03 07:32:38 |
| 合計ジャッジ時間 | 16,834 ms |
|
ジャッジサーバーID (参考情報) |
judge1 / judge5 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 28 |
ソースコード
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Main implements Runnable{
public static void main(String[] args) {
new Thread(null,new Main(), "" ,Runtime.getRuntime().maxMemory()).start();
}
long ans=0;
int totW=0,totC=0;
void dfs(int cur,int par,ArrayList<Integer>[] g,int[] c,int[] w,char[] cs) {
if(cs[cur]=='c')++c[cur];
else ++w[cur];
for(int dst:g[cur]) {
if(dst==par)continue;
dfs(dst,cur,g,c,w,cs);
c[cur]+=c[dst];
w[cur]+=w[dst];
}
if(cs[cur]=='w') {
for(int dst:g[cur]) {
if(dst==par)continue;
ans+=(long)c[dst]*(totW-w[dst]-1);
}
}
if(cs[cur]=='w')ans+=(long)(totC-c[cur])*(w[cur]-1);
}
public void run() {
Scanner sc=new Scanner(System.in);
int N=sc.nextInt();//3<=N<=1e5
char[] cs=sc.next().toCharArray();
ArrayList<Integer>[] g=new ArrayList[N];
for(int i=0;i<g.length;++i)g[i]=new ArrayList<>();
for(int i=0;i<N-1;++i) {
int a=sc.nextInt();
int b=sc.nextInt();
--a;--b;
g[a].add(b);
g[b].add(a);
}
int[] c=new int[N];
int[] w=new int[N];
for(char ch:cs)if(ch=='c')++totC; else ++totW;;
dfs(0,-1,g,c,w,cs);
System.out.println(ans);
}
void tr(Object...objects) {System.out.println(Arrays.deepToString(objects));}
}