spfa求负环,玄学复杂度
int head[MAXN] = {0}, tot = 0;
void init(){ mem(head); tot = 0; }
struct node { int from, to, val, nex; } edge[MAXN << 1];
int add(int x, int y, int z)
{
edge[++tot].to = y;
edge[tot].val = z;
edge[tot].nex = head[x];
head[x] = tot;
return tot;
}
int dis[MAXN], cnt[MAXN] = {0};
bitset <MAXN> used;
bool spfa(int x)
{
memset(dis, 63, sizeof(dis));
used.reset();
mem(cnt);
queue <int> Q;
Q.push(x);
used[x] = true;
dis[x] = 0;
cnt[x] = 1;
while(!Q.empty())
{
int now = Q.front();
Q.pop();
used[now] = false;
for(int it = head[now]; it; it = edge[it].nex)
{
int to = edge[it].to, val = edge[it].val;
if(dis[to] > dis[now] + val)
{
dis[to] = dis[now] + val;
cnt[to] = cnt[now] + 1;
if(cnt[to] > n)
return false;
if(!used[to])
Q.push(to), used[to] = true;
}
}
}
return true;
}