洛谷 P2664 树上游戏

博主分享了树上差分的80分代码,却找不到代码错误所在。涉及树上差分相关信息技术内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <bits/stdc++.h>
using namespace std;
typedef long long lint;
typedef long long LL;
const lint maxn = 200000 + 5;
const lint maxm = 400000 + 5;
const lint inf = 0x3f3f3f3f3f;
lint vis[maxn],g[maxn],sz[maxn],root,sum,c[maxn];
vector<lint> ve[maxn];
void add_edge( lint x,lint y ){
    ve[x].push_back(y);
}
lint sz_sum,color_cnt,pre_color_sum,color[maxn],in_st[maxn],ans[maxn];
void dfs_cnt( lint x,lint f,lint flag ){
    sz[x]=1;
    if( !in_st[c[x] ] ){
        color_cnt++;
        pre_color_sum -= color[ c[x] ];
    }
    in_st[ c[x] ]++;
    if( !in_st[c[root] ] )
    ans[x] += pre_color_sum-color[ c[root] ] + (color_cnt+1) *( sz_sum+flag );
    else ans[x] += pre_color_sum + color_cnt * (sz_sum+flag );
    for( lint i = 0;i < ve[x].size();i++ ){
        lint y = ve[x][i];
        if( vis[y] || y==f ) continue;
        dfs_cnt( y,x,flag );
        sz[x] +=sz[y];
    }
    in_st[ c[x] ]--;
    if(!in_st[ c[x] ] ){
        color_cnt--;
        pre_color_sum += color[ c[x] ];
    }
}
void dfs_init( lint x,lint f ){
    if(!in_st[c[x]] ){
        color[ c[x] ] += sz[x];
        pre_color_sum += sz[x];
    }
    in_st[ c[x] ]++;
    for( lint i = 0;i < ve[x].size();i++ ){
        lint y = ve[x][i];
        if( y == f || vis[y] ) continue;
        dfs_init(y,x);
    }
    in_st[c[x]]--;
}
void dfs_init2( lint x,lint f ){
    color[c[x] ]=0;
    for( lint i = 0;i < ve[x].size();i++ ){
        lint y = ve[x][i];
        if( vis[y] || y == f ) continue;
        dfs_init2(y,x);
    }
}
void get_root(lint x,lint f)
{
    sz[x]=1;g[x]=0;
    for(int i = 0; i < ve[x].size() ;i++){
        lint y = ve[x][i];
        if( vis[y] || y == f ) continue;
        get_root(y,x);
        g[x]=max(g[x],sz[y]);
        sz[x]+=sz[y];
    }
    g[x]=max(g[x],sum-sz[x]);
    if(g[x]<g[root])root=x;
}
void dfs_div( lint x ){
    vis[x] = 1;
    sz_sum = 0;
    sz[x]=1;
    pre_color_sum=0;
    for( lint i = 0;i < ve[x].size();i++ ){
        lint  y = ve[x][i];
        if(vis[y]) continue;
        dfs_cnt(y,x,1);
        sz[x]+=sz[y];
        dfs_init( y,x );
        sz_sum += sz[y];
    }
    ans[x] += pre_color_sum +sz[x]-1 -color[ c[x] ] ;
    sz_sum = 0;
    pre_color_sum=0;
    dfs_init2(x,0);
    for( lint i =ve[x].size()-1;i >= 0;i-- ){
        lint  y= ve[x][i];
        if(vis[y]) continue;
        dfs_cnt(y,x,0);
        dfs_init(y,x);
        sz_sum += sz[y];
    }
    dfs_init2(x,0);
    for( lint i = 0; i < ve[x].size() ;i++ ){
        lint y = ve[x][i];
        if( vis[y] ) continue;
        root = 0;sum = sz[y];
        get_root( y,x );
        dfs_div( root );
    }
}
int main() {
    lint n;
    scanf("%lld",&n);
    for( lint i = 1;i <= n;i++ ) scanf("%lld",&c[i]);
    for( lint x,y,i = 1;i <= n-1;i++ ){
        scanf("%lld%lld",&x,&y);
        add_edge(x,y);add_edge(y,x);
    }
    g[0]=n;sum = n;
    get_root(1,0);
    dfs_div(root);
    for( lint i = 1;i <= n;i++ ){
        printf("%lld\n",ans[i]+1);
    }
    return 0;
}

 这是树上差分的80分代码,实在看不出来哪错了QAQ

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef LL lint;
const lint maxn = 1000005;
const lint maxm = 2000005;
lint color[maxn],c[maxn];
lint he[maxn],ver[maxm],ne[maxm],tot,val[maxn],n;
void init(){
    tot = 1;
}
void add( lint x,lint y ){
    ver[++tot] = y;
    ne[tot] = he[x];
    he[x]=tot;
};
lint sz[maxn];
void dfs( lint x,lint f ){
    sz[x]=1;
    for( lint cure = he[x];cure;cure = ne[cure] ){
        lint y = ver[cure];
        if( y == f ) continue;
        lint pre = color[ c[x] ];
        dfs(y,x);
        sz[x] += sz[y];
        val[y] = sz[y]  - (color[ c[x] ] - pre);
        color[ c[x] ] += sz[y] - ( color[ c[x] ]-pre ) ;
    }
    color[ c[x] ]++;
}
lint color_val[maxn],v[maxn];
void dfs_pre( lint x,lint f ){
    v[x] += val[x];
    v[x] -= color_val[ c[x] ];
    lint pre = color_val[ c[f] ];
    color_val[ c[f] ] = val[x];
    for( lint cure = he[x];cure;cure = ne[cure] ){
        lint y = ver[cure];
        if( y == f ) continue;
        dfs_pre(y,x);
    }
    color_val[ c[f] ] = pre;
}
lint cur = 0;
lint res[maxn];
void dfs_cal( lint x,lint f ){
    lint pre = cur;
    cur += v[x];
    res[x]=cur;
    for( lint cure = he[x];cure;cure = ne[cure] ){
        lint y = ver[cure];
        if( y == f ) continue;
        dfs_cal(y,x);
    }
    cur = pre;
}
lint in_st[maxn],vis[maxn];
void dfs_pre2( lint x,lint f ){
    if( !in_st[ c[x] ] ){
        v[ x ] -= n-color[ c[x] ];
    }
    in_st[ c[x] ]++;
    for( lint cure = he[x];cure;cure = ne[cure] ){
        lint y = ver[cure];
        if( y == f ) continue;
        dfs_pre2(y,x);
    }
    in_st[ c[x] ]--;
}
int main(){
    lint color_cnt = 0;
    scanf("%lld",&n);
    init();
    for( lint i = 1;i <= n;i++ ) {
        scanf("%lld",&c[i]);
        if( !vis[ c[i] ] ){
            color_cnt++;
            vis[ c[i] ]=1;
        }
    }
    for( lint x,y,i = 1;i <=n-1;i++ ){
        scanf("%lld%lld",&x,&y);
        add(x,y);add(y,x);
    }
    dfs(1,0);
    in_st[ c[1] ] = 1;
    for( lint i = 1;i < maxn;i++ ) {
        if( vis[i] )
            cur += n-color[i];
    }
    dfs_pre2( 1,0 );
    dfs_pre(1,0);
    dfs_cal( 1,0 );
    for( lint i = 1;i <= n;i++ ){
        printf("%lld\n", n*color_cnt-res[i] );
    }
    return 0;
}

 

