Problem E. TeaTree
Time Limit: 8000/4000 MS (Java/Others) Memory Limit: 524288/524288 K (Java/Others)
Total Submission(s): 781 Accepted Submission(s): 291
Problem Description
Recently, TeaTree acquire new knoledge gcd (Greatest Common Divisor), now she want to test you.
As we know, TeaTree is a tree and her root is node 1, she have n nodes and n-1 edge, for each node i, it has it’s value v[i].
For every two nodes i and j (i is not equal to j), they will tell their Lowest Common Ancestors (LCA) a number : gcd(v[i],v[j]).
For each node, you have to calculate the max number that it heard. some definition:
In graph theory and computer science, the lowest common ancestor (LCA) of two nodes u and v in a tree is the lowest (deepest) node that has both u and v as descendants, where we define each node to be a descendant of itself.
Input
On the first line, there is a positive integer n, which describe the number of nodes.
Next line there are n-1 positive integers f[2] ,f[3], …, f[n], f[i] describe the father of node i on tree.
Next line there are n positive integers v[2] ,v[3], …, v[n], v[i] describe the value of node i.
n<=100000, f[i]< i, v[i]<=100000
Output
Your output should include n lines, for i-th line, output the max number that node i heard.
For the nodes who heard nothing, output -1.
Sample Input
4
1 1 3
4 1 6 9
Sample Output
2
-1
3
-1
题意:给出一棵树,每个节点有一个值,求每个节点的 子树中所有节点(包括自己本身),两两组合的gcd,输出最大的gcd
这题意好像我又没描述清楚
首先观察数据,每个节点的值v<=1e5,还是比较小的,在1e5以内的数最大因子数只有128,看时间给了4s,暴力!!(其实我不会算这题复杂度,逃)可以把每个节点的因子都处理出来,然后向上合并,如果合并时有两棵子树的出现了相同因子,那么则刷新这个节点的答案
主要是考虑暴力合并子树的时候使用哪种数据结构
用值域线段树可以很好地解决这个问题,冗余节点不多,而且能很好地表示大小关系,在合并时可以直接得到答案
如果还不懂,就看代码把(蒟蒻代码适合观察)
#include
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
const int N=1e5+200;
const int M=N*400;
typedef long long LL;
vector<int>g[N],vec[N];
int root[N],tot,ls[M],rs[M],sum[M];
void pushup(int rt)
{
if(ls[rt]&&rs[rt])
sum[rt]=max(sum[ls[rt]],sum[rs[rt]]);
else if(ls[rt])
sum[rt]=ls[rt];
else if(rs[rt])sum[rt]=rs[rt];
}
void update(int q,int l,int r,int &rt)
{
if(!rt)rt=++tot;
if(l==r)
{
sum[rt]=q;
return;
}
int m=(l+r)>>1;
if(q<=m)
update(q,l,m,ls[rt]);
else
update(q,m+1,r,rs[rt]);
pushup(rt);
}
int merge(int rt1,int rt2,int &ans)
{
if(!rt1||!rt2)return rt1^rt2;
if(sum[rt1]==sum[rt2])ans=max(ans,sum[rt1]);
if(ls[rt1]||ls[rt2])ls[rt1]=merge(ls[rt1],ls[rt2],ans);
if(rs[rt1]||rs[rt2])rs[rt1]=merge(rs[rt1],rs[rt2],ans);
pushup(rt1);
return rt1;
}
int ans[N];
void dfs(int u)
{
for(auto v:g[u])
{
dfs(v);
root[u]=merge(root[u],root[v],ans[u]);
}
}
int main()
{
for(int i=1;ifor(int j=i;jmemset(ans,-1,sizeof(ans));
int n,x;
scanf("%d",&n);
for(int i=2;i<=n;i++)
{
scanf("%d",&x);
g[x].push_back(i);
}
for(int i=1;i<=n;i++)
{
scanf("%d",&x);
for(auto j:vec[x])
update(j,1,N,root[i]);
}
dfs(1);
for(int i=1;i<=n;i++)
printf("%d\n",ans[i]);
return 0;
}