P1983 [NOIP2013 普及组] 车站分级

题目描述

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

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

在这里插入图片描述

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

输入格式

第一行包含 2 个正整数 n, m,用一个空格隔开。

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

输出格式

一个正整数,即 n 个火车站最少划分的级别数。

思路

本来不想把题目的图拷下来的,但是同机房的巨爷已经磨刀霍霍向爹娘了
topsort就可以,重点在于建图。
建图参考代码:

	cin>>n>>m;
	for (int i=1;i<=m;i++)
	{
    
    
		cin>>x;
		for (int j=1;j<=x;j++)
		{
    
    
			cin>>o[j];
		}
		int u=o[1]+1;
		for (int j=2;j<=x;j++)
		{
    
    
			while (u!=o[j])
			{
    
    
				for (int k=1;k<=x;k++) if (!w[u][o[k]]) w[u][o[k]]=1,add(u,o[k]),rd[o[k]]++;
				u++;
			}
			u++;
		}
	}

code:

#include<iostream>
#include<queue>
using namespace std;
int n,m,head[1001],tot=1,rd[1001];
int book[1001];
int x,y;
struct f{
    
    
	int to,next;
} a[1001*1001];
void add(int x,int y)
{
    
    
	a[tot].to=y;
	a[tot].next=head[x];
	head[x]=tot++;
	return;
}
bool w[1001][1001];
int o[1001];
queue<int> wj;
int main()
{
    
    
	cin>>n>>m;
	for (int i=1;i<=m;i++)
	{
    
    
		cin>>x;
		for (int j=1;j<=x;j++)
		{
    
    
			cin>>o[j];
		}
		int u=o[1]+1;
		for (int j=2;j<=x;j++)
		{
    
    
			while (u!=o[j])
			{
    
    
				for (int k=1;k<=x;k++) if (!w[u][o[k]]) w[u][o[k]]=1,add(u,o[k]),rd[o[k]]++;
				u++;
			}
			u++;
		}
	}
	for (int j=1;j<=n;j++)
	{
    
    
		if (!rd[j])
		{
    
    
			book[j]=1;
			wj.push(j);
		}
	}
	while (wj.size())
	{
    
    
		x=wj.front();
		wj.pop();
		for (int i=head[x];i;i=a[i].next)
		{
    
    
			rd[a[i].to]--;
			book[a[i].to]=max(book[a[i].to],book[x]+1);
			if (rd[a[i].to]==0)
			{
    
    
				wj.push(a[i].to);
			}
		}
	}
	int s=0;
	for (int i=1;i<=n;i++)
	{
    
    
		s=max(s,book[i]);
	}
	cout<<s;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_49843717/article/details/112387552