求助差分约束模板
查看原帖
求助差分约束模板
141335
qwq2519楼主2021/9/23 10:35
#include<iostream>
#include<cstring>
#include<cstdio>
#define rep(i,j,k) for(register int i(j);i<=k;++i)
#define drp(i,j,k) for(register int i(j);i>=k;--i)
#define repg(x) for(register int i(G.head[x]);i;i=G.next[i])
#define bug cout<<"~~~~~~~~~~~~~"<<'\n';
#define bugout(x) cout<<x<<'\n';
using std::cin;
using std::cout;
typedef long long lxl;
template<typename T>
inline T  max( T a, T b) {
	return a > b ? a : b;
}
template<typename T>
inline T  min( T a, T b) {
	return a < b ? a : b;
}

inline char gt() {
	static char buf[1 << 21], *p1 = buf, *p2 = buf;
	return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1 << 21, stdin), p1 == p2) ? EOF : *p1++;
}
template <typename T>
inline void  read(T &x) {
	register char ch = gt();
	x = 0;
	int w(0);
	while(!(ch >= '0' && ch <= '9'))w |= ch == '-', ch = gt();
	while(ch >= '0' && ch <= '9')x = x * 10 + (ch & 15), ch = gt();
	w ? x = ~(x - 1) : x;
}
template <typename T>
inline void out(T x, char cc) {
	if(x < 0) x = -x, putchar('-');
	char ch[20];
	int num(0);
	while(x || !num) ch[++num] = x % 10 + '0', x /= 10;
	while(num) putchar(ch[num--]);
	putchar(cc);
}//ÓÃǰ׺ºÍϱê×÷Ϊµã
const int N = 107;
int w, n, m, v;
struct graph {
	int head[N], tot, next[N << 1], edge[N << 1], ver[N << 1];
	inline void add(int a, int b, int c) {
		ver[++tot] = b;
		next[tot] = head[a];
		head[a] = tot;
		edge[tot] = c;
	}
	inline void init() {
		tot = 0;
		memset(head, 0, sizeof head);
		memset(next, 0, sizeof next);
		memset(edge, 0, sizeof edge);
		memset(ver, 0, sizeof ver);
	}
} G;

int cnt[N], d[N];
int q[N*N];
bool vis[N];
inline bool spfa() {
	memset(vis, 0, sizeof vis);
	memset(cnt, 0, sizeof cnt);
	memset(d, 0x3f, sizeof d);
	d[0] = 0;
	vis[0] = 1;
	q[q[0] = 1] = 0;
	rep(kkk, 1, q[0]) {
		int x = q[kkk];
		vis[x] = 0;
		repg(x) {
			int y(G.ver[i]), z(G.edge[i]);
			if(d[y] > d[x] + z) {
				d[y] = d[x] + z;
				if(!vis[y]) {
					vis[y] = 1;
					if(++cnt[y] == n + 1) return false;
					q[++q[0]] = y;
				}
			}
		}
	}
	return true;
}

int main() {
	read(w);
	while(w--) {
		G.init();
		read(n);
		read(m);
		int s, t;
		rep(i, 1, n) {
			G.add(0, i, 0);
			G.add(i,0,0);
		}
		rep(i, 1, m) {
			read(s);
			read(t);
			read(v);
			G.add(s - 1, t, v); //sum[t]-sum[s-1]=v
			G.add(t, s - 1, -v); //sum[s-1]-sum[t]=-v
		}
		puts(spfa() ? "true" : "false");
	}
	return 0;
}

样例两个false。。

2021/9/23 10:35
加载中...