結果
| 問題 |
No.439 チワワのなる木
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2016-10-28 23:44:45 |
| 言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 104 ms / 5,000 ms |
| コード長 | 1,930 bytes |
| コンパイル時間 | 1,451 ms |
| コンパイル使用メモリ | 112,644 KB |
| 実行使用メモリ | 11,008 KB |
| 最終ジャッジ日時 | 2024-11-24 06:34:22 |
| 合計ジャッジ時間 | 2,803 ms |
|
ジャッジサーバーID (参考情報) |
judge2 / judge4 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 28 |
ソースコード
#define _USE_MATH_DEFINES
#include <cstdio>
#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <complex>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <bitset>
#include <numeric>
#include <limits>
#include <climits>
#include <cfloat>
#include <functional>
#include <iterator>
using namespace std;
int main()
{
int n;
string s;
cin >> n >> s;
vector<vector<int> > edges(n);
for(int i=0; i<n-1; ++i){
int a, b;
cin >> a >> b;
-- a;
-- b;
edges[a].push_back(b);
edges[b].push_back(a);
}
queue<pair<int, int> > q;
stack<pair<int, int> > stk;
q.push(make_pair(0, -1));
while(!q.empty()){
pair<int, int> p = q.front();
q.pop();
stk.push(p);
int curr = p.first;
int prev = p.second;
for(int next : edges[curr]){
if(next != prev)
q.push(make_pair(next, curr));
}
}
int cSum = count(s.begin(), s.end(), 'c');
int wSum = n - cSum;
vector<int> cCnt(n, 0), wCnt(n, 0);
long long ans = 0;
while(!stk.empty()){
pair<int, int> p = stk.top();
stk.pop();
int curr = p.first;
int parent = p.second;
for(int child : edges[curr]){
if(child != parent){
cCnt[curr] += cCnt[child];
wCnt[curr] += wCnt[child];
}
}
if(s[curr] == 'c'){
++ cCnt[curr];
continue;
}
++ wCnt[curr];
ans += (wCnt[curr] - 1LL) * (cSum - cCnt[curr]);
for(int child : edges[curr]){
if(child != parent){
ans += cCnt[child] * (wSum - wCnt[child] - 1LL);
}
}
}
cout << ans << endl;
return 0;
}