理论上时间复杂度能过,TLE求助

P6121 [USACO16OPEN] Closing the Farm G

柠檬布丁吖 @ 2023-02-17 20:22:24

//Closin
#include<bits/stdc++.h>

using namespace std;

inline int read(){
    int ret=0,f=1;
    char c=getchar();
    for(;c<'0'||c>'9';c=getchar()) if(c=='-') f=-f;
    for(;c>='0'&&c<='9';c=getchar()) ret=ret*10+c-'0';
    return ret*f;
}

const int maxn=2e5+55;
int N,M;
int head[maxn],tot;
struct cow{
    int ne;
    int to;
    int w;
}c[maxn];

void add(int x,int y){
    c[++tot].w=x;
    c[tot].to=y;
    c[tot].ne=head[x];
    head[x]=tot;
}

int r[maxn],fa[maxn],ans[maxn];
bool vis[maxn];

void init(){
    for(int i=1;i<=N;i++){
        fa[i]=i;
    }
}

int _find(int x){
    if(fa[x]==x) return x;
    else fa[x]=_find(fa[x]);
}

signed main(void){

    N=read();M=read();

    for(int i=1;i<=M;i++){
        int u,v;
        u=read();v=read();
        add(u,v);add(v,u);
    }

    for(int i=1;i<=N;i++){
        r[i]=read();    
    }

    init();
    vis[r[N]]=true;
    ans[N]=1;
    int k=0;
    for(int i=N-1;i>=1;i--){
        vis[r[i]]=true;
        for(int j=head[r[i]];j;j=c[j].ne){
            if(vis[c[j].to]==1){
                int _x=_find(r[i]),_y=_find(c[j].to);
                if(_x!=_y){
                    ++k;
                    fa[_x]=_y;
                }
            }

//          puts("awa");
        }

        if(k==N-i) ans[i]=1;
        else ans[i]=0;
    }

    for(int i=1;i<=N;i++){
        if(ans[i]==1) printf("YES\n");
        else printf("NO\n");
    }

    return 0;
}

by WatchFlowers @ 2023-02-17 20:25:39

用这个试试


#include<bits/stdc++.h>
using namespace std;
namespace IO{
    char ibuf[(1<<20)+1],*iS,*iT;
    #if ONLINE_JUDGE
    #define gh() (iS==iT ? iT=(iS=ibuf)+fread(ibuf,1,(1<<20)+1,stdin),(iS==iT ? EOF : *iS++) : *iS++)
    #else
    #define gh() getchar()
    #endif
    #define reg register
    inline long long read(){
        reg char ch=gh();
        reg long long x=0;
        reg char t=0;
        while(ch<'0'||ch>'9')   t|=ch=='-',ch=gh();
        while(ch>='0'&&ch<='9') x=x*10+(ch^48),ch=gh();
        return t?-x:x;
    }
    inline void write(long long x)
    {
        if(x < 0){
            putchar('-');
            x = -x;
        }
        if(x > 9) 
            write(x/10);
        putchar(x%10+'0');
    }
}
using IO::read;
using IO::write;
int main()
{
    int a;
    a=read();
    write(a);
   //code here
}

by WatchFlowers @ 2023-02-17 20:26:11

再开O2


by Manki233 @ 2024-05-18 14:13:52

@柠檬布丁吖

int _find(int x){
    if(fa[x]==x) return x;
    else fa[x]=_find(fa[x]); <-- 没返回!!
}

|