MnZn求助,TLE + WA,只有30pt
查看原帖
MnZn求助,TLE + WA,只有30pt
239167
Ptilopsis_w楼主2021/7/21 07:12
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define register

#define MAXN 500010

namespace fast_read{
    inline char getch(){
        static char buf[1<<21], *p1, *p2;
        return (p1==p2)and(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++;
    }
    template<typename T> inline void read(T &s){
        s = 0; int w = 1; char ch;
        while(ch=getch(),!isdigit(ch)) if(ch=='-') w=-1;
        while(isdigit(ch)) s=(s<<3)+(s<<1)+(ch^48),ch=getch();  s*=w;
    }
    template<typename T, typename... T1> inline void read(T& a, T1&... other){
        read(a); read(other...);
    }
}//using namespace fast_read;
namespace chain_forward_star{
    int head[MAXN], cnt;
    struct edge{
        int to, next;
        edge(int _to = 0, int _next = 0)
        {
            this -> to = _to;
            this -> next = _next;
        }
    }side[MAXN*2];
    void insert(int from, int to)
    {
        cnt++;
        side[cnt].to = to;
        side[cnt].next = head[from];
        head[from] = cnt;
    }
}using namespace chain_forward_star;


int n, m, s;
int fa[MAXN][40], lg[MAXN], depth[MAXN];

void input();
void dfs(int now, int nowfa);
int lca(int x, int y);

int main()
{
    #ifndef ONLINE_JUDGE
        freopen("1in.txt", "r", stdin);
        freopen("1out.txt", "w", stdout);
    #endif

    input();
    for(int i = 1, a, b; i <= m; i++)
    {
        scanf("%d%d", &a, &b);
        printf("%d\n", lca(a, b));
    }
    return 0;
}



void input()
{
    scanf("%d%d%d", &n, &m, &s);
    for(int i = 1, a, b; i < n; i++)
    {
        scanf("%d%d", &a, &b);
        insert(a, b);
        insert(b, a);
    }
    for(int i = 1; i <= n; i++)
        lg[i] = lg[i-1] + (1 << lg[i-1] == 1);
    dfs(s, 0);
}

void dfs(int now, int nowfa)
{
    fa[now][0] = nowfa; depth[now] = depth[nowfa] + 1;
    for(int i = 1; i <= lg[depth[now]]; i++)
        fa[now][i] = fa[fa[now][i-1]][i-1];
    for(int i = head[now]; i != 0; i = side[i].next)
    {
        if(side[i].to != nowfa)
            dfs(side[i].to, now);
    }
}

int lca(int x, int y)
{
    if(depth[x] < depth[y])
        swap(x, y);
    while(depth[x] > depth[y])
        x = fa[x][lg[depth[x]-depth[y]]-1];
    if(x == y)
        return x;
    
    for(int k = lg[depth[x]] - 1; k >= 0; k--)
    {
        if(fa[x][k] != fa[y][k])
            x = fa[x][k], y = fa[y][k];
    }
    return fa[x][0];
}
2021/7/21 07:12
加载中...