Luogu1993 小K的农场 (差分约束)

(if a - b <= c, AddEdge(b, a, c))
Be careful, MLE is not good.

#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#define R(a,b,c) for(register int a = (b); (a) <= (c); ++(a))
#define nR(a,b,c) for(register int a = (b); (a) >= (c); --(a))
#define Fill(a,b) memset(a, b, sizeof(a))
#define Max(a,b) ((a) > (b) ? (a) : (b))
#define Min(a,b) ((a) < (b) ? (a) : (b))
#define Swap(a,b) ((a) ^= (b) ^= (a) ^= (b))

#define ON_DEBUGG

#ifdef ON_DEBUGG

#define D_e_Line printf("
----------
") 
#define D_e(x) cout << (#x) << " : " << x << endl
#define Pause() system("pause")
#define FileOpen() freopen("in.txt", "r", stdin)

#else

#define D_e_Line ;
#define D_e(x) ;
#define Pause() ;
#define FileOpen() ;

#endif
using namespace std;
struct ios{
	template<typename ATP>inline ios& operator >> (ATP &x){
		x = 0; int f = 1; char ch;
		for(ch = getchar(); ch < '0' || ch > '9'; ch = getchar()) if(ch == '-') f = -1;
		while(ch >= '0' && ch <= '9') x = x * 10 + (ch ^ '0'), ch = getchar();
		x *= f;
		return *this;
	}
}io;

const int N = 20007;

struct Edge{
	int nxt, pre, w;
}e[N << 1];
int head[N], cntEdge;
inline void add(int u, int v, int w){
	e[++cntEdge] = (Edge){ head[u], v, w}, head[u] = cntEdge;
}

int vis[N], dis[N];
inline bool SPFA(int u){
	vis[u] = true;
	for(register int i = head[u]; i; i = e[i].nxt){
		if(dis[e[i].pre] > dis[u] + e[i].w){
			dis[e[i].pre] = dis[u] + e[i].w;
			if(vis[e[i].pre] || SPFA(e[i].pre)){
				return true;
			}
		}
	}
	vis[u] = false;
	return false;
}

int main(){
//FileOpen();
	int n, m;
	io >> n >> m;
	
	R(i,1,m){
		int opt;
		io >> opt;
		if(opt == 1){
			int x, y, w;
			io >> x >> y >> w;
			add(x, y, -w);
		}
		else if(opt == 2){
			int x, y, w;
			io >> x >> y >> w;
			add(y, x, w);	
		}
		else if(opt == 3){
			int x, y;
			io >> x >> y;
			add(x, y, 0);
			add(y, x, 0);
		}
	}
	
	R(i,1,n){
		add(0, i, 0); // this sentence caused MLE !
		dis[i] = 0x3f3f3f3f;
	}
	
	if(SPFA(0) == false){
		printf("Yes
");
	}
	else{
		printf("No
");
	}
	return 0;
}
原文地址:https://www.cnblogs.com/bingoyes/p/11406299.html