Address https://www.acwing.com/problem/content/description/855/
Given a point n and m edges directed graph, there may be multiple edges drawing and loopback, the edge weights may be negative.
After you find the shortest distance at most k edges, and if you can not go from point n No. 1 point, 1-point output from the impossible to the number n points.
Note: there may be negative cycles figure.
Input Format
The first line contains three integers n, m, k.
Subsequently m rows, each row containing three integers x, y, Z, it indicates the presence of a point x to point y directed edge from a side length of z.
Output Format
Output an integer, k represents the shortest distance through the up edges from point 1 to point number n.
If the path does not satisfy the condition, it outputs "impossible".
data range
. 1 ≤ n- , K ≤ 500 1 ≦ n, k≤500,
. 1 ≤ m ≤ 10000 1≤m≤10000,
any side length absolute value is not more than 10,000.
Sample input: . 3 . 3 . 1 . 1 2 . 1 2 . 3 . 1 . 1 . 3 . 3 Sample output: 3
solution
#include <iostream> #include <vector> #include <memory.h> using namespace std; const int N = 510 ; vector<vector<pair<int, int>>> v; int dist[N]; int back[N]; int n, m, k; /* 3 3 1 1 2 1 2 3 1 1 3 3 */ void solveInner(int back[]) { for (int i = 0; i < v.size(); i++) { for (int j = 0; j < v[i].size(); j++) { int a = i; int b = v[i][j].first; int w = v[i][j].second; if (dist[b] > back[a] + w) { dist[b] = back[a] + w; } } } } int solve() { memset(dist, 0x3f, sizeof(dist)); dist[1] = 0; // for n-th wheel for ( int I = 0 ; I <K; I ++ ) { memcpy(back, dist, sizeof dist); solveInner (back); } if (dist[n] > 0x3f3f3f3f / 2) return -1; return dist[n]; } int main () { scanf("%d%d%d",&n,&m,&k); //cin >> n >> m >> k; v.resize(n + 1); for (int i = 0; i < m; i++) { int a, b, c; //cin >> a >> b >> c; scanf("%d%d%d",&a,&b,&c); v[a].push_back({ b,c }); } int K = solve (); if (ret == -1) printf("impossible"); else printf("%d\n",ret); return 0; }