結果
問題 | No.439 チワワのなる木 |
ユーザー |
![]() |
提出日時 | 2016-04-28 22:18:35 |
言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 78 ms / 5,000 ms |
コード長 | 2,186 bytes |
コンパイル時間 | 970 ms |
コンパイル使用メモリ | 108,840 KB |
実行使用メモリ | 19,584 KB |
最終ジャッジ日時 | 2024-10-11 00:14:19 |
合計ジャッジ時間 | 2,573 ms |
ジャッジサーバーID (参考情報) |
judge4 / judge3 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
other | AC * 28 |
ソースコード
#include<cstdio>#include<cstdlib>#include<cstring>#include<cmath>//#include<cctype>#include<climits>#include<iostream>#include<string>#include<vector>#include<map>//#include<list>#include<queue>#include<deque>#include<algorithm>//#include<numeric>#include<utility>#include<complex>//#include<memory>#include<functional>#include<cassert>#include<set>#include<stack>#include<random>const int dx[] = {1, 0, -1, 0};const int dy[] = {0, 1, 0, -1};using namespace std;typedef long long ll;typedef unsigned long long ull;typedef vector<int> vi;typedef vector<ll> vll;typedef pair<int, int> pii;typedef pair<ll, ll> pll;const int MAXN = 100010;int N;string s;vector<vi> G;pll P[MAXN];// v 以下の部分木にある (ww, w) を求めるpll dfs(int v, int p) {pll& ret = P[v];if (s[v] == 'w') ret.second++;for (int ch : G[v]) if (ch != p) {pll tmp = dfs(ch, v);ret.first += tmp.first;ret.second += tmp.second;if (s[v] == 'w') ret.first += tmp.second;}return ret;}ll ans;void dfs2(int v, int par, pll p) {if (s[v] == 'c') {// c -> par 側if (s[v] ) ans += p.first;// c -> 子for (int ch : G[v]) if (ch != par) {ans += P[ch].first;}}// 子に移動for (int ch : G[v]) if (ch != par) {pll tmp = p;tmp.first += P[v].first, tmp.second += P[v].second;tmp.first -= P[ch].first, tmp.second -= P[ch].second;if (s[v] == 'w') {tmp.first -= P[ch].second;tmp.first += p.second;}dfs2(ch, v, tmp);}}int main() {cin.tie(0);ios::sync_with_stdio(false);cin >> N;cin >> s;for (int i = 0; i < N; i++) assert(s[i] == 'c' || s[i] == 'w');G.resize(N);for (int i = 0; i < N-1; i++) {int a, b;cin >> a >> b;a--; b--;G[a].emplace_back(b);G[b].emplace_back(a);}dfs(0, -1);// for (int i = 0; i < N; i++) {// cout << i << " " << P[i].first << " " << P[i].second << endl;// }dfs2(0, -1, pll());cout << ans << endl;return 0;}