牛客 216 C 小K的疑惑
生活随笔
收集整理的這篇文章主要介紹了
牛客 216 C 小K的疑惑
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
大意: 給定樹, 求多少個三元組(i,j,k), 滿足dis(i,j)=dis(j,k)=dis(k,i).
?
剛開始想復(fù)雜了, 暴力統(tǒng)計了所有的情況.
#include <iostream> #include <queue> #include <cstdio> #define REP(i,a,n) for(int i=a;i<=n;++i) using namespace std; typedef long long ll;const int N = 1e4+10; int n, dep[N]; struct _ {int to,w;}; vector<_> g[N]; int dp[N][2]; ll ans;void dfs(int x, int fa, int d) {dep[x] = d, ++ans;ll c00 = 0, c11 = 0;for (_ e:g[x]) if (e.to!=fa) {int y = e.to;dfs(y,x,d+e.w&1);ans += 6ll*c00*dp[y][0];ans += 6ll*c11*dp[y][1];ans += 6*dp[y][dep[x]];ans += 12ll*dp[x][dep[x]]*dp[y][dep[x]];ans += 6ll*dp[y][dep[x]]*(dp[y][dep[x]]-1)/2;ans += 6ll*dp[x][!dep[x]]*dp[y][!dep[x]];c00 += (ll)dp[y][0]*dp[x][0];c11 += (ll)dp[y][1]*dp[x][1];dp[x][0] += dp[y][0];dp[x][1] += dp[y][1];}for (_ e:g[x]) if (e.to!=fa) {int y = e.to;ans += 6ll*dp[y][0]*(dp[y][0]-1)/2*(dp[x][0]-dp[y][0]);ans += 6ll*dp[y][1]*(dp[y][1]-1)/2*(dp[x][1]-dp[y][1]);}++dp[x][dep[x]]; }int main() {scanf("%d", &n);REP(i,2,n) {int u, v, w;scanf("%d%d%d", &u, &v, &w);g[u].push_back({v,w});g[v].push_back({u,w});}dfs(1,0,0);printf("%lld\n", ans); }?
?
實際上可以發(fā)現(xiàn)所有路徑都滿足 奇奇奇 或 偶偶偶.
#include <iostream> #include <queue> #include <cstdio> #define REP(i,a,n) for(int i=a;i<=n;++i) using namespace std; typedef long long ll;const int N = 1e4+10; int n, dep[N]; struct _ {int to,w;}; vector<_> g[N]; int dp[N][2], ans[2];void dfs(int x, int fa, int d) {++ans[d];for (_ e:g[x]) if (e.to!=fa) {int y = e.to;dfs(y,x,d+e.w&1);} }int main() {scanf("%d", &n);REP(i,2,n) {int u, v, w;scanf("%d%d%d", &u, &v, &w);g[u].push_back({v,w});g[v].push_back({u,w});}dfs(1,0,0);printf("%lld\n",(ll)ans[0]*ans[0]*ans[0]+(ll)ans[1]*ans[1]*ans[1]); }?
轉(zhuǎn)載于:https://www.cnblogs.com/uid001/p/10985385.html
總結(jié)
以上是生活随笔為你收集整理的牛客 216 C 小K的疑惑的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 小程序云开发使用where查询遇到的问题
- 下一篇: pip 批量安装包