1. 程式人生 > >bzoj 1589: [Usaco2008 Dec]Trick or Treat on the Farm 采集糖果【tarjan+記憶化搜索】

bzoj 1589: [Usaco2008 Dec]Trick or Treat on the Farm 采集糖果【tarjan+記憶化搜索】

dfs spa 重新 i++ mes RM tar \n ()

對這個奇形怪狀的圖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\n",mp[bl[i]]); return 0; } /* 4 1 3 2 3 */

bzoj 1589: [Usaco2008 Dec]Trick or Treat on the Farm 采集糖果【tarjan+記憶化搜索】