您的位置:首页 > 其它

poj 1716 Integer Intervals

2017-03-10 11:27 267 查看
[b] Integer Intervals[/b]
http://poj.org/problem?id=1716

Time Limit: 1000MSMemory Limit: 10000K
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

CEOI 1997
题目大意:在指定的几个区间中选出最少的数,使每个区间至少包含这些数中的2个,求最少多少数
解法一:贪心
把所有的区间按右端点从小到大排序
初始时,假设这两个数x,y为第一个区间最右边的2个数,x<=y,ans=2
如果下一个区间左端点<=x,跳过
如果下一个区间的左端点在>x 且<=y,令x=y,y=当前区间右端点,ans++
如果下一个区间的左端点>y x,y为当前区间最右边的两个数,ans+2

#include<cstdio>
#include<queue>
#include<cstring>
#include<algorithm>
#define N 10002
using namespace std;
int n,minn=10002,maxn;
queue<int>q;
struct node
{
int to,next,w;
}e[N*3];
int dis
,front
,tot;
bool v
;
void add(int u,int v,int w)
{
e[++tot].to=v;e[tot].next=front[u];front[u]=tot;e[tot].w=w;
}
int main()
{
int x,y;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d%d",&x,&y);y++;
add(x,y,2);
minn=min(x,minn);maxn=max(maxn,y);
}
for(int i=minn;i<maxn;i++)
{
add(i,i+1,0);add(i+1,i,-1);
}
memset(dis,-1,sizeof dis);
q.push(minn);v[minn]=true;dis[minn]=0;
while(!q.empty())
{
int now=q.front();q.pop();v[now]=false;
for(int i=front[now];i;i=e[i].next)
{
int to=e[i].to;
if(dis[to]<dis[now]+e[i].w)
{
dis[to]=dis[now]+e[i].w;
if(!v[to])
{
v[to]=true;
q.push(to);
}
}
}
}
printf("%d",dis[maxn]);
}


View Code
一个错误:N=10001,因为全体后移了一位,所以N最少是10002
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: