码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-11-03 17:54:30      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:spfa   差分约束系统   最长路   bzoj   scoi2011   

题目大意:幼儿园老师给小盆友们发糖果。有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 糖果 差分约束系统

标签:spfa   差分约束系统   最长路   bzoj   scoi2011   

原文地址:http://blog.csdn.net/jiangyuze831/article/details/40742845

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!