C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSIZE 2010
int n, m, dist[MAXSIZE], cnt[MAXSIZE];
int head, tail, queue[MAXSIZE], inQueue[MAXSIZE];
struct Edge {
int to_, weight_;
struct Edge *nxt_;
} *edges[MAXSIZE];
void init() {
int x, y, z;
scanf("%d%d", &n, &m);
while (m--) {
scanf("%d%d%d", &x, &y, &z);
struct Edge *s = (struct Edge*) calloc(1, sizeof(struct Edge));
s->to_ = y;
s->weight_ = z;
s->nxt_ = edges[x];
edges[x] = s;
}
memset(dist, 0x3f, sizeof(dist));
head = 0, tail = 0;
}
int empty() {
return head == tail ? 1 : 0;
}
void push(int val) {
queue[tail] = val;
tail = (tail+1) % MAXSIZE;
}
void pop() {
head = (head+1) % MAXSIZE;
}
int front() {
return queue[head];
}
int SPFA() {
for (int i = 1; i <= n; ++i) {
push(i);
inQueue[i] = 1;
++cnt[i];
}
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->nxt_;
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()) {
puts("No");
} else {
puts("Yes");
}
return 0;
}
C++
#include <cstring>
#include <iostream>
#include <queue>
using namespace std;
const int MAXSIZE = 2010;
int n, m, dist[MAXSIZE], cnt[MAXSIZE];
bool inQueue[MAXSIZE];
queue<int> q;
struct Edge {
int to_, weight_;
Edge *nxt_;
Edge(int to, int weight) : to_(to), weight_(weight), nxt_(nullptr) {}
} *edges[MAXSIZE];
void addEdge(int from, int to, int weight) {
Edge *s = new Edge(to, weight);
s->nxt_ = edges[from];
edges[from] = s;
}
void init() {
int x, y, z;
cin >> n >> m;
while (m--) {
cin >> x >> y >> z;
addEdge(x, y, z);
}
memset(dist, 0x3f, sizeof(dist));
}
bool SPFA() {
for (int i = 1; i <= n; ++i) {
q.push(i);
inQueue[i] = true;
++cnt[i];
}
while (!q.empty()) {
int u = q.front();
q.pop();
inQueue[u] = false;
Edge *p = edges[u];
while (p != nullptr) {
int v = p->to_, w = p->weight_;
p = p->nxt_;
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()) {
cout << "No" << endl;
} else {
cout << "Yes" << endl;
}
return 0;
}