使用取模操作来实现线性表循环队列
插入后 tail %= N
删除后 head %= N
其中N是队列最大长度
#include<stdio.h>
#include<string.h>
#include<stdbool.h>
#define N 2010
#define M 10010
#define INF 0x3f3f3f3f
int n, m;
int dist[N];
int queue[N];
bool inQue[N];
int head, tail;
int h[N], cnt;
int count[N];
struct edge{
int to;
int next;
int weight;
}E[M];
void add(int v, int w, int weight){
E[++cnt].next = h[v];
E[cnt].to = w;
E[cnt].weight = weight;
h[v] = cnt;
}
bool spfa(){
for(int i = 1; i <= n; i++){
queue[tail++] = i;
inQue[i] = true;
}
while(head != tail){
int t = queue[head++];
head %= N;
inQue[t] = false;
for(int i = h[t]; i != -1; i = E[i].next){
int u = E[i].to;
if(dist[t] + E[i].weight < dist[u]){
dist[u] = dist[t] + E[i].weight;
count[u] = count[t] + 1;
if(count[u] >= n) return true;
if(!inQue[u]){
queue[tail++] = u;
tail %= N;
inQue[u] = true;
}
}
}
}
return false;
}
int main(){
scanf("%d %d", &n, &m);
memset(h, -1, sizeof h);
for(int i = 1; i <= m; i++){
int a, b, w;
scanf("%d %d %d", &a, &b, &w);
if(a == b) add(a, b, 0);
else add(a, b, w);
}
if(spfa()) printf("Yes");
else printf("No");
return 0;
}