【Logu】P1137 Travel Plan

【Logu】P1137 Travel Plan

Title description

Xiao Ming is going to travel to a country. There are N cities in this country, numbered 1 to N, and connected by M roads. Xiao Ming is going to start from one of these cities and only go east to stop at city i.

So he needs to choose the first city to arrive, and make a route with city i as the end point, so that except for the first city on the route, every city is east of the previous city on the route, and he wants to visit under this premise. As many cities as possible.

Now, you only know the relative position of the two cities connected by each road, but you don't know the specific positions of all cities. Now for all i, you need to make a route for Xiao Ming and find out how many cities you can visit with city i as the destination.

Input format

The first line is two positive integers N and M.

In the next M lines, each line has two positive integers x, y, indicating that there is a road connecting city x and city y, ensuring that city x is west of city y.

Output format

N line, the i-th line contains a positive integer, indicating the maximum number of cities that can be visited with the i-th city as the destination.

Sample input and output

enter
5 6
1 2
1 3
2 3
2 4
3 4
2 5
Output
1
2
3
4
3

Instructions/tips

You can get the above answer if you choose to start from city 1.

For 20% of the data, N ≤ 100;

For 60% of the data, N ≤ 1000;

For 100% data, N ≤ 100000 and M ≤ 200000.

Ideas

Topological sorting, using an array to store the maximum number of cities visited to each point.

Code

#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
int ans[100010],tot=0,n,m,head[100010],ins[100010];
struct jgt
{
    
    
	int x,y,nxt;
}f[200010];
queue<int> q;
void topsort()
{
    
    
	int i;
	for(i=1;i<=n;i++)
		if(!ins[i])
		{
    
    
			q.push(i);
			ans[i]=1;
		}
	for(;!q.empty();q.pop())
	{
    
    
		for(i=head[q.front()];i;i=f[i].nxt)//更新入度 
		{
    
    
			ins[f[i].y]--;
			ans[f[i].y]=max(ans[f[i].y],ans[q.front()]+1);
			if(!ins[f[i].y])//当能够到达这个点的所有点都遍历过后将这个点加入队列
				q.push(f[i].y);
		}
	}
	return;
}
int main()
{
    
    
	int i,j,t;
	memset(ans,0,sizeof(ans));
	memset(ins,0,sizeof(ins));
	scanf("%d%d",&n,&m);
	for(i=1;i<=m;i++)
	{
    
    
		tot++;
		scanf("%d%d",&f[tot].x,&f[tot].y);
		f[tot].nxt=head[f[tot].x];
		head[f[tot].x]=tot;
		ins[f[tot].y]++;
	}
	topsort();
	for(i=1;i<=n;i++)
		printf("%d\n",ans[i]);
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_46975572/article/details/112910373