洛谷 P1137 旅行计划

旅行计划

待证明这样dp的正确性。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
//Mystery_Sky
//
#define maxn 1000010
#define maxm 5000050
#define INF 0x3f3f3f3f;
queue <int> q;
int head[maxn], ind[maxn], cnt, dis[maxn];
int n, m;
struct Edge{
	int to, next;
}edge[maxn];

inline void add_edge(int u, int v)
{
	edge[++cnt].to = v;
	edge[cnt].next = head[u];
	head[u] = cnt;
}

inline void topo()
{
	for(int i = 1; i <= n; i++) {
		if(!ind[i]) {
			q.push(i);
			dis[i]++; 
		}
	}
	while(!q.empty()) {
		int u = q.front();
		q.pop();
		for(int i = head[u]; i; i = edge[i].next) {
			int v = edge[i].to;
			dis[v] = max(dis[v], dis[u]+1);
			if(!--ind[v]) q.push(v); 
		}
	}
}

int main() {
	scanf("%d%d", &n, &m);
	int u, v;
	for(int i = 1; i <= m; i++) {
		scanf("%d%d", &u, &v);
		add_edge(u, v);
		ind[v]++;
	}
	topo();
	for(int i = 1; i <= n; i++) printf("%d\n", dis[i]);
	return 0;
}
posted @ 2019-05-11 21:05  Mystery_Sky  阅读(89)  评论(0编辑  收藏  举报