建图:
const int SIZE = 100010;
const int INF = 0x3f3f3f3f;
int u[4*SIZE], w[4*SIZE], v[4*SIZE], next[4*SIZE]; //一般是4*SIZE
int first[SIZE], d[SIZE];
int sum[SIZE];
int n, m; //n个顶点,m条边。
memset(first, -1, sizeof(first));
void read_graph(int u1, int v1, int w1)
{
for(int e = 0; e < n; e++)
{
scanf("%d%d%d", &u[e], &v[e], &w[e]);
next[e] = first[u[e]];
first[u[e]] = e;
}
}
const int INF = 0x3f3f3f3f;
int u[4*SIZE], w[4*SIZE], v[4*SIZE], next[4*SIZE]; //一般是4*SIZE
int first[SIZE], d[SIZE];
int sum[SIZE];
int n, m; //n个顶点,m条边。
memset(first, -1, sizeof(first));
void read_graph(int u1, int v1, int w1)
{
for(int e = 0; e < n; e++)
{
scanf("%d%d%d", &u[e], &v[e], &w[e]);
next[e] = first[u[e]];
first[u[e]] = e;
}
}
队列:
int spfa(int src)
{
queue<int> q;
bool inq[SIZE] = {0};
for(int i = 0; i <= n; i++) d[i] = (i == src)? 0:INF;
q.push(src);
while(!q.empty())
{
int x = q.front(); q.pop();
inq[x] = 0;
for(int e = first[x]; e!=-1; e = next[e]) if(d[v[e]] > d[x]+w[e])
{
d[v[e]] = d[x]+w[e];
if(!inq[v[e]])
{
inq[v[e]] = 1;
if(++sum[v[e]] > n) //判断负环
{
return -1;
}
q.push(v[e]);
}
}
}
if(d[n] == INF) return -2;
else return d[n];
}
{
queue<int> q;
bool inq[SIZE] = {0};
for(int i = 0; i <= n; i++) d[i] = (i == src)? 0:INF;
q.push(src);
while(!q.empty())
{
int x = q.front(); q.pop();
inq[x] = 0;
for(int e = first[x]; e!=-1; e = next[e]) if(d[v[e]] > d[x]+w[e])
{
d[v[e]] = d[x]+w[e];
if(!inq[v[e]])
{
inq[v[e]] = 1;
if(++sum[v[e]] > n) //判断负环
{
return -1;
}
q.push(v[e]);
}
}
}
if(d[n] == INF) return -2;
else return d[n];
}
堆栈:
int spfa(int src)
{
int stack[SIZE] = {0};
bool ins[SIZE] = {0};
int top = 0;
for(int i = 1; i <= n; i++) d[i] = (i == src)? 0:INF;
stack[top++] = src;
while(top)
{
int x = stack[--top];
ins[x] = 0;
for(int e = first[x]; e!=-1; e = next[e]) if(d[v[e]] > d[x] + w[e])
{
d[v[e]] = d[x]+w[e];
if(!ins[v[e]])
{
ins[v[e]] = 1;
if(++sum[v[e]] > n)
{
return -1;
}
stack[top++] = v[e];
}
}
}
if(d[n] == INF) return -2;
return d[n];
}//SPFA的堆栈实现
{
int stack[SIZE] = {0};
bool ins[SIZE] = {0};
int top = 0;
for(int i = 1; i <= n; i++) d[i] = (i == src)? 0:INF;
stack[top++] = src;
while(top)
{
int x = stack[--top];
ins[x] = 0;
for(int e = first[x]; e!=-1; e = next[e]) if(d[v[e]] > d[x] + w[e])
{
d[v[e]] = d[x]+w[e];
if(!ins[v[e]])
{
ins[v[e]] = 1;
if(++sum[v[e]] > n)
{
return -1;
}
stack[top++] = v[e];
}
}
}
if(d[n] == INF) return -2;
return d[n];
}//SPFA的堆栈实现