2020 cattle off winter training camp algorithm base 6 B title

Map

There are N points a directed graph, each edge point out only one
number you need to find a simple FIG longest path containing points (1≤N≤1,000,000)

Enter a description:

A number N of the first row
next N rows, each row a positive integer, the i + 1 row numbers i-th point represents the number of end edges
(the start point of the reference numeral 1)
Output Description:

A digit line, the path length of the longest simple


This question is first determined at various points in the topological sort (actually branched) longest length, then no topology is traversing point to point on the ring, again traversed to identify these points, find the point on the ring size of the longest length and can be connected to the ring,
why should not traverse through all the points, because this problem FIG communication may not be, that there may be a plurality of rings;

Code:

#include<bits/stdc++.h>
#define ll long long
#define pa pair<int,int>
#define lson k<<1
#define rson k<<1|1
#define inf 0x3f3f3f3f
//ios::sync_with_stdio(false);
using namespace std;
const int N=1000100;
const int M=1000100;
const ll mod=998244353;
int in[N];
int n;
struct Node{
	int to,nex;
}edge[N*2];
int head[N];
int cnt;
void add(int p,int q){
	edge[cnt].to=q;
	edge[cnt].nex=head[p];
	head[p]=cnt++;
}
int dp[N];
queue<int>qu;
bool vis[N];
void bfs(){
	while(!qu.empty()){
		int u=qu.front();
		vis[u]=true;
		qu.pop();
		for(int i=head[u];~i;i=edge[i].nex){
			int v=edge[i].to;
			dp[v]=max(dp[v],dp[u]+1);
			in[v]--;
			if(in[v]==0) qu.push(v);
		}
	}
}
int sum,mmax;
bool f[N];
void dfs(int p){
	f[p]=true;
	mmax=max(mmax,dp[p]);//最长支链大小
	sum++;//环的大小 
	for(int i=head[p];~i;i=edge[i].nex){
		int u=edge[i].to;
		if(!f[u]) dfs(u);
	}
}
int main(){
	ios::sync_with_stdio(false);
	cin>>n;
	memset(head,-1,sizeof(head));
	for(int i=1;i<=n;i++){
		int q;
		cin>>q;
		add(i,q);
		in[q]++;//入度
	}
	for(int i=1;i<=n;i++){
		dp[i]=1;
		if(in[i]==0) qu.push(i);
	}
	bfs();
	int ans=0;
	for(int i=1;i<=n;i++){
		if(!vis[i]&&!f[i]){
			sum=mmax=0;
			dfs(i);
			ans=max(ans,sum+mmax-1);
		}
	}
	cout<<ans<<endl;
	return 0;
}
Published 203 original articles · won praise 45 · views 7852

Guess you like

Origin blog.csdn.net/qq_44291254/article/details/104345509