結果

問題 No.439 チワワのなる木
ユーザー 37zigen37zigen
提出日時 2020-04-04 16:59:04
言語 Java21
(openjdk 21)
結果
AC  
実行時間 1,215 ms / 5,000 ms
コード長 1,293 bytes
コンパイル時間 2,297 ms
コンパイル使用メモリ 76,864 KB
実行使用メモリ 102,312 KB
最終ジャッジ日時 2023-09-16 05:56:06
合計ジャッジ時間 16,345 ms
ジャッジサーバーID
(参考情報)
judge11 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 125 ms
55,464 KB
testcase_01 AC 125 ms
55,548 KB
testcase_02 AC 124 ms
55,928 KB
testcase_03 AC 126 ms
55,480 KB
testcase_04 AC 128 ms
55,864 KB
testcase_05 AC 125 ms
55,620 KB
testcase_06 AC 126 ms
55,568 KB
testcase_07 AC 125 ms
55,628 KB
testcase_08 AC 133 ms
55,292 KB
testcase_09 AC 135 ms
56,012 KB
testcase_10 AC 142 ms
55,664 KB
testcase_11 AC 126 ms
55,812 KB
testcase_12 AC 132 ms
55,644 KB
testcase_13 AC 179 ms
55,808 KB
testcase_14 AC 188 ms
56,140 KB
testcase_15 AC 203 ms
60,888 KB
testcase_16 AC 213 ms
59,000 KB
testcase_17 AC 205 ms
58,760 KB
testcase_18 AC 1,003 ms
71,616 KB
testcase_19 AC 919 ms
72,844 KB
testcase_20 AC 1,109 ms
80,292 KB
testcase_21 AC 546 ms
64,928 KB
testcase_22 AC 516 ms
63,092 KB
testcase_23 AC 1,215 ms
86,380 KB
testcase_24 AC 1,195 ms
100,120 KB
testcase_25 AC 1,069 ms
82,496 KB
testcase_26 AC 1,046 ms
80,656 KB
testcase_27 AC 913 ms
102,312 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		long curtime=System.currentTimeMillis();
		new Main().run();
		System.err.println(System.currentTimeMillis()-curtime);
	}
	
	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);
	}
	
	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));}
}

0