結果

問題 No.439 チワワのなる木
ユーザー pekempey
提出日時 2016-10-28 23:57:04
言語 C++11(廃止可能性あり)
(gcc 13.3.0)
結果
AC  
実行時間 79 ms / 5,000 ms
コード長 968 bytes
コンパイル時間 1,595 ms
コンパイル使用メモリ 161,108 KB
実行使用メモリ 19,968 KB
最終ジャッジ日時 2024-11-24 06:43:39
合計ジャッジ時間 2,813 ms
ジャッジサーバーID
(参考情報)
judge2 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 28
権限があれば一括ダウンロードができます
コンパイルメッセージ
main.cpp: In function ‘int main()’:
main.cpp:49:22: warning: ignoring return value of ‘int scanf(const char*, ...)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
   49 |                 scanf("%d %d", &u, &v);
      |                 ~~~~~^~~~~~~~~~~~~~~~~

ソースコード

diff #

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

const int N = 1e5;

int n;
string s;

vector<int> g[N];
long long sub_c[N];
long long sub_w[N];
long long sub_ww[N];
long long sub_wc[N];
long long ans;

void dfs(int u, int p) {
	for (int v : g[u]) if (v != p) {
		dfs(v, u);
		sub_c[u] += sub_c[v];
		sub_w[u] += sub_w[v];
		sub_ww[u] += sub_ww[v];
		sub_wc[u] += sub_wc[v];
		if (s[u] == 'c') {
			ans += sub_ww[v];
		} else {
			sub_wc[u] += sub_c[v];
			sub_ww[u] += sub_w[v];
			ans -= sub_c[v] * sub_w[v];
			ans += sub_wc[v];
		}
	}
	if (s[u] == 'w') ans += sub_c[u] * sub_w[u];
	for (int v : g[u]) if (v != p) {
		ans += sub_wc[v] * (sub_w[u] - sub_w[v]);
		ans += sub_ww[v] * (sub_c[u] - sub_c[v]);
	}

	if (s[u] == 'c') {
		sub_c[u]++;
	} else {
		sub_w[u]++;
	}
}

int main() {
	cin >> n >> s;
	for (int i = 0; i < n - 1; i++) {
		int u, v;
		scanf("%d %d", &u, &v);
		u--; v--;
		g[u].push_back(v);
		g[v].push_back(u);
	}
	dfs(0, -1);
	cout << ans << endl;
}
0