結果

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

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 125 ms
57,256 KB
testcase_01 AC 124 ms
57,924 KB
testcase_02 AC 124 ms
57,288 KB
testcase_03 AC 125 ms
57,864 KB
testcase_04 AC 123 ms
57,472 KB
testcase_05 AC 124 ms
55,164 KB
testcase_06 AC 122 ms
57,220 KB
testcase_07 AC 122 ms
57,068 KB
testcase_08 AC 129 ms
57,500 KB
testcase_09 AC 131 ms
57,348 KB
testcase_10 AC 138 ms
57,500 KB
testcase_11 AC 124 ms
57,012 KB
testcase_12 AC 133 ms
57,544 KB
testcase_13 AC 200 ms
59,132 KB
testcase_14 AC 200 ms
59,352 KB
testcase_15 AC 213 ms
60,620 KB
testcase_16 AC 222 ms
61,324 KB
testcase_17 AC 220 ms
60,880 KB
testcase_18 AC 935 ms
76,080 KB
testcase_19 AC 982 ms
74,556 KB
testcase_20 AC 1,118 ms
82,508 KB
testcase_21 AC 523 ms
65,652 KB
testcase_22 AC 484 ms
65,216 KB
testcase_23 AC 1,199 ms
86,856 KB
testcase_24 AC 1,211 ms
99,440 KB
testcase_25 AC 1,036 ms
83,588 KB
testcase_26 AC 998 ms
81,840 KB
testcase_27 AC 884 ms
102,156 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

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));}
}

0