poj1201 Intervals--单源最短路径&差分约束

原题链接: http://poj.org/problem?id=1201


一:原题内容

Description

You are given n closed, integer intervals [ai, bi] and n integers c1, ..., cn.
Write a program that:
reads the number of intervals, their end points and integers c1, ..., cn from the standard input,
computes the minimal size of a set Z of integers which has at least ci common elements with interval [ai, bi], for each i=1,2,...,n,
writes the answer to the standard output.

Input

The first line of the input contains an integer n (1 <= n <= 50000) -- the number of intervals. The following n lines describe the intervals. The (i+1)-th line of the input contains three integers ai, bi and ci separated by single spaces and such that 0 <= ai <= bi <= 50000 and 1 <= ci <= bi - ai+1.

Output

The output contains exactly one integer equal to the minimal size of set Z sharing at least ci elements with interval [ai, bi], for each i=1,2,...,n.

Sample Input

5
3 7 3
8 10 3
6 8 1
1 3 1
10 11 1

Sample Output

6

二:分析理解

题目说[ai, bi]区间内和点集Z至少有ci个共同元素,那也就是说如果我用Si表示区间[0,i]区间内至少有多少个元素的话,那么Sbi - Sai >= ci,这样我们就构造出来了一系列边,权值为ci,但是这远远不够,因为有很多点依然没有相连接起来(也就是从起点可能根本就还没有到终点的路线),此时,我们再看看Si的定义,也不难写出0<=Si - Si-1<=1的限制条件,虽然看上去是没有什么意义的条件,但是如果你也把它构造出一系列的边的话,这样从起点到终点的最短路也就顺理成章的出现了。

我们将上面的限制条件写为同意的形式:

Sbi - Sai >= ci

Si - Si-1 >= 0

Si-1 - Si >= -1

这样一来就构造出了三种权值的边,而最短路自然也就没问题了。


三:AC代码

#include<iostream>    
#include<string.h>  
#include<algorithm>  

using namespace std;

struct Edge
{
	int v;
	int w;
	int next;
};

Edge edge[50005 * 3];
int head[50005];
int dis[50005];
bool visited[50005];
int sta[50005];
int n;
int a, b, c;
int num = 0;

void AddEdge(int u, int v, int w)
{
	edge[num].v = v;
	edge[num].w = w;
	edge[num].next = head[u];
	head[u] = num++;
}

void Spfa(int s)
{
	fill(dis, dis + 50005, -99999999);

	int top = 1;
	dis[s] = 0;
	visited[s] = 1;
	sta[top] = s;

	while (top)
	{
		int u = sta[top--];
		visited[u] = 0;
		for (int i = head[u]; i != -1; i = edge[i].next)
		{
			int v = edge[i].v;
			if (dis[v] < dis[u] + edge[i].w)
			{
				dis[v] = dis[u] + edge[i].w;
				if (!visited[v])
				{
					sta[++top] = v;
					visited[v] = 1;
				}
			}

		}
	}
}


int main()
{
	scanf("%d", &n);

	memset(head, -1, sizeof(head));

	int maxx = -1;
	int minn = 99999999;
	for (int i = 0; i < n; i++)
	{
		scanf("%d%d%d", &a, &b, &c);
		AddEdge(a, b + 1, c);
		minn = min(a, minn);
		maxx = max(b + 1, maxx);
	}

	for (int i = minn; i < maxx; i++)
	{
		AddEdge(i, i + 1, 0);
		AddEdge(i + 1, i, -1);
	}

	Spfa(minn);

	printf("%d\n", dis[maxx]);

	return 0;
}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值