洛谷 P1983 车站分级(拓扑排序)

https://www.luogu.com.cn/problem/P1983

思路

对于每一趟车,将其经过的车站中,停靠的和不停靠的连一条边,注意边的去重,要双向标记,不然有个点会超时,这样拓扑排序递推一下就能分级出来

代码
#include 
using namespace std;
struct node{
	int id;
	int level;
};

const int N = 1005;

int n, m;
int ru[N];
vector <int> g[N];
int tong[N][N];
queue <node> q;
int flag[N];
int ting[N];

int main() {
	//freopen("in.txt", "r", stdin);
	cin >> n >> m;
	for (int i = 0; i < m; i++) {
		memset(flag, 0, sizeof(flag));
		memset(ting, 0, sizeof(ting));
		int k, t; cin >> k;
		for (int j = 1; j <= k; j++) {
			cin >> ting[j];
			flag[ting[j]] = 1;
		}
		for (int j = ting[1]; j <= ting[k]; j++) {
			if (!flag[j])
			for (int p = ting[1]; p <= ting[k]; p++) {
				if (flag[p] && !tong[j][p]) {
					ru[p]++;
					tong[j][p] = 1;
					tong[p][j] = 1;
					g[j].push_back(p);
				}
			}
		}
	}

	for (int i = 1; i <= n; i++) {
		// cout << i << " " << ru[i] << endl;
		if (!ru[i]) {
			q.push((node){i, 1});
		}
	}
	int mosttop = 1;
	while (!q.empty()) {
		node fro = q.front();
		q.pop();
		//vis[fro.id] = 1;
		// cout << "-----------------------" << endl;
		// cout << "fro: " << fro.id << " " << fro.level << endl;
		for (int j = 0; j < g[fro.id].size(); j++) {
			ru[g[fro.id][j]]--;
			// cout << g[fro.id][j] << " " << ru[g[fro.id][j]] << endl;
			if (!ru[g[fro.id][j]]) {
				q.push((node){g[fro.id][j], fro.level + 1});
				mosttop = max(mosttop, fro.level + 1);
			}
		}
	}
	cout << mosttop << endl;
	return 0;
}

你可能感兴趣的:(随笔,code,图论)