//第二题70% #include <iostream> #include <stdio.h> #include <stdlib.h> #include <string> #include <algorithm> #include <vector> #include <math.h> using namespace std; typedef long long ll; bool compare(int a,int b) {     return a>b; } void dfs(vector<int > &sontree,vector<int > &others,int *father,int *value,int i,int n) {     for(int j=0;j<n-1;j++)     {         if(father[j]==i)         {             sontree.push_back(value[j+1]);             dfs(sontree,others,father,value,j+1,n);         }     }     return; } int main() {     int n;     while(cin>>n)     {         int father[n-1];         for(int i=0;i<n-1;i++)             cin>>father[i];         int value[n];         for(int i=0;i<n;i++)             cin>>value[i];         vector<int > sontree;         vector<int > others;         int sum=0;         for(int i=1;i<=n-1;i++)         {             sontree.clear();             others.clear();             sontree.push_back(value[i]);             dfs(sontree,others,father,value,i,n);             sort(sontree.begin(),sontree.end(),compare);             for(int i=0;i<sontree.size();i++)                 cout<<sontree[i]<<' ';             cout<<endl;             for(int i=0;i<n;i++)             {                 vector<int>::iterator it=find(sontree.begin(),sontree.end(),value[i]);                 if (it==sontree.end())                 {                     others.push_back(value[i]);                 }             }             sort(others.begin(),others.end(),compare);             for(int i=0;i<others.size();i++)                 cout<<others[i]<<' ';             cout<<endl;             sum+=abs(sontree[0]-others[0]);         }         cout<<sum<<endl;     } }
点赞 2

相关推荐

牛客网
牛客网在线编程
牛客网题解
牛客企业服务