您的位置:首页 > 其它

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

2016-04-01 10:46 375 查看
原题链接: 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: