Live2d Test Env

HDU - 6430:TeaTree (线段树合并)

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.

InputOn 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]<=100000OutputYour 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

题意:对于每个点,求以它为LCA的最大GCD。

思路:求出每个点的子树的 因子线段树,然后暴力合并,3000ms过了,(没有启发式,就是裸的合并,我也不知道复杂度怎么算的)。

不过好像可以启发式(我尝试了下用size来排序后合并,时间上并没有优化,所以不知所措); 以及bitset两种方式来优化。占位。

#include<bits/stdc++.h>
#define rep(i,a,b) for(int i=a;i<=b;i++)
using namespace std;
const int maxn=100010;
struct in{ int l,r,Max; }s[maxn*400];
vector<int>G[maxn],P[maxn]; //图,因子
int rt[maxn],ans[maxn],a[maxn],cnt;
void prepare()
{
    for(int i=1;i<maxn;i++)
     for(int j=i;j<maxn;j+=i)
       P[j].push_back(i);
}
void update(int &Now,int L,int R,int val)
{
    if(!Now) Now=++cnt;
    if(L==R){ s[Now].Max=val; return ;}
    int Mid=(L+R)>>1;
    if(val<=Mid) update(s[Now].l,L,Mid,val);
    else update(s[Now].r,Mid+1,R,val);
    s[Now].Max=max(s[s[Now].l].Max,s[s[Now].r].Max);
}
int merrge(int u,int v,int &ans)
{
    if(!u||!v) return u|v;
    if(s[u].Max==s[v].Max) ans=max(ans,s[u].Max);
    if(s[u].l||s[v].l) s[u].l=merrge(s[u].l,s[v].l,ans);
    if(s[u].r||s[v].r) s[u].r=merrge(s[u].r,s[v].r,ans);
    return u;
}
void dfs(int u)
{
    for(int i=0,L=G[u].size();i<L;i++){
        dfs(G[u][i]);
        merrge(rt[u],rt[G[u][i]],ans[u]);
    }
}
int main()
{
    prepare();
    int N,x,mx=0; scanf("%d",&N);
    rep(i,1,N) ans[i]=-1;
    rep(i,2,N) scanf("%d",&x),G[x].push_back(i);
    rep(i,1,N) scanf("%d",&a[i]),mx=max(mx,a[i]);
    rep(i,1,N) {
        for(int j=0,L=P[a[i]].size();j<L;j++)
         update(rt[i],1,mx,P[a[i]][j]);
    }
    dfs(1);
    rep(i,1,N) printf("%d\n",ans[i]);
    return 0;
}

 

posted @ 2018-10-25 10:02  nimphy  阅读(205)  评论(0编辑  收藏  举报