[2020.10.28 SSL popularization simulation tournament T6] [POPULAR popular cow] [DFS]

Title description

Every cow has a dream: to become the most popular cow in a group! In a herd of N(1<=N<=10,000) cows, give you M(1<=M<=50,000) two-tuples (A, B) to indicate that A thinks B is popular. Since popularity is transferable, if A thinks B is popular, and B thinks C is popular, A will also think C is popular, even if this is not a very clear rule. Your task is to count the number of cows that are liked by all other cows.

enter

In the first line, two numbers, N and M. Lines 2~M+1 have two numbers in each line, A and B, indicating that A thinks B is popular.

Output

A number, the number of cows considered popular by all other cows.

Input sample

3
1 2
2 1
2 3

Sample output

1

Sample description

Cow No. 3 is the only one considered famous by all other cows.

Description

Data range limit
1 <= N <= 10, 000 1<=N<=10,0001<=N<=10,000
1 < = M < = 50 , 000 1<=M<=50,000 1<=M<=50,000

analysis

O (n 2) O (n ^ 2) O ( n2 )Over a million who can be me! ?

Connect the edges directly to the adjacent table, and then search for each cow linked to it. If the number reaches n-1, it means that ta is a POPULAR cow.
Then add it to the ans array, and finally count the ans array

Upload code

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;

int n,m,v[100001],ans[100001],s;
int h[100001],tot;

struct node
{
    
    
	int x,y;
}e[100001];

void add(int x,int y)
{
    
    
	tot++;
	e[tot].x=y;
	e[tot].y=h[x];
	h[x]=tot;
}

void dfs(int x)
{
    
    
	v[x]=1;
	for(int i=h[x];i>0;i=e[i].y)
	{
    
    
		int t=e[i].x;
		if(!v[t])
		{
    
    
			ans[t]++;
			dfs(t);
		}
	}
}

int main()
{
    
    
	cin>>n>>m;
	for(int i=1;i<=m;i++)
	{
    
    
		int a,b;
		cin>>a>>b;
		add(a,b);
	}
	for(int i=1;i<=n;i++)
	{
    
    
		memset(v,0,sizeof(v)); 
		dfs(i);
	}
	for(int i=1;i<=n;i++)
	{
    
    
		if(ans[i]==n-1) s++;
	}
	cout<<s;
	return 0;
}

Finished this question smoothly AK.

Guess you like

Origin blog.csdn.net/dglyr/article/details/109352409