ECNU 3263 丽娃河的狼人传说(差分约束)

丽娃河的狼人传说

Time limit per test: 1.0 seconds

Memory limit: 256 megabytes

丽娃河是华师大著名的风景线。但由于学校财政紧缺,丽娃河边的路灯年久失修,一到晚上就会出现走在河边要打着手电的情况,不仅非常不方便,而且影响安全:已经发生了大大小小的事故多起。

方便起见,丽娃河可以看成是从 1 到 n 的一条数轴。为了美观,路灯只能安装在整数点上,每个整数点只能安装一盏路灯。经专业勘测,有 m 个区间特别容易发生事故,所以至少要安装一定数量的路灯,

请问至少还要安装多少路灯。

Input

第一行一个整数 T (1T300),表示测试数据组数。

对于每组数据:

  • 第一行三个整数 

  • 第二行 k 个不同的整数用空格隔开,表示这些位置一开始就有路灯。

  • 接下来 m 行表示约束条件。第 i 行三个整数 (1lirin,1tin)

Output

对于每组数据,输出 Case x: y。其中 x 表示测试数据编号(从 1 开始),y 表示至少要安装的路灯数目。如果无解,y 为 1

Examples

input
3
5 1 3
1 3 5
2 3 2
5 2 3
1 3 5
2 3 2
3 5 3
5 2 3
1 3 5
2 3 2
4 5 1
output
Case 1: 1
Case 2: 2
Case 3: 1

Note

因为今天不是满月,所以狼人没有出现。

Source

2017 华东师范大学网赛
 
 
题目链接:ECNU 3263
突然发现以前这题是一道裸的差分约束……由于要求的是最小值,那必定要把所有不等式化成da-db>=c的形式,首先一个点至多安装一盏路灯,那么有di-d{i-1}>=1,然后一些点已经存在了路灯,又有:dx-d{x-1}=1,这条等式可以用两条不等式表示:dx-d{x-1}>=1和dx-d{x-1}<=1,后者两边同时乘以-1得到d{x-1}-dx>=-1,最后SPFA的时候用入队次数检测一下正环就可以了,如果存在正环说明方案不存在输出-1
代码:
#include <bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
#define LC(x) (x<<1)
#define RC(x) ((x<<1)+1)
#define MID(x,y) ((x+y)>>1)
#define fin(name) freopen(name,"r",stdin)
#define fout(name) freopen(name,"w",stdout)
#define CLR(arr,val) memset(arr,val,sizeof(arr))
#define FAST_IO ios::sync_with_stdio(false);cin.tie(0);
typedef pair<int, int> pii;
typedef long long LL;
const double PI = acos(-1.0);
const int N = 1010;
struct edge
{
	int to, nxt, d;
	edge() {}
	edge(int _to, int _nxt, int _d): to(_to), nxt(_nxt), d(_d) {}
};
edge E[N * 5];
int head[N], tot;
int vis[N], d[N];
int cnt[N];
int flag, n, m, k;

void init()
{
	CLR(head, -1);
	tot = 0;
	CLR(cnt, 0);
	flag = 1;
}
inline void add(int s, int t, int d)
{
	E[tot] = edge(t, head[s], d);
	head[s] = tot++;
}
void spfa(int s)
{
	queue<int>Q;
	Q.push(s);
	CLR(vis, 0);
	CLR(d, -INF);
	vis[s] = 1;
	d[s] = 0;
	while (!Q.empty())
	{
		int u = Q.front();
		Q.pop();
		vis[u] = 0;
		if (++cnt[u] > n)
		{
			flag = 0;
			return ;
		}
		for (int i = head[u]; ~i; i = E[i].nxt)
		{
			int v = E[i].to;
			if (d[v] < d[u] + E[i].d)
			{
				d[v] = d[u] + E[i].d;
				if (!vis[v])
				{
					vis[v] = 1;
					Q.push(v);
				}
			}
		}
	}
}
int main(void)
{
	int tcase, i;
	scanf("%d", &tcase);
	for (int q = 1; q <= tcase; ++q)
	{
		scanf("%d%d%d", &n, &m, &k);
		init();
		int already = k;
		while (k--)
		{
			int x;
			scanf("%d", &x);
			add(x - 1, x, 1);// d[x] - d[x - 1] >= 1;
			add(x, x - 1, -1);// d[x - 1] - d[x] >= -1;
		}
		for (i = 1; i <= n; ++i)
		{
			add(i - 1, i, 0);//d[i] - d[i - 1] >= 0
			add(i, i - 1, -1);//d[i-1] - d[i] >= -1
		}
		while (m--)
		{
			int l, r, t;
			scanf("%d%d%d", &l, &r, &t);
			add(l - 1, r, t);//d[r] - d[l - 1] >= t
		}
		spfa(0);
		printf("Case %d: %d\n", q, flag ? d[n] - d[0] - already : -1);
	}
	return 0;
}
posted @ 2017-07-11 17:11  Blackops  阅读(320)  评论(0编辑  收藏  举报