NOIP 2013 车站分级

NOIP 2013 车站分级

洛谷传送门

JDOJ传送门

Description

一条单向的铁路线上,依次有编号为1, 2, …, n的n个火车站。每个火车站都有一个级别,最低为1级。现有若干趟车次在这条线路上行驶,每一趟都满足如下要求:如果这趟车次停靠了火车站x,则始发站、终点站之间所有级别大于等于火车站x的都必须停靠。(注意:起始站和终点站自然也算作事先已知需要停靠的站点)

例如,下表是5趟车次的运行情况。其中,前4趟车次均满足要求,而第5趟车次由于停靠了3号火车站(2级)却未停靠途经的6号火车站(亦为2级)而不满足要求。

img

现有m趟车次的运行情况(全部满足要求),试推算这n个火车站至少分为几个不同的级别。

Input

第一行包含2个正整数n, m,用一个空格隔开。
第i+1行(1≤i≤m)中,首先是一个正整数s_i(2≤s_i≤n),表示第i趟车次有s_i个停靠站;接下来有s_i个正整数,表示所有停靠站的编号,从小到大排列。每两个数之间用一个空格隔开。输入保证所有的车次都满足要求。

Output

输出只有一行,包含一个正整数,即n个火车站最少划分的级别数。

Sample Input

Sample Input I: 9 2 4 1 3 5 6 3 3 5 6 Sample Input II: 9 3 4 1 3 5 6 3 3 5 6 3 1 5 9

Sample Output

Sample Output I: 2 Sample Output II: 3

HINT

对于20%的数据,1 ≤ n, m ≤ 10;

对于50%的数据,1 ≤ n, m ≤ 100;

对于100%的数据,1 ≤ n, m ≤ 1000。


最优解声明:


题解:

一道典型的层次类问题。考虑拓扑排序。

拓扑排序特别擅长解决层次类问题和依赖性问题。

就是由层次低的向层次高的点建边,最后整个图的拓扑深度就是答案。(因为蒟蒻代码dep初值为0,所以最后加一即可)

代码:

#include<cstdio>
#include<algorithm>
#include<queue>
#include<cstring>
#define R register
using namespace std;
char *p1,*p2,buf[100000];
#define nc() (p1==p2 && (p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++)
inline int read()
{
    int x=0,f=1;
    char ch=nc();
    while(ch<48||ch>57)
    {
        if(ch=='-')
            f=-1;
        ch=nc();
    }
    while(ch>=48&&ch<=57)
        x=x*10+ch-48,ch=nc();
   	return x*f;
}
const int maxn=1002;
int n,m,ans;
int a[maxn],du[maxn],dep[maxn];
bool v[maxn],vis[maxn][maxn];
queue<int> q;
int tot,head[maxn],nxt[maxn*maxn],to[maxn*maxn];
inline void add(int x,int y)
{
    to[++tot]=y;
    nxt[tot]=head[x];
    head[x]=tot;
}
inline void topsort()
{
    for(R int i=1;i<=n;i++)
        if(!du[i])
            q.push(i);
    while(!q.empty())
    {
        int x=q.front();
        q.pop();
        for(R int i=head[x];i;i=nxt[i])
        {
            int y=to[i];
            dep[y]=dep[x]+1;
            ans=max(ans,dep[y]);
            du[y]--;
            if(!du[y])
                q.push(y);
        }
    }
}
int main()
{
    n=read();m=read();
    for(R int i=1;i<=m;i++)
    {
        int k;
        k=read();
        memset(v,0,sizeof(v));
        for(R int j=1;j<=k;j++)
        {
            a[j]=read();
            v[a[j]]=1;
        }
        for(R int j=a[1]+1;j<=a[k];j++)
            if(!v[j])
                for(R int l=1;l<=k;l++)
                    if(!vis[j][a[l]])
                    {
                        add(j,a[l]);
                        du[a[l]]++;
                        v[j]=1;
                        vis[j][a[l]]=1;
                    }
    }
    topsort();
    printf("%d",ans+1);
    return 0;
}
原文地址:https://www.cnblogs.com/fusiwei/p/13886670.html