当前位置:网站首页>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;
}
边栏推荐
猜你喜欢
随机推荐
真offer收割机 第一弹~大厂如何考察候选人?(附答案详解)
我想申请专利,却没有经验,如何学会写专利申请文件?
JZ6 从尾到头打印链表
《MySQL DBA封神打怪之路》专栏学习大纲
C语言实现扫雷(9*9)游戏——详解
J9 Number Theory: Why do we need Web3?
SQL 改写系列七:谓词移动
This article penetrates the architecture design and cluster construction of the distributed storage system Ceph (hands-on)
GBASE 8s PAM插入式身份验证模块
【板栗糖GIS】wps—如何查看表格中的超链接
OR59 字符串中找出连续最长的数字串
都有哪些查找和下载英文文献的方法?
三、HikariCP源码分析之获取连接流程三
一文读懂Elephant Swap,为何为ePLATO带来如此高的溢价?
i2c时序图的详细讲解[通俗易懂]
Any to Any 实时变声的实现与落地丨RTC Dev Meetup
canvas 中如何实现物体的点选(五)
Advanced Mathematics (Seventh Edition) Tongji University Exercises 3-8 Individual Answers
GBASE 8s 用户标示与鉴别
JVM 上数据处理语言的竞争:Kotlin, Scala 和 SPL