求助悬关60pts

P2272 [ZJOI2007] 最大半连通子图

whileAK @ 2024-10-07 14:30:12

TLE6,7,WA8


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
void rd(int &p){
    p=0;char z=getchar();int f(0);
    while(z>'9'||z<'0'){if(z=='-')f^=1;z=getchar();}
    while(z<='9'&&z>='0')p=(p<<1)+(p<<3)+z-'0',z=getchar();
    if(f)p=-p;
}
void rdl(ll &p){
    p=0;char z=getchar();int f(0);
    while(z>'9'||z<'0'){if(z=='-')f^=1;z=getchar();}
    while(z<='9'&&z>='0')p=(p<<1)+(p<<3)+z-'0',z=getchar();
    if(f)p=-p;
}
const int N=1e5+50,M=2e6+50;
int n,m,mod,hd[N],v[M],nxt[M],fr[N],ct(1);
void link(int x,int y){
    v[++ct]=y;fr[ct]=x;nxt[ct]=hd[x];hd[x]=ct;
}
int dfn[N],low[N],num(0),st[N],tp(0),scc[N],cnt(0);
bool in[N];
void tarjan(int p){
    dfn[p]=low[p]=++num;
    st[++tp]=p;in[p]=true;
    for(int i(hd[p]);i;i=nxt[i]){
        if(!dfn[v[i]]){
            tarjan(v[i]);low[p]=min(low[p],low[v[i]]);
        }
        else if(in[v[i]])low[p]=min(low[p],dfn[v[i]]);
    }
    if(dfn[p]==low[p]){
        ++cnt;
        while(st[tp]!=p){
            scc[st[tp]]=cnt;
            in[st[tp--]]=false;
        }
        --tp;scc[p]=cnt;in[p]=false;
    }
}
int be[N],to[N],e(0),a[N],r[N],f[N],mx[N];
map<pair<int,int>,bool>h;
int main(){
    rd(n);rd(m);rd(mod);
    for(int i(1),x,y;i<=m;++i){
        rd(x);rd(y);link(x,y);
    }
    for(int i(1);i<=n;++i)if(!scc[i])tarjan(i);
    for(int i(2);i<=ct;++i){
        if(scc[fr[i]]!=scc[v[i]]){
            be[++e]=scc[fr[i]];to[e]=scc[v[i]];
        }
    }
    for(int i(1);i<=n;++i)hd[i]=0,++a[scc[i]],f[i]=1;ct=1;
    for(int i(1),x,y;i<=e;++i){
        x=be[i],y=to[i];
        if(!h[make_pair(x,y)])link(x,y),++r[y];
        h[make_pair(x,y)]=true;
    }
    queue<int>q;int u;
    for(int i(1);i<=cnt;++i)if(!r[i])q.push(i);
    while(q.size()){
        u=q.front();q.pop();
        mx[u]+=a[u];
        for(int i(hd[u]);i;i=nxt[i]){
            --r[v[i]];if(!r[v[i]])q.push(v[i]);
            if(mx[u]>mx[v[i]]){
                mx[v[i]]=mx[u];f[v[i]]=f[u];
            }
            else if(mx[u]==mx[v[i]])f[v[i]]+=f[u];
            f[v[i]]%=mod;
        }
    }
    int ans(0),ANS(0);
    // for(int i(1);i<=n;++i)printf("%d ",scc[i]);cout<<endl;
    // for(int i(1);i<=e;++i)printf("%d %d\n",be[i],to[i]);cout<<endl;
    // for(int i(1);i<=cnt;++i)printf("%d ",mx[i]);cout<<endl;
    // for(int i(1);i<=cnt;++i)printf("%d ",f[i]);cout<<endl;
    for(int i(1);i<=cnt;++i)ans=max(ans,mx[i]);
    for(int i(1);i<=cnt;++i)if(mx[i]==ans){
        ANS+=f[i];ANS%=mod;
    }printf("%d\n%d",ans,ANS);
    return 0;
}

by whileAK @ 2024-10-07 15:43:52

问题已解决,数组开小导致的


|