Luogu3275 [SCOI2011]糖果 (差分约束)

逆序建超级源快十倍还行

#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("\n----------\n") 
#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 = 100007;

struct Edge{
	int nxt, pre, w;
}e[N * 3];
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]; long long dis[N];
inline bool SPFA(int u){
	vis[u] = true;
	for(register int i = head[u]; i; i = e[i].nxt){
		int v = e[i].pre;
		if(dis[v] < dis[u] + e[i].w){
			dis[v] = dis[u] + e[i].w;
			if(vis[v] || SPFA(v) == true){
				return true;
			}
		}
	}
	vis[u] = false;
	return false;
}
//int tot[N], q[N], top;
//inline bool SPFA(int st, int &n){
//	vis[st] = true;
//	q[++top] = st;
//	tot[st] = 1;
//	while(top){
//		int u = q[top--];
//		vis[u] = false;
//		for(register int i = head[u]; i; i = e[i].nxt){
//			int v = e[i].pre;
//			if(dis[v] < dis[u] + e[i].w){
//				dis[v] = dis[u] + e[i].w;
//				tot[v] = tot[u] + 1;
//				if(tot[v] > n + 1){
//					return true;
//				}
//				if(!vis[v]){
//					vis[v] = true;
//					q[++top] = v;
//				}
//			}
//		}
//	}
//	return false;
//}

int main(){
	int n, m;
	io >> n >> m;
	R(i,1,m){
		int opt, x, y;
		io >> opt >> x >> y;
		if(opt == 1){
			add(x, y, 0);
			add(y, x, 0);
		}
		else if(opt == 2){
			if(x == y){
				printf("-1");
				return 0;
			}
			add(x, y, 1);
		}
		else if(opt == 3){
			add(y, x, 0);
		} 
		else if(opt == 4){
			if(x == y){
				printf("-1");
				return 0;
			}
			add(y, x, 1);
		}
		else if(opt == 5){
			add(x, y, 0);
		}
	}
	
//	R(i,1,n){
//		add(0, i, 1);
//	}
	nR(i,n,1){
		add(0, i, 1);
	}
	
	if(SPFA(0) == true){
		printf("-1");
	}
	else{
		long long ans = 0;
		R(i,1,n){
			//printf("%d -> %d\n", i, dis[i]);
			ans += dis[i];
		}
		printf("%lld", ans);
	}
	
	return 0;
}
/*
1 : add both
	a + 1 <= b
2:	a -> b 1
3 : a >= b + 0
3 : b -> a 0
*/
posted @ 2019-08-24 23:04  邱涵的秘密基地  阅读(115)  评论(0编辑  收藏  举报