首页 > 代码库 > BZOJ 2330 SCOI 2011 糖果 差分约束系统

BZOJ 2330 SCOI 2011 糖果 差分约束系统

题目大意:幼儿园老师给小盆友们发糖果。有5种要求,问老师最少需要准备多少糖果。如不能满足,输出-1。


思路:裸地差分约束系统,但是正向加边会T,需要反向加边。


CODE:

#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define MAX 400010
using namespace std;

int points,asks;
int head[MAX],total;
int next[MAX],aim[MAX],length[MAX];

int f[MAX],showed_time[MAX];
bool v[MAX];

inline void Add(int x,int y,int len)
{
	next[++total] = head[x];
	aim[total] = y;
	length[total] = len;
	head[x] = total;
}

bool SPFA()
{
	static queue<int> q;
	while(!q.empty())	q.pop();
	q.push(0);
	memset(f,0xef,sizeof(f));
	f[0] = 0;
	while(!q.empty()) {
		int x = q.front(); q.pop();
		v[x] = false;
		for(int i = head[x]; i; i = next[i])
			if(f[aim[i]] < f[x] + length[i]) {
				f[aim[i]] = f[x] + length[i];
				if(!v[aim[i]]) {
					v[aim[i]] = true;
					q.push(aim[i]);
					showed_time[aim[i]] = showed_time[x] + 1;
					if(showed_time[aim[i]] > points + 1)
						return false;
				}
			}	
	}
	return true;
}

int main()
{
	cin >> points >> asks;
	for(int i = points; i; --i)	Add(0,i,1);
	for(int flag,x,y,i = 1; i <= asks; ++i) {
		scanf("%d%d%d",&flag,&x,&y);
		if(flag == 1)	Add(x,y,0),Add(y,x,0);
		if(flag == 2)	Add(x,y,1);
		if(flag == 3)	Add(y,x,0);
		if(flag == 4)	Add(y,x,1);
		if(flag == 5)	Add(x,y,0);
	}
	if(!SPFA()) {
		puts("-1");
		return 0;
	}
	long long ans = 0;
	for(int i = 1; i <= points; ++i)
		ans += f[i];
	cout << ans << endl;
	return 0;
}


BZOJ 2330 SCOI 2011 糖果 差分约束系统