#include <bits/stdc++.h>
#define MEM(a,x) memset(a , x , sizeof(a))
using namespace std;
typedef int weight_t;
const int SIZE_E = //1000000; 注意是双向边 题目的m条边 在mkEdge里面存了两条
const int SIZE_V = //1050;
int n;
int ECnt = 0;
struct edge_t{
int v;
weight_t w;
edge_t *next;
}Edge[SIZE_E];
edge_t *V[SIZE_V];
void mkEdge(int const &a,int const &b,weight_t const &w){
Edge[ECnt].v = b;
Edge[ECnt].w = w;
Edge[ECnt].next = V[a];
V[a] = Edge+ECnt++;
Edge[ECnt].v = a;
Edge[ECnt].w = w;
Edge[ECnt].next = V[b];
V[b] = Edge+ECnt++;
}
weight_t D[SIZE_V];
bool flag[SIZE_V];
void spfa(int s){
MEM(flag,0);
fill(D,D+SIZE_V,INT_MAX);
D[s] = 0;
flag[s] = true;
queue<int>q;
q.push(s);
while(!q.empty()){
int u = q.front();
q.pop();
flag[u] = false;
for(edge_t *p = V[u];p;p = p->next){
int v = p->v;
weight_t temp = D[u] + p->w;
if (temp < D[v]){
D[v] = temp;
if (!flag[v]){
flag[v] = true;
q.push(v);
}
}
}
}
}
void init(){
ECnt = 0;
memset(V,0,sizeof(V));
MEM(Edge,0);
}
使用邻接矩阵的存储方式
#include <bits/stdc++.h>
#define MEM(a,x) memset(a , x , sizeof(a))
using namespace std;
/**下标从1开始,只能存一条边
*注意初始化
*/
typedef int weight_t;
const int SIZE_V = 110;
int n;
weight_t Road[SIZE_V][SIZE_V];
///不能存多条边,所以存边要先判断
inline void mkEdge(int const &a,int const &b,weight_t const &w){
Road[a][b] = Road[b][a] = w;
}
weight_t D[SIZE_V];
bool flag[SIZE_V];
void spfa(int s){
MEM(flag,0);
fill(D,D+SIZE_V,INT_MAX);
D[s] = 0;
flag[s] = true;
queue<int>q;
q.push(s);
while(!q.empty()){
int u = q.front();
q.pop();
flag[u] = false;
for (int i = 1;i <= n;++i){
///注意是减法,初始化没边是int_max,加上D[u]会变成负数
if ( D[i] - Road[u][i] > D[u] ){
D[i] = Road[u][i]+D[u];
if (!flag[i]){
flag[i] = true;
q.push(i);
}
}
}
}
}
void init(){
for (int i = 0;i<= n;++i)for (int j = 0;j <= n;++j){
Road[i][j] = INT_MAX;
}
}