「Poetize4」创世纪

在tyvj上怀疑爆栈了.....或许一定是我写挂了。以后调吧。。。
题解:https://blog.csdn.net/popoqqq/article/details/39965603
po姐太神了!

#include <cstdio>
#include <queue>
#include <cstring>
#include <algorithm>
using namespace std;
const int N=1001001,inf=0x3f3f3f3f;
int n;
int head[N],ans,cnt,a[N],p,tp,f[N],g[N],fa[N];
bool vis[N];
struct Edge {
    int to,nxt;
    bool cir;
} e[N];
void add(int bg,int ed) {
    e[++cnt].to=ed;
    e[cnt].nxt=head[bg];
    head[bg]=cnt;
}
void dfs(int x) {
    vis[x]=1;
    if(vis[a[x]]) p=x;
    else dfs(a[x]);
}
void Treedp(int x) {
    f[x]=1;
    g[x]=inf;
    vis[x]=1;
    if(x==tp) g[x]=0;
    for(int i=head[x]; i; i=e[i].nxt) {
        if(!e[i].cir&&e[i].to!=fa[x]) {
            fa[e[i].to]=x;
            Treedp(e[i].to);
            g[x]+=min(g[e[i].to],f[e[i].to]);
            g[x]=min(g[x],f[x]+f[e[i].to]-1);
            f[x]+=min(g[e[i].to],f[e[i].to]);
        }
    }
}
int main() {
    freopen("input.txt","r",stdin);
    scanf("%d",&n);
    printf("%d",n);
    for(int i=1,x; i<=n; i++) {
        scanf("%d",&a[i]);
        add(a[i],i);
    }
    for(int i=1; i<=n; i++) {
        if(!vis[i]) {
            dfs(i);
            e[p].cir=1;
            tp=a[p];
            Treedp(p);
            int tmp=f[p];
            tp=0;
            Treedp(p);
            ans+=min(tmp,g[p]);
        }
    }
    printf("%d",n-ans);
}

Please contact [email protected]!

猜你喜欢

转载自www.cnblogs.com/sdfzhsz/p/9279356.html
今日推荐