POJ 2186 Popular Cows(强连通分量分解)

Popular Cows
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 34884 Accepted: 14218

Description

Every cow's dream is to become the most popular cow in the herd. In a herd of N (1 <= N <= 10,000) cows, you are given up to M (1 <= M <= 50,000) ordered pairs of the form (A, B) that tell you that cow A thinks that cow B is popular. Since popularity is transitive, if A thinks B is popular and B thinks C is popular, then A will also think that C is 
popular, even if this is not explicitly specified by an ordered pair in the input. Your task is to compute the number of cows that are considered popular by every other cow. 

Input

* Line 1: Two space-separated integers, N and M 

* Lines 2..1+M: Two space-separated numbers A and B, meaning that A thinks B is popular. 

Output

* Line 1: A single integer that is the number of cows who are considered popular by every other cow. 

Sample Input

3 3
1 2
2 1
2 3

Sample Output

1

Hint

Cow 3 is the only cow of high popularity. 

Source



思路:把牛看作顶点,对每个有序对(A,B)连一条有向边,那么,被其他所有牛认为是红人,也就是从其他顶点都可达的顶点。首先考虑枚举,把边反向储存,枚举当前顶点是否能到达所有顶点,但是时间复杂度确实O(N*M),是不可行的。接下来考虑强连通分量分解点击打开链接,显然分解之后至多有一个强连通分量满足题目的条件,且拓扑序为最大的,具体看代码。

时间复杂度:O(N+M)


代码:

//输入
int N,M;
int A[max_M],B[max_M];

void solve()
{
          V=N;

          for(int i=0;i<M;i++)
                     add_edge(A[i]-1,B[i]-1);

          int n=scc();//强连通分量个数
          
          //统计备选解的个数
          int u,sum=0;
          for(int v=0;v<V;v++)
          {
                     if(cmp[v]==n-1)//判断顶点拓扑序是否为n-1
                     {
                                 u=v;//u保存强连通分量中的一个值
                                 sum++;
                     }
           }
           
           //检查是否从所有点可达
           memset(used,0,sizeof(used));
           rdfs(u,0);//反向图的搜索,重用了强连通分量分解的代码
           for(int v=0;v<V;v++)
           {
                     if(!used[v])//从该点不可达
                     {
                                num=0;    
                                break;
                      }
            }

            printf("%d\n",num);
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值