UVa 11478 - Halum (差分约束)

题目链接:https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=0&problem=2473&mosmsg=Submission+received+with+ID+26584758

题目条件可以转化为每个点最终的权值为:\(w + sum[u] - sum[v]\),二分答案,判断最小的边可不可以是 \(x\),则有 \(sum[v] <= sum[u] + w - x\),即转化为差分约束系统,若系统中有负环,则无解(大小关系矛盾)

如果要求方案,添加一个源点 \(S\),\(S\) 向其他所有点连边,边权为 \(0\),跑一遍 \(spfa\),则从源点到每个点的距离就是答案

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

const int maxn = 510;
const int maxm = 3010;

int n, m;

int h[maxn], cnt = 0;
struct E{
	int to, cost, next;
}e[maxm];
void add(int u, int v, int w){
	e[++cnt].to = v;
	e[cnt].cost = w;
	e[cnt].next = h[u];
	h[u] = cnt;
}

int in[maxn], tot[maxn], d[maxn];
bool spfa(int mid){
	queue<int> q;
	memset(tot, 0, sizeof(tot));
	memset(in, 0, sizeof(in));
	for(int i = 1 ; i <= n ; ++i) {
		d[i] = 0;
		in[i] = 1;
		q.push(i);
	}
	
	while(!q.empty()){
		int u = q.front(); q.pop(); in[u] = 0;
		for(int i = h[u] ; i != -1 ; i = e[i].next){
			int v = e[i].to;
			if(d[u] + e[i].cost - mid < d[v] ){
				d[v] = d[u] + e[i].cost - mid;
				
				if(!in[v]){
					in[v] = 1;
					q.push(v);
					++tot[v];
					if(tot[v] > n) {
						return false;
					}
				}
			}
		}
	}
	
	return true;
}

bool check(int x){
	return spfa(x);
}

ll read(){ ll s = 0, f = 1; char ch = getchar(); while(ch < '0' || ch > '9'){ if(ch == '-') f = -1; ch = getchar(); } while(ch >= '0' && ch <= '9'){ s = s * 10 + ch - '0'; ch = getchar(); } return s * f; }

int main(){
	while(scanf("%d%d", &n, &m) != EOF){
		memset(h, -1, sizeof(h)); cnt = 0;
		int u, v, w;
		
		int L = 0, R = 0;
		for(int i = 1 ; i <= m ; ++i){
			scanf("%d%d%d", &u, &v, &w);
			add(u, v, w);
			R = max(R, w);
		}
		
		if(check(R + 1)) printf("Infinite\n");
		else if(!check(1)) printf("No Solution\n");
		else {
			int ans = 0;
			while(L <= R){
				int mid = (L + R) >> 1;
				if(check(mid)){
					L = mid + 1;
					ans = mid;
				} else{
					R = mid - 1;
				}
			}
			printf("%d\n", ans);			
		}

	}
	return 0;
}
上一篇:小球下落——UVa 679


下一篇:JavaScript Patterns 4.6 Immediate Object Initialization