我的代码好像并不对,复杂度是假的????

CF1009F Dominant Indices

七里 @ 2019-12-19 20:17:51

#include<cstdio>
#include<algorithm>
#define R register
using namespace std;
const int N=1001000;
int n,dep[N],son[N],ans[N],cnt[N],fa[N],mx,ddp,Son,d[N],sz[N];

int tot,head[N],nex[N<<1],ver[N<<1];

inline void add(int x,int y){
    ver[++tot]=y;nex[tot]=head[x];head[x]=tot;
}

inline void dfs1(int x,int f){
    sz[x]=1;
    dep[x]=1;fa[x]=f;d[x]=d[f]+1;
    for(R int i=head[x];i;i=nex[i]){
        if(ver[i]==f) continue;
        dfs1(ver[i],x);
        dep[x]=max(dep[x],dep[ver[i]]+1);
        sz[x]+=sz[ver[i]];
        if(dep[ver[i]]>dep[son[x]]) son[x]=ver[i];
    }
}

inline void change(int x,int v){
    cnt[d[x]]+=v;
    if(cnt[d[x]]>mx) mx=cnt[d[x]],ddp=d[x];
    else if(cnt[d[x]]==mx&&d[x]<ddp) ddp=d[x];
    for(R int i=head[x];i;i=nex[i]){
        if(ver[i]==fa[x]||ver[i]==Son) continue;
        change(ver[i],v);
    }
}

inline void dfs2(int x,int op){
    for(R int i=head[x];i;i=nex[i]){
        if(ver[i]==fa[x]||ver[i]==son[x]) continue;
        dfs2(ver[i],0);
    }
    if(son[x]) dfs2(son[x],1),Son=son[x];
    change(x,1);ans[x]=ddp-d[x];Son=0;
    if(!op) change(x,-1),ddp=mx=0;
}

int main (){
    scanf("%d",&n);
    for(R int x,y,i=1;i<n;i++){
        scanf("%d%d",&x,&y);
        add(x,y),add(y,x);
    }
    dfs1(1,0);
    dfs2(1,1);
    for(R int i=1;i<=n;i++) printf("%d\n",ans[i]);
    return 0;
}

上面那个可以AC。

下面这个TLE喽 (虽然这是肯定的)

#include<cstdio>
#include<algorithm>
#define R register
using namespace std;
const int N=1001000;
int n,dep[N],son[N],ans[N],cnt[N],fa[N],mx,ddp,Son,d[N],sz[N];

int tot,head[N],nex[N<<1],ver[N<<1];

inline void add(int x,int y){
    ver[++tot]=y;nex[tot]=head[x];head[x]=tot;
}

inline void dfs1(int x,int f){
    sz[x]=1;
    dep[x]=1;fa[x]=f;d[x]=d[f]+1;
    for(R int i=head[x];i;i=nex[i]){
        if(ver[i]==f) continue;
        dfs1(ver[i],x);
        dep[x]=max(dep[x],dep[ver[i]]+1);
        sz[x]+=sz[ver[i]];
        //if(dep[ver[i]]>dep[son[x]]) son[x]=ver[i];
        if(son[ver[i]]>sz[son[x]]) son[x]=ver[i];
    }
}

inline void change(int x,int v){
    cnt[d[x]]+=v;
    if(cnt[d[x]]>mx) mx=cnt[d[x]],ddp=d[x];
    else if(cnt[d[x]]==mx&&d[x]<ddp) ddp=d[x];
    for(R int i=head[x];i;i=nex[i]){
        if(ver[i]==fa[x]||ver[i]==Son) continue;
        change(ver[i],v);
    }
}

inline void dfs2(int x,int op){
    for(R int i=head[x];i;i=nex[i]){
        if(ver[i]==fa[x]||ver[i]==son[x]) continue;
        dfs2(ver[i],0);
    }
    if(son[x]) dfs2(son[x],1),Son=son[x];
    change(x,1);ans[x]=ddp-d[x];Son=0;
    if(!op) change(x,-1),ddp=mx=0;
}

int main (){
    scanf("%d",&n);
    for(R int x,y,i=1;i<n;i++){
        scanf("%d%d",&x,&y);
        add(x,y),add(y,x);
    }
    dfs1(1,0);
    dfs2(1,1);
    for(R int i=1;i<=n;i++) printf("%d\n",ans[i]);
    return 0;
}

by 1saunoya @ 2019-12-19 20:33:00

dsu on tree?


|