1589: [Usaco2008 Dec]Trick or Treat on the Farm 采集糖果
Time Limit: 5 Sec Memory Limit: 64 MBSubmit: 693 Solved: 390
[Submit][Status][Discuss]
Description
每年万圣节,威斯康星的奶牛们都要打扮一番,出门在农场的N(1≤N≤100000)个牛棚里转悠,来采集糖果.她们每走到一个未曾经过的牛棚,就会采集这个棚里的1颗糖果. 农场不大,所以约翰要想尽法子让奶牛们得到快乐.他给每一个牛棚设置了一个“后继牛棚”.牛棚i的后继牛棚是Xi.他告诉奶牛们,她们到了一个牛棚之后,只要再往后继牛棚走去,就可以搜集到很多糖果.事实上这是一种有点欺骗意味的手段,来节约他的糖果. 第i只奶牛从牛棚i开始她的旅程.请你计算,每一只奶牛可以采集到多少糖果.
Input
第1行输入N,之后一行一个整数表示牛棚i的后继牛棚Xi,共N行.
Output
共N行,一行一个整数表示一只奶牛可以采集的糖果数量.
Sample Input
4 //有四个点
1 //1有一条边指向1
3 //2有一条边指向3
2 //3有一条边指向2
3
INPUT DETAILS:
Four stalls.
* Stall 1 directs the cow back to stall 1.
* Stall 2 directs the cow to stall 3
* Stall 3 directs the cow to stall 2
* Stall 4 directs the cow to stall 3
1 //1有一条边指向1
3 //2有一条边指向3
2 //3有一条边指向2
3
INPUT DETAILS:
Four stalls.
* Stall 1 directs the cow back to stall 1.
* Stall 2 directs the cow to stall 3
* Stall 3 directs the cow to stall 2
* Stall 4 directs the cow to stall 3
Sample Output
1
2
2
3
2
2
3
HINT
Cow 1: Start at 1, next is 1. Total stalls visited: 1. Cow 2: Start at 2, next is 3, next is 2. Total stalls visited: 2. Cow 3: Start at 3, next is 2, next is 3. Total stalls visited: 2. Cow 4: Start at 4, next is 3, next is 2, next is 3. Total stalls visited: 3.
这个题
tarjan完 记忆化搜索就好了
写完这道题
理解了记忆化搜索的本质是搜索
#include<cmath>
#include<ctime>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<complex>
#include<iostream>
#include<algorithm>
#include<iomanip>
#include<vector>
#include<string>
#include<bitset>
#include<queue>
#include<set>
#include<map>
using namespace std;
inline int read()
{
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch<='9'&&ch>='0'){x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}
return x*f;
}
void print(int x)
{if(x<0)putchar('-'),x=-x;if(x>=10)print(x/10);putchar(x%10+'0');}
const int N=100100;
int n,a[N],dfn[N],low[N],tot,scc,bel[N],sz[N],st[N],top;
bool ins[N];
void tarjan(int u)
{
dfn[u]=low[u]=++tot;st[++top]=u;ins[u]=1;
if(ins[a[u]])low[u]=min(low[u],dfn[a[u]]);
else if(!dfn[a[u]])tarjan(a[u]),low[u]=min(low[u],low[a[u]]);
if(dfn[u]==low[u])
{
int tmp;scc++;
do{tmp=st[top--];bel[tmp]=scc;ins[tmp]=0;sz[scc]++;}while(tmp^u);
}
}
int b[N];
void build()
{
register int i;
for(i=1;i<=n;++i)if(bel[i]^bel[a[i]])b[bel[i]]=bel[a[i]];
}
int f[N];
bool book[N];
int dp(int u)
{
if(f[u])return f[u];
f[u]=sz[u];
if(sz[u]==1)f[u]+=dp(b[u]);
return f[u];
}
int main()
{
n=read();
register int i;
for(i=1;i<=n;++i)a[i]=read();
for(i=1;i<=n;++i)if(!dfn[i])tarjan(i);
build();
for(i=1;i<=n;++i)print(dp(bel[i])),puts("");
return 0;
}
/*
4
1
3
2
3
1
2
2
3
*/