打暴力40,这题的话预处理和暴搜哪个复杂度更高?
查看原帖
打暴力40,这题的话预处理和暴搜哪个复杂度更高?
817616
Arthur_楼主2023/11/10 19:53
#include <bits/stdc++.h>
using namespace std;
#define int long long
vector<int> edge[100001];
int n,q,a,b,c,d;
int dis[100001];
int fa[100001];
bool flaga[100001];
bool flagb[100001];
bool flag=true;
void read(int &p)
{
    p=0;
    int k=1;
    char c=getchar();
    while(c<'0' || c>'9')
    {
        if(c=='-')
        {
            k=-1;
        }
        c=getchar();
    }
    while(c>='0' && c<='9')
    {
        p=p*10+c-'0';
        c=getchar();
    }
    p*=k;
    return;
}
void found(int aim,int pos)
{
    memset(flagb,0,sizeof(flagb));
    int now=aim;
    flagb[pos]=true;
    while(now!=pos)
    {
        flagb[now]=true;
        now=fa[now];
    }
    return;
}
void find(int aim,int pos)
{
    int now=aim;
    if(flagb[pos])
    {
        flag=true;
        return;
    }
    while(now!=pos)
    {
        if(flagb[now])
        {
            flag=true;
            return;
        }
        now=fa[now];
    }
    return;
}
void bfs(int pos,int aim)
{
    memset(fa,0,sizeof(fa));
    memset(flaga,0,sizeof(flaga));
    queue<int> p;
    p.push(pos);
    while(!p.empty())
    {
        int u=p.front();
        p.pop();
        for(int i=0;i<edge[u].size();i++)
        {
            if(flaga[edge[u][i]]==false)
            {
                flaga[edge[u][i]]=true;
                p.push(edge[u][i]);
                fa[edge[u][i]]=u;
                if(edge[u][i]==aim)
                {
                    found(aim,pos);
                    return;
                }
            }
        }
    }
}
void bfss(int pos,int aim)
{
    memset(fa,0,sizeof(fa));
    memset(flaga,0,sizeof(flaga));
    queue<int> p;
    p.push(pos);
    while(!p.empty())
    {
        int u=p.front();
        p.pop();
        for(int i=0;i<edge[u].size();i++)
        {
            if(flaga[edge[u][i]]==false)
            {
                flaga[edge[u][i]]=true;
                p.push(edge[u][i]);
                fa[edge[u][i]]=u;
                if(edge[u][i]==aim)
                {
                    find(aim,pos);
                    return;
                }
            }
        }
    }
}
signed main()
{
    read(n),read(q);
    for(int i=1,u,v;i<n;i++)
    {
        read(u),read(v);
        edge[u].push_back(v);
        edge[v].push_back(u);
    }
    for(int i=1;i<=q;i++)
    {
        flag=false;
        read(a),read(b),read(c),read(d);
        bfs(a,b);
        bfss(c,d);
        if(flag)
        {
            cout<<"Y"<<endl;
        }
        else
        {
            cout<<"N"<<endl;
        }
    }
    return 0;
}
'''
2023/11/10 19:53
加载中...