其他分享
首页 > 其他分享> > CodeForces - 960E Alternating Tree

CodeForces - 960E Alternating Tree

作者:互联网

题意:

给定一棵有 nnn 个结点的树,边权均为 111,结点带点权 ViV_iVi​,一条路径 (v1,v2,...,vm)(v_1,v_2,...,v_m)(v1​,v2​,...,vm​) 的权值定义为 i=1m(1)(i+1)Vvi\sum\limits_{i = 1}^{m}(-1)^{(i + 1)}V_{v_i}i=1∑m​(−1)(i+1)Vvi​​,求所有路径权值总和。(n2×105)(n \leq 2 × 10^5)(n≤2×105)

链接:

https://codeforces.com/problemset/problem/960/E

解题思路:

路径问题,可以考虑点分求解,易知偶数长路径的权值为 000,则只需要统计奇数长度的路径,故分奇偶讨论路径的合并即可。我们发现这个奇偶路径信息还是很容易转移的 (这次不写点分),故树形 dpdpdp 即可。注意取模,点权可能为负,注意取模!

参考代码:

#include<bits/stdc++.h>
 
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
#define sz(a) ((int)a.size())
#define pb push_back
#define lson (rt << 1)
#define rson (rt << 1 | 1)
#define gmid (l + r >> 1)
const int maxn = 2e5 + 5;
const int inf = 0x3f3f3f3f;
const int mod = 1e9 + 7;
 
vector<int> G[maxn];
ll dis[maxn][2], ans;
int a[maxn], siz[maxn][2];
int n;

void dfs(int u, int f){

    siz[u][1] = 1, dis[u][1] = (a[u] % mod + mod) % mod;
    for(auto &v : G[u]){

        if(v == f) continue;
        dfs(v, u);
        ans += dis[u][0] * siz[v][1] + dis[v][1] * siz[u][0];
        ans += dis[u][1] * siz[v][0] + dis[v][0] * siz[u][1]; ans %= mod;
        siz[u][0] += siz[v][1], siz[u][1] += siz[v][0];
        dis[u][0] += dis[v][1] - a[u] * 1ll * siz[v][1], dis[u][0] = (dis[u][0] % mod + mod) % mod;
        dis[u][1] += dis[v][0] + a[u] * 1ll * siz[v][0], dis[u][1] = (dis[u][1] % mod + mod) % mod;
    }
}

int main(){
 
    ios::sync_with_stdio(0); cin.tie(0);
    cin >> n;
    for(int i = 1; i <= n; ++i) cin >> a[i];
    for(int i = 1; i < n; ++i){

        int u, v; cin >> u >> v;
        G[u].pb(v), G[v].pb(u);
    }
    dfs(1, 0);
    // cout << ans << endl;
    // for(int i = 1; i <= n; ++i) cout << i << " " << siz[i][0] << " "<< siz[i][1] << " " << dis[i][0] << " " << dis[i][1] << endl;
    ans <<= 1;
    for(int i = 1; i <= n; ++i) ans += a[i];
    ans = (ans % mod + mod) % mod;
    cout << ans << endl;
    return 0;
}
freeze up 发布了56 篇原创文章 · 获赞 0 · 访问量 1494 私信 关注

标签:Alternating,int,siz,路径,Tree,960E,maxn,mod,dis
来源: https://blog.csdn.net/weixin_44059127/article/details/104098526