ZOJ - 2770 差分约束

题意:n个军营,给出每个军营的最大人数,m个估计,表示一段区间内的军营的最少人数和,现在让你求所有军营的最小可能人数和

利用前缀和构造不等式关系,形成差分约束系统,其实就是跑一遍最短路就可以了

#include<bits/stdc++.h>
#define inf  0x3f3f3f3f3f3f3f3f
using namespace std;
const int maxn = 2000;
struct node{
	int ne;
	long long cost;
	node(int u, long long v){
		ne = u;
		cost = v;
	}
	node(){
	}
};
vector<node>w[maxn];
long long dis[maxn], s[maxn];
int book[maxn], cnt[maxn], n, a[maxn];
int SPFA(){
	for(int i = 0; i <= n; i++){
		book[i] = 0, cnt[i] = 0, dis[i] = -inf;
	}
	queue<int>Q;
	Q.push(0);
	dis[0] = 0;
	book[0] = cnt[0] = 1;
	while(!Q.empty()){
		int pre = Q.front();
		book[pre] = 0; Q.pop();
	//	cout << pre << " " << dis[pre] << endl;
		for(int i = 0; i < w[pre].size(); i++){
			if(dis[pre] + w[pre][i].cost > dis[w[pre][i].ne]){
				dis[w[pre][i].ne] = dis[pre] + w[pre][i].cost;
				if(!book[w[pre][i].ne]){
					book[w[pre][i].ne] = 1;
					Q.push(w[pre][i].ne);
				}
			}
		}
	}
	return dis[n];
}
int main(){
	int m, u, v, cost;
	while(cin >> n >> m){
		int flog = 0;
		for(int i = 0; i <= n; i++){
			w[i].clear();
			s[i] = 0;
		}
		for(int i = 1; i <= n; i++){
			scanf("%d", &a[i]);
			s[i] = s[i - 1] + a[i];
			w[i].push_back(node(i - 1, -a[i]));
			w[i - 1].push_back(node(i, 0));
		} 
		while(m--){
			scanf("%d %d %d", &u, &v, &cost);
			if(cost > s[v] - s[u - 1])
			flog = 1;
			w[u - 1].push_back(node(v, cost));
		}
		if(flog)
		cout << "Bad Estimations" << endl;
		else
		cout << SPFA() << endl;
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值