当前位置:网站首页>Codeforces Round #245 (Div. 1) A (dfs)
Codeforces Round #245 (Div. 1) A (dfs)
2022-07-29 22:43:00 【先求一个导】
题目
题意: 给定一棵树,权值均为0或1。现在要执行尽量少的操作,使得初始树中每个点的权值变为对应权值。操作: 使某个节点的权值进行异或,并且其孙子、孙子的孙子都会进行异或操作。
思路: dfs,额外维护当前节点的层数以及奇数层节点的翻转次数、偶数的翻转次数,如果当前层是奇数并且奇数层节点翻转了奇数次,他也需要翻转。O(1)计算值,否则暴力会卡到O(n^2)
时间复杂度: O(n)
代码:
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
int n;
int a[N];
int b[N];
vector<int> va[N];
vector<int> res;
void dfs(int cur,int fa,int level,int l,int r) //奇数、偶数
{
if(level&1)
{
if(l&1) a[cur] ^= 1;
}
else
{
if(r&1) a[cur] ^= 1;
}
int ll = l,rr = r;
if(a[cur]!=b[cur])
{
if(level&1) ll++;
else rr++;
res.push_back(cur);
}
for(int i=0;i<va[cur].size();++i)
{
int j = va[cur][i];
if(j==fa) continue;
dfs(j,cur,level+1,ll,rr);
}
}
void solve()
{
cin>>n;
for(int i=0;i<n-1;++i)
{
int x,y; cin>>x>>y;
va[x].push_back(y),va[y].push_back(x);
}
for(int i=1;i<=n;++i) cin>>a[i];
for(int i=1;i<=n;++i) cin>>b[i];
dfs(1,0,0,0,0);
cout<<res.size()<<"\n";
for(int i=0;i<res.size();++i)
{
if(i) cout<<'\n';
cout<<res[i];
}
}
signed main(void)
{
solve();
return 0;
}
边栏推荐
猜你喜欢
随机推荐
html+css+php+mysql实现注册+登录+修改密码(附完整代码)
The sequence table of the linear table (the dry goods are full of sharing ~ contains all the function codes of the sequence table~
模型评价指标汇总(持续更新)
lambda表达式
Baidu Intelligent Cloud Zhangmiao: Detailed explanation of enterprise-level seven-layer load balancing open source software BFE
五、HikariCP源码分析之初始化分析二
JZ39 数组中出现次数超过一半的数字
go语言中的goroutine(协程)
二、HikariCP源码分析之获取连接流程二
一文参透分布式存储系统Ceph的架构设计、集群搭建(手把手)
一、HikariCP源码分析之获取连接流程一
PLSQL Developer安装和配置
云计算1+X之openstack篇
【企业架构框架】谁推动了现代 EA 最佳实践和内容?
【企业架构】描绘未来第 3 部分:产品路线图
viewpager fragment data refresh
【面试:并发篇29:多线程:volatile】原理
六、HikariConfig配置解析
jsonArray中按某字段排序
J9数字论:为什么我们需要Web3?









