Integer Intervals(贪心)

Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 12123   Accepted: 5129

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

题意:在数轴上给n个区间,区间上的点均是整数,再在数轴上取x个点构成的点集V使得V与上述每个区间的交集至少包含两个交点,输出满足题意的x的最小值。
思路:可以贪心,先按每个区间的有端点升序排序,
初始化:计数器 sum = 2,集合V的前两个元素selem,telem为第一个区间的最后两个整数;(selem和telem在整个循环中作为集合V的最后两个元素,所以必要时更新其值)
for:
  若第i+1个区间包含selem和telem,不需要做任何改变;
  若第i+1个区间只包含telem,更新selem和telem,sum加1;
  若第i+1个区间不包含selem和telem,更新selem和telem,sum加2;
 #include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std; struct node
{
int s,t;
}L[];
int cmp(const struct node &a, const struct node &b)
{
return a.t < b.t;
} int main()
{
int n;
scanf("%d",&n);
for(int i = ; i < n; i++)
scanf("%d %d",&L[i].s,&L[i].t);
sort(L,L+n,cmp);
int sum,selem,telem;
sum = ;
selem = L[].t-;
telem = L[].t;
for(int i = ; i < n;)
{
if(selem >= L[i].s && selem <= L[i].t && telem >= L[i].s && telem <= L[i].t)
i++;
else if(selem < L[i].s && telem >= L[i].s && telem <= L[i].t)
{
selem = telem;
telem = L[i].t;
sum++;
i++;
}
else if(selem < L[i].s && telem < L[i].s)
{
selem = L[i].t-;
telem = L[i].t;
sum += ;
i++;
}
}
printf("%d\n",sum);
return ;
}

上一篇:Java的继承和多态


下一篇:iOS WKWebview 网页开发适配指南