2023-8-31 有边数限制的最短路(bellman-ford)

题目链接:有边数限制的最短路

2023-8-31 有边数限制的最短路(bellman-ford)_第1张图片

#include 
#include 
#include 

using namespace std;

const int N = 510, M = 10010;

int n, m, k;
int dist[N], backup[N];

// 存放边的信息
struct Edge
{
    int a, b, w;
}edges[M];

void bellman_ford()
{
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0;
    
    for(int i = 0; i < k; i ++)
    {
        memcpy(backup, dist, sizeof dist);
        
        for(int i = 0; i < m; i ++)
        {
            int a = edges[i].a, b = edges[i].b, w = edges[i].w;
            dist[b] = min(dist[b], backup[a] + w);
        }
    }
}

int main()
{
    cin >> n >> m >> k;
    for(int i = 0; i < m; i++)
    {
        int a, b, w;
        cin >> a >> b >> w;
        edges[i] = {a, b, w};
    }
    
    bellman_ford();
    if(dist[n] > 0x3f3f3f3f / 2) cout << "impossible" << endl;
    else cout << dist[n] <

你可能感兴趣的:(算法,图论)