描述
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.
输入
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 the minimal number of elements in a set containing at least two different integers from each interval.
样例输入
4 3 6 2 4 0 2 4 7
样例输出
4
只看样例是不是很激动啊,这题样例和贪心算法1中整理的一个题一模一样,但是,你会发现输出结果不一样哦。我大概看了一下题发现这提要求有tow,难道前后间距不小于2?
错误代码:
#include<iostream>
#include<algorithm>
using namespace std;
struct A
{
int begin;
int end;
}ff[101];
bool cmp(A x,A y)
{
return x.end<y.end;
}
int main()
{
int i,n,sum=0;
cin>>n;
for(i=0;i<n;i++)
cin>>ff[i].begin>>ff[i].end;
sort(ff,ff+n,cmp);
for(i=0;i<n;i++)
{
if(ff[i+1].begin-ff[i].end<=2)
{
++sum;
}
}
cout<<sum<<endl;
return 0;
}
还是应该仔细翻译题目哦
描述
整数间隔[a,b],a<b,是以a开头和以b结尾的所有连续整数的集合。
编写一个程序,该程序:在包含至少两个不同整数的集合中找到每个间隔的最小元素数。
输入
输入的第一行包含间隔数n,1<=n<=10000。以下n行中的每一行都包含由单个空格分隔的两个整数a、b,0<=a<b<=10000。它们是间隔的开始和结束。
输出
输出包含来自每个间隔的至少两个不同整数的集合中的最小元素数。
第二次尝试(超时)
#include<iostream>
#include<algorithm>
using namespace std;
struct A
{
int begin;
int end;
}ff[101];
bool cmp(A x,A y)
{
return x.end<y.end;
}
int main()
{
int i,n;
cin>>n;
for(i=0;i<n;i++)
cin>>ff[i].begin>>ff[i].end;
sort(ff,ff+n,cmp);
int b=ff[0].end-1;
int c=ff[0].end;
int sum=2;
for(i=1;i<n;i++)
{
if(c<ff[i].begin)
{
sum+=2;
b=ff[i].end-1;
c=ff[i].end;
}
else if(ff[i].begin>b&&ff[i].begin<=c)
{
sum++;
b=c;
c=ff[i].end;
}
}
cout<<sum<<endl;
return 0;
}
哎呀,事不过三哦
#include<iostream>
#include<algorithm>
using namespace std;
struct A
{
int begin;
int end;
}ff[10001];
bool cmp(A x,A y)
{
return x.end<y.end;
}
int main()
{
int i,n;
cin>>n;
for(i=0;i<n;i++)
cin>>ff[i].begin>>ff[i].end;
sort(ff,ff+n,cmp);
int b=ff[0].end-1;
int c=ff[0].end;
int sum=2;
for(i=1;i<n;i++)
{
if(c<ff[i].begin)
{
sum+=2;
b=ff[i].end-1;
c=ff[i].end;
}
else if(ff[i].begin>b&&ff[i].begin<=c)
{
sum++;
b=c;
c=ff[i].end;
}
}
cout<<sum<<endl;
return 0;
}
其实只要把ff数组开大一点就OK了
为了加强记忆,还是把贪心1整理的类似题目搬过来吧
8.正数区间
整数区间。请编程完成以下任务:
1. 读取闭区间的个数及它们的描述;
2.找到一个含元素个数最少的集合,使得对于每一个区间,都至少有一个整数属于该集合,输出该集合的元素个数。
【输入】
首行包括区间的数目n,1<=n<=10000,接下来的n行,每行包括两个整数a,b,被一空格隔开,0<=a<=b<=10000,它们是某一个区间的开始值和结束值。
【输出】
第一行集合元素的个数,对于每一个区间都至少有一个整数属于该区间,且集合所包含元素数目最少。
【样例输入】
4
3 6
2 4
0 2
4 7
【样例输出】
2
原文链接:https://blog.csdn.net/weixin_45901806/article/details/104673051