[P1137] Luo Gu travel plans topological sorting []

Title Description

Xiao Ming to go to a national tour. The country has #NN cities, numbered 11 to NN, and there are roads connecting the MM, Xiao Ming ready to depart from one of the cities, and only go east city i stopped.

So he needs to select a city first to arrive, and to develop a route to the city i is the end, so that in addition to the first city, every city east of the city in front of a line on the line, and to meet this premise also want to visit city ​​as much as possible.

Now, you only know the relative positional relationship between the two cities every road is connected, but does not know the specific location of all cities. Now for all i, you need to develop a course for the Bob and urban ii obtained for the end of the maximum number of cities to visit.

Input Format

11 is the two positive integers N, MN, M.

Next MM lines of two positive integers x, yx, y, shows there is a connection with the city yy xx city roads, to ensure that the city xx yy west of the city.

Output Format

NN line, ii the first line contains a positive integer, expressed in the first ii cities for the end of the maximum number of cities can tour.

Sample input and output

Input # 1

5 6
1 2
1 3
2 3
2 4
3 4
2 5

Output # 1

1
2
3
4
3

Analysis & Description:

This question is a topological sorting . Each point is that it answers to all predecessor nodes answers plus 1, i.e., F [I] = max (F [I], F [J] + 1'd) ; with the adjacency list stored figure, topological sorting (count bit template) while doing little DP enough.

CODE:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>  //STL队列
using namespace std;
int n,m,dis[100010],in[100010],tot,f[100010];
queue<int>q;  //创建队列
struct node{
    int to,next;
}a[400010];
int main()
{
	ios::sync_with_stdio(false);
    cin>>n>>m;
    for(int i=1;i<=m;i++)
    {
        int x,y;
        ios::sync_with_stdio(false);
        cin>>x>>y;
        a[++tot].to=y;  //邻接表
        a[tot].next=dis[x];
        dis[x]=tot;
        in[y]++;
    }
    for(int i=1;i<=n;i++)
    if(!in[i])
    {  //拓扑排序部分
        f[i]=1;
        q.push(i);
    }
    while(!q.empty())
    {
        int cnt=q.front();q.pop();
        memset(in,0,sizeof(in));
        for(int i=dis[cnt];i;i=a[i].next)
        {
            f[a[i].to]=max(f[a[i].to],f[cnt]+1);  //前驱节点+1
            if(!--in[a[i].to])
			q.push(a[i].to);    
        }   
    }
    for(int i=1;i<n;i++) 
	cout<<f[i]<<endl;  //特别注意输出
	cout<<f[n];
}
Published 35 original articles · won praise 22 · views 586

Guess you like

Origin blog.csdn.net/dgssl_xhy/article/details/104024183