zoukankan      html  css  js  c++  java
  • [NOIP2015] 提高组 洛谷P2661 信息传递

    题目描述

    有n个同学(编号为1到n)正在玩一个信息传递的游戏。在游戏里每人都有一个固定的信息传递对象,其中,编号为i的同学的信息传递对象是编号为Ti同学。

    游戏开始时,每人都只知道自己的生日。之后每一轮中,所有人会同时将自己当前所知的生日信息告诉各自的信息传递对象(注意:可能有人可以从若干人那里获取信息,但是每人只会把信息告诉一个人,即自己的信息传递对象)。当有人从别人口中得知自己的生日时,游戏结束。请问该游戏一共可以进行几轮?

    输入输出格式

    输入格式:

    输入共2行。

    第1行包含1个正整数n表示n个人。

    第2行包含n个用空格隔开的正整数T1,T2,……,Tn其中第i个整数Ti示编号为i

    的同学的信息传递对象是编号为Ti的同学,Ti≤n且Ti≠i

    数据保证游戏一定会结束。

    输出格式:

    输出共 1 行,包含 1 个整数,表示游戏一共可以进行多少轮。

    输入输出样例

    输入样例#1:
    5
    2 4 2 3 1
    输出样例#1:
    3

    说明

    样例1解释

    游戏的流程如图所示。当进行完第 3 轮游戏后, 4 号玩家会听到 2 号玩家告诉他自

    己的生日,所以答案为 3。当然,第 3 轮游戏后, 2 号玩家、 3 号玩家都能从自己的消息

    来源得知自己的生日,同样符合游戏结束的条件。

    对于 30%的数据, n ≤ 200;

    对于 60%的数据, n ≤ 2500;

    对于 100%的数据, n ≤ 200000。

    其实暴力DFS就可解。

    然而我写了tarjan,利用缩点后点集的大小来判断答案。

     1 /**/
     2 #include<iostream>
     3 #include<cstdio>
     4 #include<cmath>
     5 #include<cstring>
     6 #include<algorithm>
     7 using namespace std;
     8 const int mxn=230000;
     9 int v[mxn];
    10 int dtime=0;
    11 bool inst[mxn]; 
    12 int st[mxn],top;
    13 int low[mxn],dfn[mxn];
    14 //
    15 int belone[mxn],cnt=0;
    16 int dg[mxn];
    17 //
    18 int n;
    19 void tarjan(int u){
    20     low[u]=dfn[u]=++dtime;
    21     st[++top]=u;
    22     inst[u]=1;
    23     //
    24     if(!dfn[v[u]]){
    25         tarjan(v[u]);
    26         low[u]=min(low[u],low[v[u]]);
    27     }
    28     else if(inst[v[u]])
    29         low[u]=min(low[u],dfn[v[u]]);
    30     //
    31     if(low[u]==dfn[u]){
    32         ++cnt;
    33         int w;
    34         do{
    35             w=st[top--];
    36             dg[cnt]++;
    37             inst[w]=0;
    38         }while(w!=u);
    39     }
    40     return;
    41 }
    42 int main(){
    43     scanf("%d",&n);
    44     int i,j;
    45     for(i=1;i<=n;i++){
    46         scanf("%d",&v[i]);
    47     }
    48     for(i=1;i<=n;i++){
    49         if(!dfn[i])tarjan(i);
    50     }
    51     int ans=5000000;
    52     for(i=1;i<=cnt;i++) {if(dg[i]<ans && dg[i]!=1)ans=dg[i];}
    53     printf("%d
    ",ans);
    54     return 0;
    55 }
  • 相关阅读:
    Codeforces 834D The Bakery
    hdu 1394 Minimum Inversion Number
    Codeforces 837E Vasya's Function
    Codeforces 837D Round Subset
    Codeforces 825E Minimal Labels
    Codeforces 437D The Child and Zoo
    Codeforces 822D My pretty girl Noora
    Codeforces 799D Field expansion
    Codeforces 438D The Child and Sequence
    Codeforces Round #427 (Div. 2) Problem D Palindromic characteristics (Codeforces 835D)
  • 原文地址:https://www.cnblogs.com/SilverNebula/p/6078791.html
Copyright © 2011-2022 走看看