[题解]洛谷P1983 车站分级

一道经典的拓扑排序的题目

原题链接

首先,对于一条路径中的点,没出现的一定比出现了的低级,所以在这两个点间连边

然后toposort算最长链

代码:

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<queue>
using namespace std;
const int MAX = 10100;

int n,m,rud[MAX]={0};
int first[MAX];
int ans=0;

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

struct edge{
    int u,v,next;
}e[MAX];

struct node{
    int u,len;
};

int cnt=0;
void insert(int u,int v){
    ++cnt;e[cnt].u=u;e[cnt].v=v;e[cnt].next=first[u];first[u]=cnt;
}

node makenode(int u,int len){
    node qwq;
    qwq.len=len;qwq.u=u;
    return qwq;
}

queue<node> q;
void topo(){
    for(int i=1;i<=n;i++){
        if(rud[i]==0)q.push(makenode(i,1));
    }
    ans=1;
    while(!q.empty()){
        int u=q.front().u,len=q.front().len;
        q.pop();
        for(int i=first[u];i!=-1;i=e[i].next){
            int v=e[i].v;
            rud[v]--;
            if(rud[v]==0){
                q.push(makenode(v,len+1));
                ans=max(ans,len+1);
            }
        }
    }
}

int con[MAX][MAX]={0};
int main(){
    memset(first,-1,sizeof(first));
    n=read();m=read();
    int temp[MAX],stop[MAX];
    for(int i=1;i<=m;i++){
        memset(stop,0,sizeof(stop));
        int tot=read();
        for(int j=1;j<=tot;j++){
            temp[j]=read();
            stop[temp[j]]=1;
        }
        for(int j=temp[1];j<=temp[tot];j++){
            if(!stop[j]){
                for(int k=1;k<=tot;k++){
                    if(!con[j][temp[k]]){
                        con[j][temp[k]]=1;
                        insert(j,temp[k]);
                        rud[temp[k]]++;
                    }
                }
            }
        }
    }
    topo();
    printf("%d",ans);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/sjrb/p/10391242.html