HDU 5416 CRB and Tree (树形dp)

本文详细介绍了如何解决HDU 5416问题,该问题涉及到树形DP、边权异或运算以及路径查询。通过树形DP的方法,我们能够高效地计算任意两点间异或路径的个数,并处理询问操作。

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

题目:http://acm.hdu.edu.cn/showproblem.php?pid=5416

题意:给出一棵树和每条边的权值,f(u,v) 表示结点u到结点v之间路径上所有边异或运算的结果,q次询问,每次问f(u,v)=s的路径有多少条,u可以等于v。

代码:

#include <stdio.h>
#include <string.h>
#include <vector>
using namespace std;
typedef long long ll;
int n, cnt[200005], vis[200005];
struct Edge
{
    int to, cost;
}e;
vector<Edge> G[100005];

void dfs(int v, int cur)
{//f(1,v)=cur
    vis[v] = 1;
    for(int i = 0; i < G[v].size(); i++)
    {
        e = G[v][i];
        if(!vis[e.to])
        {
            cnt[cur ^ e.cost]++;
            dfs(e.to, cur ^ e.cost);
        }
    }
}

int main()
{
    int t, a, b, c, q, s;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%d", &n);
        for(int i = 0; i <= n; i++)
            G[i].clear();
        for(int i = 0; i < n - 1; i++)
        {
            scanf("%d%d%d", &a, &b, &c);
            e.to = b; e.cost = c;
            G[a].push_back(e);
            e.to = a;
            G[b].push_back(e);
        }
        memset(cnt, 0, sizeof(cnt)); //cnt[i]记录f(1,u)=i的结点u的个数
        memset(vis, 0, sizeof(vis));
        dfs(1, 0); //树形dp求cnt[]
        scanf("%d", &q);
        while(q--)
        {
            scanf("%d", &s);
            ll ans = 0;
            ans += cnt[s]; //f(1,u)=s的结点u个数(u不等于1)
            memset (vis, 0, sizeof(vis));
            if(s == 0)
            {
                ans += n; //每个结点u都有f(u,u)=0
                for(int i = 0; i <= ((1<<17)-1); i++)
                {
                    if(cnt[i]) //f(1,u)=f(1,v)则f(u,v)=0
                        ans += (ll)cnt[i] * (cnt[i] - 1) / 2;
                }
            }
            else
            {
                for(int i = 0; i <= ((1<<17)-1); i++)
                {//f(1,u)=i,f(1,v)=j则f(u,v)=i^j=s,j=s^i
                    if(!vis[i])
                    {
                        ans += (ll)cnt[i] * cnt[s ^ i];
                        vis[i] = vis[s ^ i] = 1;
                    }
                }
            }
            printf("%I64d\n", ans);
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值