萌新刚学OI TLE 55分 求助!

P3038 [USACO11DEC] Grass Planting G

wlwlwll @ 2019-11-11 22:49:17

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int n,m;
const int maxn=100010;
int head[maxn],nxt[maxn*2],id=0,ans[maxn],d[maxn];
int top[maxn],dep[maxn],son[maxn],hs[maxn],f[maxn],dlt[maxn]; 
struct node{
    int x,y;
};
node E[maxn*2];
void add(int x,int y)
{
    E[++id].y=y;
    E[id].x=x;
    nxt[id]=head[x];
    head[x]=id;
}
void dfs1(int x,int fa)
{
    son[x]=1;
    hs[x]=0;
    f[x]=fa;
    dep[x]=dep[fa]+1;
    for(int i=head[x];i;i=nxt[i])
    {
        int y=E[i].y;
        if(y==fa) continue;
        dfs1(y,x);
        son[x]+=son[y];
        if(son[hs[x]]<son[y])
            hs[x]=y;
    }
}
void dfs2(int x,int t)
{
    top[x]=t;
    if(hs[x]) dfs2(hs[x],t);
    for(int i=head[x];i;i=nxt[i])
    {
        int y=E[i].y;
        if(y==f[x] || y==hs[x]) continue;
        dfs2(y,y);
    }
}
int lca(int x,int y)
{
    while(top[x]!=top[y])
    {
        if(dep[top[x]]<dep[top[y]]) swap(x,y);
        x=f[top[x]];
    }
    return dep[x]<dep[y]?x:y;
}
void dfs3(int x,int fa)
{
    for(int i=head[x];i;i=nxt[i])
    {
        int y=E[i].y;
        if(y==fa) continue;
        dfs3(y,x);
        dlt[x]+=dlt[y];
    }
    ans[d[x]]+=dlt[x];
}
int main()
{
    scanf("%d%d",&n,&m);
    for(int i=1;i<n;i++)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        add(x,y);
        add(y,x);
    }
    dfs1(1,0);
    int t=1;
    for(int i=1;i<n*2;i++)
       if(i%2==1)
       {
            if(dep[E[i].x]>=dep[E[i].y])
              d[E[i].x]=t++;
            else  
              d[E[i].y]=t++;    
       }

    dfs2(1,1);
    for(int i=1;i<=m;i++)
    {
        int x,y;
        char ch;
        cin>>ch;
        scanf("%d%d",&x,&y);
        if(ch=='P')
        {
            int z=lca(x,y);
            dlt[x]++;
            dlt[y]++;
            dlt[z]-=2;
        }
        else
        {
            dfs3(1,0);
            if(dep[x]<dep[y])
               cout<<ans[d[y]]<<endl;
            else
               cout<<ans[d[x]]<<endl;
            memset(dlt,0,sizeof(dlt));
        }
    }
    return 0;
}

orz 大佬看一看


by ztx__ @ 2020-08-09 11:53:12

qwq我的连样例都过不了


|