旅行商(TSP)

旅行商(TSP)


Description

Shrek is a postman working in the mountain, whose routine work is sending mail to n villages. Unfortunately, road between villages is out of repair for long time, such that some road is one-way road. There are even some villages that can’t be reached from any other village. In such a case, we only hope as many villages can receive mails as possible.

Shrek hopes to choose a village A as starting point (He will be air-dropped to this location), then pass by as many villages as possible. Finally, Shrek will arrived at village B. In the travelling process, each villages is only passed by once. You should help Shrek to design the travel route.

Input

There are 2 integers, n and m, in first line. Stand for number of village and number of road respectively.

In the following m line, m road is given by identity of villages on two terminals. From v1 to v2. The identity of village is in range [1, n].

Output

Output maximum number of villages Shrek can pass by.

Example

Input

4 3
1 4
2 4
4 3

Output

3

Restrictions

1 <= n <= 1,000,000

0 <= m <= 1,000,000

These is no loop road in the input.

Time: 2 sec

Memory: 256 MB

Hints

Topological sorting

  1. 原理与要点: 按照拓扑排序的方法对图进行遍历,遍历的过程中记录路径长度,取一个最大值即得到答案。
    - 预处理出所有点的入度\(deg[i]\),起初把所有入度为0的点入队
    • 取出队头节点x,答案与x的路径长度取一个最大值,对于从x出发的每条边(x,y)把\(deg[y]\)减1。若被减为0,则把y入队,y的路径长度为x的路径长度加1。
    • 重复上述步骤直至队列为空,此时所取得的最大值即为答案
  2. 遇到的问题:
  3. 时间和空间复杂度: 时间复杂度\(O(n+m)\),空间复杂度\(O(n+m)\)
#include "cstdio"
#include "cmath"

using namespace std;
const int maxn = 1e6 + 100;
const int mod = 1e6 - 10;

const int SZ = 1<<20;  //快速io
struct fastio{
    char inbuf[SZ];
    char outbuf[SZ];
    fastio(){
        setvbuf(stdin,inbuf,_IOFBF,SZ);
        setvbuf(stdout,outbuf,_IOFBF,SZ);
    }
}io;
int ver[maxn], Next[maxn], head[maxn], deg[maxn];
int tot, n;
int ansmax = 0;
struct node {
    int x, length;
};
node q[maxn];

void add(int x, int y) {
    ver[++tot] = y, Next[tot] = head[x], head[x] = tot;
    deg[y]++;
}

void topsort() {
    int from = 0, to = 0;
    for (int i = 1; i <= n; i++) {
        if (deg[i] == 0) {
            q[to] = {i, 1};
            to = (to + 1) % mod;
        }
    }
    while (from != to) {
        node x = q[from++];
        from %= mod;
        if (x.length > ansmax) ansmax = x.length;
        for (int i = head[x.x]; i; i = Next[i]) {
            int y = ver[i];
            if (--deg[y] == 0) {
                q[to] = {y, x.length + 1};
                to = (to + 1) % mod;
            }
        }
    }
}

int main() {
    int m;
    scanf("%d %d", &n, &m);
    int u, v;
    for (int i = 0; i < m; i++) {
        scanf("%d %d", &u, &v);
        add(u, v);
    }
    topsort();
    printf("%d\n", ansmax);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值