0
点赞
收藏
分享

微信扫一扫

旅行计划。

mafa1993 2022-03-19 阅读 64
c++

题目描述
​ 小明要去一个国家旅游。这个国家有 N 个城市,编号为 1 至 N,并且有 M 条道路连接着,小明准备从其中一个城市出发,并只往东走到城市 i 停止。

​ 所以他就需要选择最先到达的城市,并制定一条路线以城市 i 为终点,使得线路上除了第一个城市,每个城市都在路线前一个城市东面,并且满足这个前提下还希望游览的城市尽量多。

​ 现在,你只知道每一条道路所连接的两个城市的相对位置关系,但并不知道所有城市具体的位置。现在对于所有的 i,都需要你为小明制定一条路线,并求出以城市 i 为终点最多能够游览多少个城市。

输入
​ 第 1 行为两个正整数 N,M。

​ 接下来 M 行,每行两个正整数 x,y,表示了有一条连接城市 x 与城市 y 的道路,保证了城市 x 在城市 y 西面。

输出
​ N 行,第 i 行包含一个正整数,表示以第 i 个城市为终点最多能游览多少个城市。

样例输入
5 6
1 2
1 3
2 3
2 4
3 4
2 5
样例输出
1
2
3
4
3
数据规模与约定
​ 时间限制:1 s

​ 内存限制:256 M

​ 100% 的数据保证 1≤n≤100000,1≤m≤200000

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;

struct edge {
    int to, next;
};

edge edg[200005];
int n, m, head[100005], in_degree[100005], ans[100005];

int main() {
    memset(head, -1, sizeof(head));
    cin >> n >> m;
    for (int i = 0; i < m; i++) {
        int a, b;
        cin >> a >> b;
        edg[i].to = b;
        edg[i].next = head[a];
        head[a] = i;
        in_degree[b]++;
    }
    queue<int> que;
    for (int i = 1; i <= n; i++) {
        if (in_degree[i] == 0) {
            que.push(i);
            ans[i] = 1;
        }
    }
    while (!que.empty()) {
        int t = que.front();
        que.pop();
        for (int i = head[t]; i != -1; i = edg[i].next) {
            int e = edg[i].to;
            ans[e] = max(ans[e], ans[t] + 1);
            in_degree[e]--;
            if (in_degree[e] == 0) {
                que.push(e);
            }
        }
    }
    for (int i = 1; i <= n; i++) {
        cout << ans[i] << endl;
    }
    return 0;
}
 
举报

相关推荐

0 条评论