CSP 202312-3 树上搜索 100分题解

本文介绍了使用C++实现的树上搜索算法解决CSP问题,包括结构定义、函数如wgt_init、quest和protree,以及在给定边的关系下求解路径的过程。
摘要由CSDN通过智能技术生成

csp该题链接 

202312-3 树上搜索

大模拟,磨的累了,不想详写,直接上代码(15ms,3.156MB)

#include<algorithm>
#include<iostream>
#include<cstring>
#include<vector>
#include<set>
using namespace std;
struct Node
{
    int pre=0;
    set<int>nxt;
    long long wgt;
    Node(int WGT):wgt(WGT){}
};
long long _abs(long long num)
{
    if(num>=0)  return num;
    else return -num;
}
struct Choice
{
    int id;
    long long d;
    Choice(int ID,long long D):id(ID),d(D){}
    bool operator<(Choice b) const
    {
        long long fd=_abs(d),bfd=_abs(b.d);
        if(fd!=bfd) return fd<bfd;
        else        return id<b.id;
    }
};
vector<Node> node={Node(0)};
set<int> belong;
int wgt[2001]={0};
bool rej[2001]={0};
int n,m,q;
long long wgt_init(int i)
{
    node[i].wgt=wgt[i];
    for(auto x:node[i].nxt)
        if(!rej[x])
            node[i].wgt+=wgt_init(x);
    return node[i].wgt;
}
int quest(int i,long long tot)
{
    vector<Choice> choice;
    choice.push_back(Choice(i,tot-2*node[i].wgt));
    for(auto x:node[i].nxt)
    {
        if(!rej[x])
        {
            long long d=tot-2*node[x].wgt;
            if(d<0)
                return quest(x,tot);
            else
                choice.push_back(Choice(x,d));
        }
    }
    if(tot==node[i].wgt&&choice.size()==1)    return 0;
    return (*min_element(choice.begin(),choice.end())).id;
}
void protree()
{
    int temp,top=1;
    memset(rej,0,sizeof(rej));
    wgt_init(top);
    while(temp=quest(top,node[top].wgt),temp)
    {
        cout<<temp<<' ';
        if(belong.count(temp))
        {
            top=temp;
        }
        else
        {
            rej[temp]=1;
            wgt_init(top);
        }
    }
    cout<<endl;
}
int main()
{
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        cin>>wgt[i];
        node.push_back(Node(wgt[i]));
    }
    for(int i=2;i<=n;i++)
    {
        int p;
        cin>>p;
        node[p].nxt.insert(i);
        node[i].pre=p;
    }
    for(int i=0;i<m;i++)
    {
        cin>>q;
        belong.clear();
        int temp=q;
        do
        {
            belong.insert(temp);
            temp=node[temp].pre;
        } while (temp);
        protree();
    }
    return 0;
}

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值