#include #include #include #include #include using namespace std; using Graph = vector< vector< pair > >; int main() { int N, K; scanf("%d%d", &N, &K); Graph G(N); for(int i=0; i+1 vector< pair > { vector< vector< pair > > children; vector< pair > rec; for(auto e : G[cur]) { int to, color; tie(to, color) = e; if(to == par) continue; auto vec = f(f, to, cur); children.emplace_back(); for(auto edge : vec) { if(edge.first == color or edge.second == color) { children.back().emplace_back(edge); rec.emplace_back(edge); if(edge.first != -1 and edge.second != -1) { ans++; } } else if(edge.first == -1) { edge.first = color; if(edge.first > edge.second) swap(edge.first, edge.second); children.back().emplace_back(edge); rec.emplace_back(edge); if(edge.first != -1 and edge.second != -1) { ans++; } } } // cur と to の間のパス { pair short_edge(-1, color); children.back().emplace_back(short_edge); rec.emplace_back(short_edge); } sort(children.back().begin(), children.back().end()); } sort(rec.begin(), rec.end()); for(const auto &v : children) { for(const auto &e : v) { if(e.first != -1 and e.second != -1) { // 完全に一致するもの (2 回数えられる) { auto ub = upper_bound(rec.begin(), rec.end(), e); auto lb = lower_bound(rec.begin(), rec.end(), e); ans_dbl += ub - lb; } { auto ub = upper_bound(v.begin(), v.end(), e); auto lb = lower_bound(v.begin(), v.end(), e); ans_dbl -= ub - lb; } // first だけ { pair one(-1, e.first); { auto ub = upper_bound(rec.begin(), rec.end(), one); auto lb = lower_bound(rec.begin(), rec.end(), one); ans += ub - lb; } { auto ub = upper_bound(v.begin(), v.end(), one); auto lb = lower_bound(v.begin(), v.end(), one); ans -= ub - lb; } } // second だけ { pair one(-1, e.second); { auto ub = upper_bound(rec.begin(), rec.end(), one); auto lb = lower_bound(rec.begin(), rec.end(), one); ans += ub - lb; } { auto ub = upper_bound(v.begin(), v.end(), one); auto lb = lower_bound(v.begin(), v.end(), one); ans -= ub - lb; } } } else { // 一色だけなら、他の一色だけのものと合わせられるかも int c = e.second; { pair p1(-1, 1 << 28); pair p2(-1, -1); auto ub = upper_bound(rec.begin(), rec.end(), p1); auto lb = lower_bound(rec.begin(), rec.end(), p2); ans_dbl += ub - lb; } { pair p1(-1, 1 << 28); pair p2(-1, -1); auto ub = upper_bound(v.begin(), v.end(), p1); auto lb = lower_bound(v.begin(), v.end(), p2); ans_dbl -= ub - lb; } { pair p(-1, c); auto ub = upper_bound(rec.begin(), rec.end(), p); auto lb = lower_bound(rec.begin(), rec.end(), p); ans_dbl -= ub - lb; } { pair p(-1, c); auto ub = upper_bound(v.begin(), v.end(), p); auto lb = lower_bound(v.begin(), v.end(), p); ans_dbl += ub - lb; } } } } return rec; }; dfs(dfs, 0, -1); printf("%lld\n", ans + ans_dbl / 2); return 0; }