### 关于 P1481 的字典树 (Trie) 算法 #### 字典树 (Trie) 数据结构简介 字典树是一种用于高效存储和检索字符串集合的数据结构。它通过将公共前缀共享的方式来节省空间并提高查询效率。对于本题而言,字典树的核心思想在于构建一棵多叉树来表示一组单词的字符序列[^5]。 #### 构建字典树的过程 在字典树中,每个节点代表一个字符,而从根到某个节点的路径则构成了一部分字符串。以下是构建字典树的主要过程: 1. **初始化**: 创建一个根节点 `root`。 2. **插入操作**: 将每一个单词逐字符插入字典树中。如果当前字符不存在,则创建新的子节点;否则沿已有路径继续向下遍历直到完成整个单词的插入。 ```python class TrieNode: def __init__(self): self.children = {} self.is_end_of_word = False def insert(root, word): node = root for char in word: if char not in node.children: node.children[char] = TrieNode() node = node.children[char] node.is_end_of_word = True ``` #### 查询操作 为了判断某字符串是否存在或者统计某些特定条件下的匹配数量,可以通过递归或迭代的方式访问字典树中的相应节点。例如,在此题目背景下可能需要计算满足一定约束条件下能够组成的合法串数。 #### 动态规划与状态转移方程 由于题目涉及到构造固定长度且包含指定数目关键词汇表内的任意组合形式的新字符串问题,因此除了单纯依靠字典树外还需要引入动态规划的思想来进行求解。设 dp[i][j] 表示已经处理到了第 i 位,并且此时正好包含了 j 个目标词汇的情况总数,则有如下关系式成立: \[dp[i][j]=\sum_{w \in S} dp[i-len(w)][max(0,j-cnt[w])]\] 其中 \(S\) 是所有候选单词集,\(len(w)\) 和 \(cnt[w]\) 分别对应着单个词语本身的尺寸以及其贡献给最终计数值的部分大小[^4]。 #### 完整解决方案框架 综合以上分析我们可以给出这样一个完整的解决流程概述: - 初始化必要的辅助数组如 trie 结构体实例化对象; - 根据输入数据依次调用上述定义好的函数完成各项预处理工作比如建立索引映射关系等准备工作; - 使用双重循环枚举位置变量i及其关联参数k从而填充DP表格直至得出最后答案为止。 ```python MOD = int(1e9 + 7) trie_root = TrieNode() for word in words_set: insert(trie_root, word) # Initialize DP table with dimensions [N+1][K+1], where N is max length of string to be formed, # K represents number of distinct required substrings. dp = [[0]*(k_max+1) for _ in range(n_max+1)] dp[0][0] = 1 for l in range(1, n_max+1): for c in alphabet: current_node = trie_root temp_dp = list(dp[l]) # Traverse through possible prefixes ending at position 'l' prefix_length = 0 while current_node and prefix_length <= l: new_k = min(k_max, k_found[current_node]) if new_k >=0 : temp_dp[new_k]=(temp_dp[new_k]+dp[l-prefix_length][new_k-count(current_node)])% MOD if c in current_node.children: current_node=current_node.children[c] prefix_length+=1 else: break dp[l]=temp_dp[:] result=sum([d[k_target]%MOD for d in dp[n]]) print(result) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值