问个SPFA做法的小问题
查看原帖
问个SPFA做法的小问题
895312
Archy_楼主2024/8/23 11:16

我是用 SPFA 写的,那个在

if(dis[v] > dis[u] + 1) {
				dis[v] = dis[u] + 1;
				ans[v] = ans[u];
				if(!inq[v]) {
					q.push(v);
					inq[v] = 1;
				}
			}

中对 ans 数组处理不是很理解,谁能浅浅讲一下,谢谢。

下面是需要完整的code。

#include <iostream>
#include <queue>
#define mod 100003
#define re register
using namespace std;

const int N = 1000005;
const int M = 2000005;
int n, m, head[N], cnt;
int dis[N], ans[N];
bool inq[N];

inline int rd();

struct node {
	int next, to;	
} e[M << 1]; 

inline void add(int u, int v) {
	e[++ cnt].to = v;
	e[cnt].next = head[u];
	head[u] = cnt;
}

inline void SPFA() {
	queue <int> q;
	for(int i = 1; i <= n; i ++) dis[i] = 1e9;
	dis[1] = 0, inq[1] = 1, ans[1] = 1;
	q.push(1);
	while(!q.empty()) {
		int u = q.front();
		q.pop();
		inq[u] = 0;
		for(re int i = head[u]; i; i = e[i].next) {
			int v = e[i].to;
			if(dis[v] > dis[u] + 1) {
				dis[v] = dis[u] + 1;
				ans[v] = ans[u];
				if(!inq[v]) {
					q.push(v);
					inq[v] = 1;
				}
			}
			else if(dis[v] == dis[u] + 1) {
				ans[v] += ans[u];
				ans[v] %= mod;
			}
		}
	}
} 

int main() {
	n = rd(), m = rd();
	for(re int i = 1; i <= m; i ++) {
		int u = rd(), v = rd();
		add(u, v), add(v, u);
	}
	SPFA();
	for(re int i = 1; i <= n; i ++) {
		printf("%d\n", ans[i]);
	}
	return 0;
}

inline int rd(){
	re int w = 1, x = 0;
    re char c = getchar();
	while(c < 48 || c > 57) {
		if(c == 45) w *= -1;
		c = getchar();
	}
	while(c >= 48 && c <= 57) {
		x = (x << 1) + (x << 3) + (c ^ 48);
		c = getchar();
	}
	return x * w;
}
2024/8/23 11:16
加载中...