結果
| 問題 |
No.1002 Twotone
|
| コンテスト | |
| ユーザー |
TAISA_
|
| 提出日時 | 2020-03-01 21:20:45 |
| 言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 1,151 ms / 5,000 ms |
| コード長 | 2,769 bytes |
| コンパイル時間 | 2,010 ms |
| コンパイル使用メモリ | 192,208 KB |
| 実行使用メモリ | 65,592 KB |
| 最終ジャッジ日時 | 2024-10-13 20:52:54 |
| 合計ジャッジ時間 | 12,241 ms |
|
ジャッジサーバーID (参考情報) |
judge4 / judge3 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 2 |
| other | AC * 33 |
ソースコード
#include <bits/stdc++.h>
#define all(vec) vec.begin(), vec.end()
#define eb emplace_back
using namespace std;
using ll = long long;
using P = pair<ll, ll>;
constexpr ll INF = (1LL << 30) - 1LL;
constexpr ll LINF = (1LL << 60) - 1LL;
constexpr ll MOD = 1e9 + 7;
template <typename T> void chmin(T &a, T b) { a = min(a, b); }
template <typename T> void chmax(T &a, T b) { a = max(a, b); }
int n, k;
vector<vector<P>> G;
vector<int> vis, sz;
ll res;
void szd(int i, int p) {
sz[i] = 1;
for (auto &e : G[i]) {
if (e.first == p || vis[e.first]) {
continue;
}
szd(e.first, i);
sz[i] += sz[e.first];
}
}
int findc(int i, int p, int lim) {
for (auto &e : G[i]) {
if (e.first == p || vis[e.first]) {
continue;
}
if (sz[e.first] >= lim) {
return findc(e.first, i, lim);
}
}
return i;
}
void dfs(int i, int p, int a, int b, map<P, ll> &mp) {
if (a < b) {
swap(a, b);
}
mp[P(a, b)]++;
for (auto &e : G[i]) {
if (e.first == p || vis[e.first]) {
continue;
}
if (a == e.second || b == e.second) {
dfs(e.first, i, a, b, mp);
} else if (b == -1) {
dfs(e.first, i, a, e.second, mp);
}
}
}
void calc(int v) {
szd(v, -1);
int c = findc(v, -1, sz[v] / 2);
map<P, ll> mp;
map<ll, ll> cnt, m1;
ll sum = 0;
for (auto &e : G[c]) {
if (vis[e.first]) {
continue;
}
map<P, ll> mpn;
dfs(e.first, c, e.second, -1, mpn);
for (auto p : mpn) {
if (p.first.second == -1) {
res +=
(cnt[p.first.first] + sum - m1[p.first.first]) * p.second;
} else {
res += (mp[p.first] + m1[p.first.first] + m1[p.first.second]) *
p.second;
}
}
for (auto p : mpn) {
if (p.first.second == -1) {
m1[p.first.first] += p.second;
sum += p.second;
} else {
res += p.second;
cnt[p.first.first] += p.second;
cnt[p.first.second] += p.second;
mp[p.first] += p.second;
}
}
}
vis[c] = 1;
for (auto &e : G[c]) {
if (vis[e.first]) {
continue;
}
calc(e.first);
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n >> k;
G.resize(n);
vis.resize(n);
sz.resize(n);
for (int i = 0; i < n - 1; i++) {
int a, b, c;
cin >> a >> b >> c;
--a;
--b;
--c;
G[a].eb(b, c);
G[b].eb(a, c);
}
calc(0);
cout << res << '\n';
}
TAISA_