题目是图片形式给出的,只能贴出地址:
http://acm.bupt.edu.cn/onlinejudge/newoj/showProblem/show_problem.php?problem_id=302
思路:
对于区间[Li,Ri),按照Li排序,然后对于每个方块区间[Li,Ri),判断当前所有层中最右边的方块的Rk是否小于等于Li,如果存在,则将[Li,Ri)放入该层,如果不存在,则新加一层。更新此层最右边方块为Ri。
开始的时候用数组Floor记录,每次扫描没一层,结果超时。
超时代码:
#include<iostream>
#include<algorithm>
using namespace std;
#define Max 100005
struct Range{
int left;
int right;
};
Range data[Max];
int Floor[Max];
int cmp(const Range &a,const Range &b)
{
return a.left<b.left;
}
int main()
{
int n;
while(~scanf("%d",&n))
{
int high=1;
for(int i=0;i<n;i++)
{
scanf("%d%d",&data[i].left,&data[i].right);
Floor[i]=0;
}
sort(data,data+n,cmp);
for(int i=0;i<n;i++)
{
int flag=false;
for(int k=1;k<=high;k++)
{
if(Floor[k]<=data[i].left)
{
flag=true;
Floor[k]=data[i].right;
break;
}
}
if(flag==false)
Floor[high++]=data[i].right;
}
printf("%d\n",high);
}
}
后来用优先队列,记录最小的Rk,AC
代码:
#include<iostream>
#include<algorithm>
#include<queue>
#include<functional>
using namespace std;
#define Max 100005
struct Range{
int left;
int right;
};
Range data[Max];
int cmp(const Range &a,const Range &b)
{
return a.left<b.left;
}
int main()
{
int n;
while(~scanf("%d",&n))
{
int high=1;
for(int i=0;i<n;i++)
scanf("%d%d",&data[i].left,&data[i].right);
sort(data,data+n,cmp);
priority_queue<int,vector<int>,greater<int> >que;
que.push(data[0].right);
for(int i=1;i<n;i++)
{
if(que.top()<=data[i].left)
que.pop();
else
high++;
que.push(data[i].right);
}
printf("%d\n",high);
}
}