O(nm)
int h[N], w[M], e[M], ne[M], idx;
int dist[N], cnt[N];
bool s[N];
void add(int a, int b, int c) //memset(h,-1,sizeof h);
{
e[idx] = b;
ne[idx] = h[a];
w[idx] = c;
h[a] = idx++;
}
bool spfa() //返回1时有负环
{
memset(dist, 0, sizeof dist);
memset(cnt, 0, sizeof cnt);
memset(s, 0, sizeof s);
queue<int> q;
for (int i = 1; i <= n; i++)
{
q.push(i);
s[i] = 1;
}
while (q.size())
{
int t = q.front();
q.pop();
s[t] = 0;
for (int i = h[t]; ~i; 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 1;
}
if (!s[j])
{
q.push(j);
s[j] = 1;
}
}
}
}
return 0;
}