C. Garland(思维)

https://codeforces.com/problemset/problem/767/C


思路:

答案必定%3==0

然后跑子树的和一旦出现了sum/3就可以砍一段,然后记为0接着跑

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=1e6+100;
typedef long long LL;
inline LL read(){LL x=0,f=1;char ch=getchar();	while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
LL val[maxn],siz[maxn];
vector<LL>g[maxn];
vector<LL>ans;
LL tar;
void dfs(LL u,LL fa){
     siz[u]=val[u];
     bool flag=1;
     for(LL i=0;i<g[u].size();i++){
         LL v=g[u][i];
         if(v==fa) continue;
         dfs(v,u);

     }
     if(siz[u]==tar){
        ans.push_back(u);
        siz[u]=0;
     }
}
int main(void){
   cin.tie(0);std::ios::sync_with_stdio(false);
   LL n;cin>>n;
   LL sum=0;
   LL root=0;
   for(LL i=1;i<=n;i++){
       LL fat;cin>>fat>>val[i];sum+=val[i];
       g[fat].push_back(i);
       g[i].push_back(fat);
       if(fat==0) root=i;
   }
   if(sum%3!=0){
      cout<<"-1"<<"\n";
      return 0;
   }
   tar=sum/3;
   dfs(root,0);
   if(ans.size()<=2){
      cout<<"-1"<<"\n";
      return 0;
   }
   LL num=0;
   for(LL i=0;i<ans.size();i++){
       if(ans[i]==root) continue;
       num++;
       cout<<ans[i]<<" ";
       if(num==2) break;
   }
   return 0;
}

 

上一篇:实验十三 扫描 FAT12 文件系统管理的软盘


下一篇:18 机器学习 - 决策树分类器案例