目前是得了40分,判负环的思路:用一个cnt[n]来存储从1到这个点n要走的步数,如果走到某一个点的步数比点的数量减一(n-1)还要大的话,就说明存在负环,否则步数最大为n-1
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N = 2010, M = 3010*2;
int h[N], e[M], ne[M], w[M], idx;
int times, n, m;
int dist[N], cnt[N];
bool st[N];
void add(int a, int b, int c)
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
bool spfa()
{
queue <int> q;
q.push(1);
st[1] = true;
while (q.size())
{
int t = q.front();
q.pop();
st[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];
cnt[j] = cnt[t] + 1;
if (cnt[j] >= n) return true;
if (!st[j])
{
q.push(j);
st[j] = true;
}
}
}
}
return false;
}
int main()
{
cin >> times;
while (times--)
{
idx = 0;
memset(h, -1, sizeof h);
memset(e, 0, sizeof e);
memset(ne, 0, sizeof ne);
memset(cnt, 0, sizeof cnt);
memset(st, false, sizeof st);
memset(dist,0,sizeof dist);
cin >> n >> m;
while (m--)
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
if (c >= 0) add(b, a, c);
}
if (spfa()) cout << "YES" << endl;
else cout << "NO" << endl;
}
return 0;
}