POJ-3159___Candies——差分约束 + stack

题目链接:点我啊╭(╯^╰)╮

题目大意:

     n n 个人, m m 个信息 A A B B K K ,每个信息表示 B B 同学得到糖的数量不能比 A A 同学多 K K 个。求第 n n 个最多比第 1 1 个多几个糖??

解题思路:

    明显是最短路,明显是模板,但为什么还要发这篇博客呢,因为这题的数据比较抠门,用SPFA + 队列会超时,用Dijkstra + 优先队列好像也会超时,但是用SPFA + stack竟然能过!!!

    这里给出我的解释:
    SPFA + queue 等于 BFS + 迭代
    SPFA + stack 等于 DFS + 迭代
    两者的时间复杂度差不多,但是在没有负权环的情况下好像是说stack会快一点,但是我本人试了几道题,发现stack反而会慢一点???
    但是说,stack的速度会比queue快一丢丢,但具体的效率还是要根据题目给出的数据来定,比如本题,用 stack 会比 queue 快很多

代码思路:

    无

核心:SPFA+stack有时会比queue快!

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

const int MAXN = 200010;
const int MAXM = 500010;
const int ANS_MAX = 2147483647;

struct EDGE {
	int next;
	int to;
	ll w;
} edge[MAXM];

int n, m, st, ed, cnt, pre[MAXN];
int head[MAXN], num[MAXN];
ll dis[MAXN];
bool vis[MAXN];
stack<int> Q;

inline int Read() {  //读入优化 可忽略
	char c;
	int ans = 0;
	bool Sign = false;
	while(!isdigit(c=getchar()) && c != '-');
	if(c == '-') {
		Sign = true;
		c = getchar();
	}
	do {
		ans = (ans<<3) + (ans<<1) + (c - '0');
	} while(isdigit(c=getchar()));
	return Sign ? -ans : ans;
}

void Add(int u, int v, ll w) {
	edge[++cnt].next = head[u];
	edge[cnt].to = v;
	edge[cnt].w = w;
	head[u] = cnt;
}

void read() {
	int x, y;
	ll w;
	n = Read();
	m = Read();
	for(int i=1; i<=m; i++) {
		x = Read();
		y = Read();
		w = Read();
		Add(x, y, w);
	}
}

bool SPFA(int x) {
	while(!Q.empty()) Q.pop();
	for(int i=1; i<=n; i++) dis[i] = ANS_MAX;
	dis[x] = 0;
	num[x] = 1;
	Q.push(x);
	vis[x] = true;
	while(!Q.empty()) {
		int k = Q.top();
		Q.pop();
		vis[k] = false;
		if(dis[k] == ANS_MAX) continue;
		for(int i=head[k]; i!=0; i=edge[i].next) {
			int j = edge[i].to;
			if(dis[j] > dis[k] + edge[i].w) {
				dis[j] = dis[k] + edge[i].w;
				num[j] = num[k]+1;
				pre[j] = k;
				//if(num[j]>n) return 1;	//判断负环
				if(!vis[j]) {
					Q.push(j);
					vis[j] = true;
				}
			}
		}
	}
	return 0;
}

int main() {
	memset(vis, 0, sizeof(vis));
	memset(num, 0, sizeof(num));
	memset(head, 0, sizeof(head));
	cnt = 0;
	read();
	SPFA(1);
	printf("%lld\n", dis[n]);
}

猜你喜欢

转载自blog.csdn.net/Scar_Halo/article/details/83511781
今日推荐