851. Find the shortest path in spfa

Given a directed graph with n points and m edges, there may be multiple edges and self-loops in the graph, and the edge weights may be negative.

Please find the shortest distance from point 1 to point n. If it is impossible to get from point 1 to point n, output impossible.

The data guarantees that there are no negative weight loops.

Input format
The first line contains integers n and m.

Each of the next m lines contains three integers x, y, z, indicating that there is a directed edge from point x to point y, and the edge length is z.

Output Format
Output an integer representing the shortest distance from point 1 to point n.

If the path does not exist, output impossible.

The data range is
1≤n, m≤105, and
the absolute value of the side length involved in the figure does not exceed 10000.

Input sample:
3 3
1 2 5
2 3 -3
1 3 4
Output sample:
2

insert image description here

#include<bits/stdc++.h>
using namespace std;
const int N = 100010;
int h[N], e[N], ne[N], w[N], idx;
int dist[N];
bool vis[N];
int n, m;

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

int spfa()
{
    
    
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0;
    queue<int> q;
    q.push(1);
    vis[1] = true;
    
    while(q.size()) {
    
    
        int t = q.front();
        q.pop();
        vis[t] =false;
        
        for(int i = h[t]; i != -1; i = ne[i]) {
    
    
            int j = e[i];
            if(dist[j] > dist[t] + w[i]) {
    
    
                dist[j] = dist[t] + w[i];
                if(!vis[j]) {
    
    
                    q.push(j);
                    vis[j] = true;
                }
            }
        }
    }
    
    if(dist[n] == 0x3f3f3f3f) return -1;
    else return dist[n];
}

int main()
{
    
    
    memset(h, -1, sizeof h);
    
    cin >> n >> m;
    int a, c, b;
    for(int i=0; i<m; i++) {
    
    
        cin >> a >> b  >> c;
        add(a, b, c);
    }
    
    int t = spfa();
    if(t == -1) puts("impossible");
    else cout << t << endl;
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324134338&siteId=291194637