TLE #7#9 求助!(悬关)

P3806 【模板】点分治 1

dpACerFXing @ 2024-08-23 03:14:30

# include<iostream>
# include<algorithm>
# include<cmath>
# include<vector>
# include<set>
# define endl "\n"
# define int long long
using namespace std;
const int maxn=100001, maxk=10000001;
struct Node{
    int u, v, w, next;
}edge[maxn];
int n, m, head[maxn], vis[maxn], query[maxn], ans[maxn], cnt=0;
int size[maxn], minweight[3];
int dis[maxn], s1[maxk], s2[maxn], t[maxn], s2cnt=0, tcnt=0;
void add(int u, int v, int w) {
    edge[++cnt].u=u;
    edge[cnt].v=v;
    edge[cnt].w=w;
    edge[cnt].next=head[u];
    head[u]=cnt;
}
void get_core(int u, int fa) {
    int weight=0;
    size[u]=1;
    for(int i=head[u]; i; i=edge[i].next) {
        int v=edge[i].v, w=edge[i].w;
        if(v==fa || vis[v]==true) continue ;
        get_core(v, u);
        size[u]+=size[v];
        weight=max(weight, size[v]);
    }
    weight=max(weight, n-size[u]);
    if(minweight[0]==0 || minweight[1]>weight) {
        minweight[0]=1;
        minweight[1]=weight;
        minweight[2]=u;
    }
}
void dep(int u, int fa) {
    s2[++s2cnt]=dis[u];
    for(int i=head[u]; i; i=edge[i].next) {
        int v=edge[i].v, w=edge[i].w;
        if(v==fa || vis[v]) continue;
        dis[v]=dis[u]+w;
        dep(v, u); 
    }
}
void dfs(int u) {
    s1[0]=vis[u]=true; tcnt=0;
    for(int i=head[u]; i; i=edge[i].next) {
        int v=edge[i].v, w=edge[i].w;
        if(vis[v]) continue;
        s2cnt=0; dis[v]=w;
        dep(v, u);

        for(int j=s2cnt; j>=1; j--)
            for(int k=1; k<=m; k++)
                if(query[k]>=s2[j] && s1[query[k]-s2[j]])
                    ans[k]=true;
        for(int j=s2cnt; j>=1; j--) if(s2[j]<maxk) t[++tcnt]=s2[j], s1[s2[j]]=true;
    }
    for(int i=1; i<=tcnt; i++) s1[t[i]]=0;

    for(int i=head[u]; i; i=edge[i].next) {
        int v=edge[i].v, w=edge[i].w;
        if(vis[v]) continue;
        minweight[0]=0;
        get_core(v, u);
        dfs(minweight[2]); 
    }
} 
signed main() {
    cin >> n >> m;
    for(int i=1; i<n; i++) {
        int u, v, w; scanf("%d%d%d", &u, &v, &w);
        add(u, v, w); add(v, u, w);
    }
    for(int i=1; i<=m; i++) cin >> query[i];
    minweight[0]=0; 
    get_core(1, 0);
    dfs(minweight[2]);
    for(int i=1; i<=m; i++)
        if(ans[i]) cout << "AYE" << endl;
        else cout << "NAY" << endl;
    return 0;
}

aaa实在是不会调了qwq


by ZYLZPP @ 2024-08-23 07:28:36

@dpACerLZJun

weight=max(weight, n-size[u]);

此时点分的块的大小不是 n 了,这样找到的不是块的重心,所以TLE

你需要每次找重心前用siz更新块的大小而不是用 n


by dpACerFXing @ 2024-08-23 21:31:34

AC了 mol大佬Orz 给了6个关注


|