题目大意:有n个点,m条边,问从1号点到n号点的最短路
思路:spfa的思路就是先把起点的所有邻接点放入队列中,然后对于队列中的每一个点,遍历他的相邻点,如果通过该点到相邻点的路径更短,就更新路径长度,并将更新过且没在队列中的点放入队列,如果一个点更新了超过n次 ,则说明出现了负圈,因为负圈
- #include
- #include
- #include
- using namespace std;
- const int N = 105, M = 1e4 + 5, INF = 0x7fffffff;
- struct Edge
- {
- int v, w, next;
- }e[M << 1];//链式前向星存图
- struct node
- {//优先队列中存储的点的编号和最短路
- int id, dis;
- bool operator<(const node& a)const
- {
- return dis > a.dis;
- }//因为我们要小的先出队,所以要把小于号重载为大于
- node(int a, int b)
- {
- id = a, dis = b;
- }
- };
- int head[N], cnt = 0;
- void addedge(int u, int v, int w)
- {
- e[++cnt].v = v;
- e[cnt].w = w;
- e[cnt].next = head[u];
- head[u] = cnt;
- }
- int n, m;
- int dis[N], done[N], neg[N];
- void spfa()
- {
- for (int i = 1; i <= n; i++)
- {
- neg[i] = 0;
- dis[i] = INF;
- done[i] = 0;
- }
- dis[1] = 0;
- queue<int>q;
- q.push(1);
- done[1] = 1;
- while (!q.empty())
- {
- int u = q.front();
- q.pop();
- done[u] = 0;
- for (int i = head[u]; ~i; i = e[i].next)
- {
- int v = e[i].v, w = e[i].w;
- //遍历当前队列中节点的所有邻接点
- if (dis[u] + w < dis[v])
- {
- dis[v] = dis[u] + w;
- if (!done[v])//将所有距离被更新的,且没在队列里的点放入队列
- {
- done[v] = 1;
- q.push(v);
- neg[v]++;//统计每个点被更新的次数,>n则说明有负圈
- if (neg[v] > n)
- {
- //有负圈
- }
- }
- }
- }
- }
- }
- int main()
- {
- while (~scanf("%d%d", &n, &m))
- {
- if (n == 0 && m == 0)
- break;
- for (int i = 1; i <= n; i++)
- {
- e[i].next = -1;
- head[i] = -1;//对于链式前向星,只需初始化头指针
- }
- cnt = 0;
- for (int i = 1; i <= m; i++)
- {
- int u, v, w;
- scanf("%d%d%d", &u, &v, &w);
- addedge(u, v, w);
- addedge(v, u, w);//无向图建两条边
- }
- spfa();
- printf("%d\n", dis[n]);
- }
- }
可以更新无数次