結果

問題 No.439 チワワのなる木
ユーザー femtofemto
提出日時 2016-10-28 23:12:32
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 49 ms / 5,000 ms
コード長 924 bytes
コンパイル時間 1,304 ms
コンパイル使用メモリ 167,740 KB
実行使用メモリ 16,800 KB
最終ジャッジ日時 2023-08-15 21:34:35
合計ジャッジ時間 2,874 ms
ジャッジサーバーID
(参考情報)
judge15 / judge11
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 3 ms
5,704 KB
testcase_01 AC 3 ms
5,684 KB
testcase_02 AC 2 ms
5,920 KB
testcase_03 AC 3 ms
5,656 KB
testcase_04 AC 3 ms
5,764 KB
testcase_05 AC 3 ms
5,696 KB
testcase_06 AC 3 ms
5,832 KB
testcase_07 AC 3 ms
5,716 KB
testcase_08 AC 3 ms
5,664 KB
testcase_09 AC 3 ms
5,772 KB
testcase_10 AC 3 ms
5,828 KB
testcase_11 AC 3 ms
5,844 KB
testcase_12 AC 3 ms
5,864 KB
testcase_13 AC 3 ms
5,712 KB
testcase_14 AC 3 ms
5,884 KB
testcase_15 AC 3 ms
5,772 KB
testcase_16 AC 4 ms
5,760 KB
testcase_17 AC 4 ms
5,720 KB
testcase_18 AC 32 ms
9,232 KB
testcase_19 AC 29 ms
9,276 KB
testcase_20 AC 41 ms
10,168 KB
testcase_21 AC 12 ms
7,304 KB
testcase_22 AC 13 ms
7,152 KB
testcase_23 AC 45 ms
11,380 KB
testcase_24 AC 49 ms
15,668 KB
testcase_25 AC 29 ms
10,176 KB
testcase_26 AC 31 ms
10,708 KB
testcase_27 AC 33 ms
16,800 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

int N;
ll ans;
ll C[100000];
ll W[100000];
vector<int> G[100000];
string S;

void dfs1(int n, int p) {
	if(S[n] == 'c') C[n]++;
	else W[n]++;
	for(auto c : G[n]) {
		if(c == p) continue;
		dfs1(c, n);
		C[n] += C[c];
		W[n] += W[c];
	}
}

void dfs2(int n, int p) {
	if(S[n] == 'w') {
		ll csum = C[0], wsum = W[0];
		for(auto c : G[n]) {
			ll cn = 0, wn = 0;
			if(c == p) {
				cn = csum - C[n];
				wn = wsum - W[n];
			}
			else {
				cn = C[c];
				wn = W[c];
			}
			ans += cn * (wsum - 1 - wn);
			//ans += wn * (csum - cn);
		}
	}
	for(auto c : G[n]) {
		if(c == p) continue;
		dfs2(c, n);
	}
}

int main() {
	cin.tie(0);
	ios::sync_with_stdio(false);

	cin >> N;
	cin >> S;
	for(int i = 0; i < N - 1; i++) {
		int a, b;
		cin >> a >> b;
		a--, b--;
		G[a].push_back(b);
		G[b].push_back(a);
	}
	dfs1(0, -1);
	dfs2(0, -1);

	cout << ans << endl;
}
0