30pts,后面7个全WA,悬赏一赞
查看原帖
30pts,后面7个全WA,悬赏一赞
1001524
UniqueYou楼主2023/8/2 09:04
#include <bits/stdc++.h>
using namespace std;
const int N = 200005;
int n, q, tot1, tot2;
int rt, tot, head[N], de[N], pos[N], sz[N], f[N][20];
int logn, a[N<<2];
pair<int,int> ans[N];
struct edge
{
    int y, next;
}e[N];
struct node1
{
    int x, y, c, id;
}q1[N];
bool cmp(node1 x, node1 y)
{
    return x.c < y.c;
}
struct node2{
    int x,c;
}q2[N];
void adde(int x, int y)
{
    e[++tot] = (edge){y, head[x]};
    head[x] = tot;
}
void dfs(int fa, int u)
{
    pos[u] = ++tot;
    sz[u] = 1;
    for (int i = head[u]; i; i = e[i].next)
    {
        int v = e[i].y;
        if (v == fa)
            continue;
        f[v][0] = u;
        de[v] = de[u] + 1;
        dfs(u, v);
        sz[u] += sz[v];
    }
}
int lca(int x, int y)
{
    if (de[x] < de[y])
        swap(x, y);
    for (int i = 0, p = de[x] - de[y]; p; i++, p >>= 1)
        if (p & 1)
            x = f[x][i];
    if (x == y)
        return x;
    for (int i = logn; i >= 0; i--)
        if (f[x][i] != f[y][i])
            x = f[x][i], y = f[y][i];
    return f[x][0];
}
void add(int x, int k)
{
    for (; x <= n; x += x & (-x))
        a[x] += k;
}
int query(int x)
{
    int ans = 0;
    for (; x; x -= x & (-x))
        ans += a[x];
    return ans;
}
int main()
{
    cin >> n;
    logn = log2(n);
    for (int i = 1; i <= n; i++)
    {
        int x;
        cin >> x;
        if (!x)
            rt = i;
        adde(x, i);
    }
    tot = 0;
    dfs(0, rt);
    for (int j = 1; j <= logn; j++)
        for (int i = 1; i <= n; i++)
            f[i][j] = f[f[i][j-1]][j-1];
    cin >> q;
    int opt;
    for (int i=1;i<=q;++i)
    {
        cin>>opt;
        if (opt==1)
        { 
            ++tot1;
            cin>>q1[tot1].x>>q1[tot1].y>>q1[tot1].c;
            q1[tot1].c=i-q1[tot1].c;    
            q1[tot1].id=i;
        }       
        else 
        {
            ++tot2;
            cin>>q2[tot2].x;
            q2[tot2].c=i;
        }
    }
    sort(q1+1,q1+1+tot1, cmp);//将询问排序 
    int l=1;
    for (int i=1;i<=tot1;++i)
    {
        while (l<=tot2 && q1[l].c<q1[i].c)
        { 
            int x=q2[l].x;
            add(pos[x],1);
            add(pos[x]+sz[x],-1);
            ++l;    
        } 
        int k=lca(q1[i].x,q1[i].y);
        ans[q1[i].id]=make_pair(de[q1[i].x]+de[q1[i].y]-de[k]*2+1,
        query(pos[q1[i].x])+query(pos[q1[i].y])-query(pos[k])-query(pos[f[k][0]]));
    }
    for (int i=1;i<=n;++i)
        if (ans[i].first) 
            cout<<ans[i].first<<' '<<ans[i].second<<'\n';
    return 0;
}
2023/8/2 09:04
加载中...