• [图论]在农场万圣节Trick or Treat on the Farm


    在农场万圣节Trick or Treat on the Farm

    Description

    每年,在威斯康星州,奶牛们都会穿上衣服,收集农夫约翰在N(1<=N<=100,000)个牛棚隔间中留下的糖果,以此来庆祝美国秋天的万圣节。

    由于牛棚不太大,FJ通过指定奶牛必须遵循的穿越路线来确保奶牛的乐趣。为了实现这个让奶牛在牛棚里来回穿梭的方案,FJ在第i号隔间上张贴了一个“下一个隔间”Next_i(1<=Next_i<=N),告诉奶牛要去的下一个隔间;这样,为了收集它们的糖果,奶牛就会在牛棚里来回穿梭了。

    FJ命令奶牛i应该从i号隔间开始收集糖果。如果一只奶牛回到某一个她已经去过的隔间,她就会停止收集糖果。

    在被迫停止收集糖果之前,计算一下每头奶牛要前往的隔间数(包含起点)。

    Input

    第1行 整数n。

    第2行到n+1行 每行包含一个整数 next_i 。

    output

    n行,第i行包含一个整数,表示第i只奶牛要前往的隔间数。

    Examples

    Input

    4
    1
    3
    2
    3

    Output

    1
    2
    2
    3

    正确解法:

     1 #include<iostream>
     2 #include<cstdio>
     3 #include<string>
     4 #include<cstring>
     5 #include<map>
     6 #include<set>
     7 #include<vector>
     8 #include<queue>
     9 #include<algorithm>
    10 #include<cmath>
    11 using namespace std;
    12 typedef long long ll;
    13 const int N=100000+100;
    14 int Link[N],len=0,bok[N];
    15 int n,yy,ans[N],que[N];
    16 struct student
    17 {
    18     int y,next;
    19 }e[N];
    20 void insert(int xx,int yy)
    21 {
    22     e[++len].next=Link[xx];
    23     Link[xx]=len;
    24     e[len].y=yy;
    25 }
    26 int bfs(int x)
    27 {
    28     memset(bok,0,sizeof(bok));
    29     int head=1,tail=2;
    30     ans[x]++;
    31     que[head]=x;
    32     bok[x]=1;
    33     while(head<tail)
    34     {
    35         for(int i=Link[que[head]];i;i=e[i].next)
    36         {
    37             if(!bok[e[i].y])
    38             {
    39                 ans[x]++;
    40                 bok[e[i].y]=1;
    41                 que[tail++]=e[i].y;
    42             }
    43         }
    44         head++;
    45     }
    46     return ans[x];
    47 }
    48 int main()
    49 {
    50     scanf("%d",&n);
    51     for(int i=1;i<=n;i++)
    52     {
    53         scanf("%d",&yy);
    54         insert(i,yy);
    55     }
    56     for(int i=1;i<=n;i++)
    57         cout<<bfs(i)<<endl;
    58 
    59     return 0;
    60 }
    暴力40分的code
    No matter how you feel, get up , dress up , show up ,and never give up.
  • 相关阅读:
    es6 常用方法
    vue HTTP 请求(vue-resource)
    vue 常用语法糖
    js中slice,SubString和SubStr的区别
    浅谈JavaScript中forEach与each
    vue 新版本 webpack 代理 跨域设置
    js 动态添加class封装(es6语法)
    jsonp promise 封装
    location.origin兼容IE
    给zTree的treeNode添加class
  • 原文地址:https://www.cnblogs.com/Kaike/p/10461544.html
Copyright © 2020-2023  润新知