Traversal solution to a problem P3916 map

Park synchronization blog

Original title link

Briefly meaning of the questions:

Began to seek from each point, the maximum number of points that can be reached.

We just found a property, this problem becomes quite simple.

You want, if you start to go from each point, each traverse, certainly unscientific.

Because it is a directed graph, so the current point x x maximum number that can be reached Y Y , we reverse the construction drawing, Y Y must also be able to go x x . Moreover, they are able to come Y Y point, after reverse FIG construction, Y Y can come to them; if you can not come Y Y point, the reverse construction Figure, Y Y can not come to them.

Therefore, we reverse the construction drawing, descending to traverse.

time complexity: THE ( n ) O (n) .

Actual score: 100 p t s 100pts .

#pragma GCC optimize(2)
#include<bits/stdc++.h>
using namespace std;

const int N=1e5+1;

inline int read(){char ch=getchar();int f=1;while(ch<'0' || ch>'9') {if(ch=='-') f=-f; ch=getchar();}
	int x=0;while(ch>='0' && ch<='9') x=(x<<3)+(x<<1)+ch-'0',ch=getchar();return x*f;}

int n,m; int h[N]; //每个点的答案
vector<int>G[N];

inline void dfs(int dep,int top) {
	if(h[dep]) return;
	h[dep]=top; //记录答案的同时做哈希,因为先遍历到的答案肯定比后遍历的答案优
	for(int i=0;i<G[dep].size();i++)
		dfs(G[dep][i],top);
}

int main(){
	n=read(),m=read(); while(m--) {
		int x=read(),y=read();
		G[y].push_back(x);
	} for(int i=n;i>=1;i--)
		if(!h[i]) dfs(i,i);
	for(int i=1;i<=n;i++) printf("%d ",h[i]);	
	return 0;
}

Published 44 original articles · won praise 61 · views 4096

Guess you like

Origin blog.csdn.net/bifanwen/article/details/105322676