洛谷P4578 [FJOI2018]所罗门王的宝藏(dfs)

题意

题目链接

Sol

对于每个询问(x, y, c)

从在((x, y))之间连一条边权为(c)的双向边,然后就是解(K)个二元方程。

随便带个数进去找找环就行了

#include<bits/stdc++.h>
#define LL long long 
#define fi first
#define se second
#define Pair pair<int, int> 
#define Fin(x) freopen(#x".in", "r", stdin);
using namespace std;
const int MAXN = 3001, INF = 1e9 + 10;
template<typename A, typename B> inline bool chmax(A &x, B y) {return x < y ? x = y, 1 : 0;}
template<typename A, typename B> inline bool chmin(A &x, B y) {return x > y ? x = y, 1 : 0;}
inline int read() {
	char c = getchar(); int x = 0, f = 1;
	while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
	while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
	return x * f;
}
int N, M, val[MAXN], vis[MAXN];
vector<Pair> v[MAXN];
int dfs(int x) {
	vis[x] = 1;
	for(auto &to : v[x]) {
		if(vis[to.fi] && val[x] + val[to.fi] != to.se) return 0;
		else if(vis[to.fi]) continue;
		val[to.fi] = to.se - val[x];
		if(!dfs(to.fi)) return 0;
	}
	return 1;
}
void solve() {
	memset(val, 0, sizeof(val));
	memset(vis, 0, sizeof(vis));
	int N = read(), M = read(), K = read();
	for(int i = 1; i <= N + M; i++) v[i].clear();
	for(int i = 1; i <= K; i++) {
		int x = read(), y = read(), c = read();
		v[x].push_back({y + N, c});
		v[y + N].push_back({x, c});
	}
	for(int i = 1; i <= N + M; i++) 
		if(!vis[i] && !dfs(i)) 
			{puts("No"); return ;}
	puts("Yes");
}
signed main() {
//	Fin(a);
	for(int T = read(); T--; solve());
	return 0;
}
原文地址:https://www.cnblogs.com/zwfymqz/p/10448614.html