求助最长路!!!
  • 板块P1807 最长路
  • 楼主4607wjq
  • 当前回复0
  • 已保存回复0
  • 发布时间2023/10/16 15:59
  • 上次更新2023/11/2 13:27:39
查看原帖
求助最长路!!!
641047
4607wjq楼主2023/10/16 15:59

拓扑排序。在判断无解时:

  • if (dist[n] == -0x3f3f3f3f3f3f3f3f) 78pts
  • if (dist[n] <= -0x3f3f3f3f3f3f3f3f / 2) 100pts

如果无解,那么广搜完全不会搜到点 nn,否则可以一路回溯,最终到 11。那么 distndist_n 完全不会变啊。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>

using namespace std;

const int N = 1e4 + 10, M = 5e4 + 10, mod = 10000;

int h[N], e[M], ne[M], w[M], idx;
int in[N], m, n, a, b, c;
long long dist[N];

void add(int a, int b, int c)
{
    e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx ++;
}

void topsort()
{
    memset(dist, -0x3f, sizeof dist);
    dist[1] = 0;
    
    queue<int> q;
    for (int i = 2; i <= n; i ++ )
        if (!in[i])
            q.push(i);
    while (q.size())
    {
        int u = q.front(); q.pop();
        for (int i = h[u]; ~i; i = ne[i])
        {
            int j = e[i];
            in[j] --;
            if (!in[j])
                q.push(j);
        }
    }
    
    q.push(1);
    while (q.size())
    {
        int u = q.front(); q.pop();
        
        for (int i = h[u]; ~i; i = ne[i])
        {
            int j = e[i];
            
            in[j] --;
            dist[j] = max(dist[j], dist[u] + w[i]);
            
            if (!in[j])
                q.push(j);
        }
    }
}

int main()
{
    memset(h, -1, sizeof h);
    
    cin >> n >> m;
    
    while (m -- )
    {
        scanf("%d%d%d", &a, &b, &c);
        add(a, b, c);
        in[b] ++;
    }
    
    topsort();
    
    if (dist[n] <= -0x3f3f3f3f3f3f3f3f / 2)
        puts("-1");
    else cout << dist[n];
    
    return 0;
}
2023/10/16 15:59
加载中...