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.
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.
* 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);
}