日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

牛客 contest897 C-Latale(树上dp)

發布時間:2024/4/18 编程问答 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 牛客 contest897 C-Latale(树上dp) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題意

N個節點的樹,每條邊有條權值,問有多少個點對(U,V)(U, V)(U,V),使得UUUVVV的距離是3的倍數。

思路

  • dfs1dfs1dfs1處理每個節點包含子樹的dis[dis[%3 = 0],dis[%3 = 1],dis[%3 = 2]dis[的個數。
  • dfs2dfs2dfs2枚舉每個節點作為根節點的情況。

牛客OJ好像有問題。一樣的代碼:

#include <bits/stdc++.h> #define LL long long #define P pair<int, int> #define lowbit(x) (x & -x) #define mem(a, b) memset(a, b, sizeof(a)) #define mid ((l + r) >> 1) #define lc rt<<1 #define rc rt<<1|1 #define endl '\n' const int maxn = 1e5 + 5; const int inf = 0x3f3f3f3f; const int mod = 1e9 + 7; using namespace std; vector<P> g[maxn]; int dp[maxn][3]; LL ans; void dfs1(int u, int fa) {mem(dp[u], 0);dp[u][0] = 1;for (auto it : g[u]) {int v = it.first;int w = it.second;if (v == fa) continue;dfs1(v, u);dp[u][0] += dp[v][(3 - w) % 3];dp[u][1] += dp[v][(4 - w) % 3];dp[u][2] += dp[v][(5 - w) % 3];} } void dfs2(int u, int fa, int sum0, int sum1, int sum2) {ans += sum0 - 1;for (auto it : g[u]) {int v = it.first;int w = it.second;if (v == fa) continue;int other[3];other[0] = sum0 - dp[v][(3-w)%3];other[1] = sum1 - dp[v][(4-w)%3];other[2] = sum2 - dp[v][(5-w)%3];dfs2(v, u, other[(3-w)%3]+dp[v][0], other[(4-w)%3]+dp[v][1], other[(5-w)%3]+dp[v][2]);} }int main () {ios::sync_with_stdio(0);cin.tie(0), cout.tie(0);int T;cin >> T;while (T--) {int n;cin >> n;for (int i = 0; i <= n; ++i) {g[i].clear();}for (int i = 1, u,v,w; i < n; ++i) {cin >> u >> v >> w;g[u].push_back(make_pair(v, w%3));g[v].push_back(make_pair(u, w%3));}ans = 0;dfs1(1, 0);dfs2(1, 0, dp[1][0], dp[1][1], dp[1][2]);cout << ans / 2 << endl;}return 0; }

總結

以上是生活随笔為你收集整理的牛客 contest897 C-Latale(树上dp)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。