C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSIZE 100010
#define INF 0x3f3f3f3f
int n, m, dist[MAXSIZE], cnt[MAXSIZE];
int head, tail, queue[MAXSIZE], inQueue[MAXSIZE];
struct Edge {
int weight_, to_;
struct Edge *next_;
} *edges[MAXSIZE];
void init() {
scanf("%d%d", &n, &m);
int x, y, z;
for (int i = 0; i < m; ++i) {
scanf("%d%d%d", &x, &y, &z);
struct Edge *s = (struct Edge*) calloc(1, sizeof(struct Edge));
s->to_ = y;
s->weight_ = z;
s->next_ = edges[x];
edges[x] = s;
}
memset(dist, 0x3f, sizeof(dist));
head = -1, tail = -1;
}
int empty() {
return head == tail ? 1 : 0;
}
void push(int val) {
queue[++tail] = val;
}
void pop() {
++head;
}
int front() {
return queue[head+1];
}
int SPFA(int start) {
dist[start] = 0;
push(start);
inQueue[start] = 1;
++cnt[start];
while (!empty()) {
int u = front();
pop();
inQueue[u] = 0;
struct Edge *p = edges[u];
while (p != NULL) {
int v = p->to_, w = p->weight_;
p = p->next_;
if (dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
if (!inQueue[v]) {
push(v);
inQueue[v] = 1;
++cnt[v];
if (cnt[v] >= n) {
return 0;
}
}
}
}
}
return 1;
}
int main() {
init();
if (SPFA(1) && dist[n] < INF/2) {
printf("%d\n", dist[n]);
} else {
puts("impossible");
}
return 0;
}
C++
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
const int MAXSIZE = 100010;
const int INF = 0x3f3f3f3f;
int n, m;
vector<vector<pair<int, int> > > graph(MAXSIZE);
vector<int> dist(MAXSIZE, INF), cnt(MAXSIZE, 0);
vector<bool> inQueue(MAXSIZE, false);
queue<int> q;
void addEdge(int from, int to, int weight) {
graph[from].emplace_back(weight, to);
}
void init() {
int x, y, z;
cin >> n >> m;
while (m--) {
cin >> x >> y >> z;
addEdge(x, y, z);
}
}
bool SPFA(int start) {
dist[start] = 0;
q.push(start);
inQueue[start] = true;
++cnt[start];
while (!q.empty()) {
int u = q.front();
q.pop();
inQueue[u] = false;
for (const auto [w, v] : graph[u]) {
if (dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
if (!inQueue[v]) {
q.push(v);
inQueue[v] = true;
++cnt[v];
if (cnt[v] >= n) {
return false;
}
}
}
}
}
return true;
}
int main() {
init();
if (SPFA(1) && dist[n] < INF/2) {
cout << dist[n] << endl;
} else {
cout << "impossible" << endl;
}
return 0;
}