【模板】BFS-SPFA、DFS-SPFA

C++版本:

BFS-SPFA

bool SPFA(int x) {
	queue<int>q;
	q.push(x);
	vis[x] = true;
	while (!q.empty()) {
		int now = q.front(); q.pop(); vis[now] = false;
		for (int i = head[now]; i; i = eg[i].nex) {
			int v = eg[i].to;
			if (dist[v] > dist[now] + eg[i].cost) {
				dist[v] = dist[now] + eg[i].cost;
				circle[v] = circle[now] + 1;
				if (circle[v] >= V)return false;
				if (!vis[v])vis[v] = true, q.push(v);
			}
		}
	}
	return true;
}

DFS-SPFA

bool SPFA(ll x) {
	vis[x] = true;
	for (ll i = head[x]; i; i = eg[i].nex) {
		ll v = eg[i].to;
		if (dist[v] > dist[x] + eg[i].cost) {
			dist[v] = dist[x] + eg[i].cost;
			if (vis[v] || !SPFA(v)) {
				return false;
			}
		}
	}
	vis[x] = false;
	return true;
}
posted @ 2020-09-13 18:27  pjhui  阅读(160)  评论(0编辑  收藏  举报