zoukankan      html  css  js  c++  java
  • bzoj 1589: [Usaco2008 Dec]Trick or Treat on the Farm 采集糖果【tarjan+记忆化搜索】

    对这个奇形怪状的图tarjan,然后重新连边把图变成DAG,然后记忆化搜索即可

    #include<iostream>
    #include<cstdio>
    using namespace std;
    const int N=100005;
    int n,a[N],h[N],cnt,dfn[N],low[N],tot,s[N],top,bl[N],si[N],col,mp[N];
    bool v[N];
    struct qwe
    {
    	int ne,to;
    }e[N];
    int read()
    {
    	int r=0,f=1;
    	char p=getchar();
    	while(p>'9'||p<'0')
    	{
    		if(p=='-')
    			f=-1;
    		p=getchar();
    	}
    	while(p>='0'&&p<='9')
    	{
    		r=r*10+p-48;
    		p=getchar();
    	}
    	return r*f;
    }
    void tarjan(int u)
    {
    	dfn[u]=low[u]=++tot;
    	v[s[++top]=u]=1;
    	if(!dfn[a[u]])
    		tarjan(a[u]),low[u]=min(low[u],low[a[u]]);
    	else if(v[a[u]])
    		low[u]=min(low[u],dfn[a[u]]);
    	if(low[u]==dfn[u])
    	{
    		col++;
    		while(s[top]!=u)
    		{
    			bl[s[top]]=col;
    			si[col]++;
    			v[s[top--]]=0;
    		}
    		bl[s[top]]=col;
    		si[col]++;
    		v[s[top--]]=0;
    	}
    }
    void add(int u,int v)
    {//cerr<<u<<" "<<v<<endl;
    	cnt++;
    	e[cnt].ne=h[u];
    	e[cnt].to=v;
    	h[u]=cnt;
    }
    int dfs(int u)
    {
    	if(mp[u]!=0)
    		return mp[u];
    	for(int i=h[u];i;i=e[i].ne)
    		mp[u]+=dfs(e[i].to);
    	return mp[u]+=si[u];
    }
    int main()
    {
    	n=read();
    	for(int i=1;i<=n;i++)
    		a[i]=read();
    	for(int i=1;i<=n;i++)
    		if(!dfn[i])
    			tarjan(i);
    	for(int i=1;i<=n;i++)
    		if(bl[i]!=bl[a[i]])
    			add(bl[i],bl[a[i]]);
    	for(int i=1;i<=col;i++)
    		dfs(i);
    	for(int i=1;i<=n;i++)
    		printf("%d
    ",mp[bl[i]]);
    	return 0;
    }
    /*
    4
    1
    3
    2
    3
    */
    
  • 相关阅读:
    webjars管理静态资源
    SpringCloud踩坑日记
    ELK日志搜索平台搭建
    新硬盘挂载到目录后目录原先数据消失解决办法
    nginx安装缺少依赖记录
    SpringCloud踩坑日记
    .bashrc配错刷新导致linux基础命令不能用修复
    nginx超时时间配置
    nginx日志切分shell脚本
    2019.10.10 实习日记
  • 原文地址:https://www.cnblogs.com/lokiii/p/8994694.html
Copyright © 2011-2022 走看看