csp该题链接
大模拟,磨的累了,不想详写,直接上代码(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;
}