poj 1716 Integer Intervals (差分约束 或 贪心)

时间:2023-03-08 16:50:36
poj 1716 Integer Intervals (差分约束 或 贪心)
Integer Intervals
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 12192   Accepted: 5145

Description

An integer interval [a,b], a < b, is a set of all consecutive integers beginning with a and ending with b. 
Write a program that: finds the minimal number of elements in a set containing at least two different integers from each interval.

Input

The first line of the input contains the number of intervals n, 1 <= n <= 10000. Each of the following n lines contains two integers a, b separated by a single space, 0 <= a < b <= 10000. They are the beginning and the end of an interval.

Output

Output the minimal number of elements in a set containing at least two different integers from each interval.

Sample Input

4
3 6
2 4
0 2
4 7

Sample Output

4

Source

参考: http://blog.csdn.net/lyy289065406/article/details/6648679

贪心算法的思想我没证明,是参考别人的 ,不过不知道代码为什么没有过..所以就不贴出来了

差分约束的算法我自己也想了一下,其实并不难,不知道为什么老是错..可能poj的数据比较大吧

所以代码我也是参考别人的,自己的改了一段时间还没改好就没改了,贴一下:

 //Accepted    324K    297MS    C++    1088B    2013-12-01 22:11:55
/* 题意:
给出n个区间[ai,bi],求在每个区间内最少有两个数的一组数 差分约束:
S[ai - 1] <= S[bi] - 2
S[i] <= S[i - 1] + 1
S[i - 1] <= S[i] 自己看着建吧.. */
#include<iostream>
#include<queue>
#include<string.h>
#define N 10005
#define inf 0x7ffffff
using namespace std;
struct node{
int s,e;
}edge[N];
int d[N];
int n,up,down;
void bellman_ford()
{
memset(d,,sizeof(d));
int flag=;
while(flag){
flag=;
for(int i=;i<n;i++)
if(d[edge[i].s]>d[edge[i].e]-){
d[edge[i].s]=d[edge[i].e]-;
flag=;
}
for(int i=down;i<up;i++)
if(d[i+]>d[i]+){
d[i+]=d[i]+;
flag=;
}
for(int i=up-;i>=down;i--)
if(d[i]>d[i+]){
d[i]=d[i+];
flag=;
}
}
}
int main(void)
{
while(cin>>n)
{
up=;
down=n;
for(int i=;i<n;i++){
int a,b;
cin>>a>>b;
edge[i].s=a;
edge[i].e=b+;
if(down>a) down=a;
if(up<b+) up=b+;
}
bellman_ford();
cout<<d[up]-d[down]<<endl;
}
return ;
}