C++RMQ算法—————Find the hotel

题目描述:

  Summer again! Flynn is ready for another tour around. Since the tour would take three or more days, it is important to find a hotel that meets for a reasonable price and gets as near as possible! 
  But there are so many of them! Flynn gets tired to look for any. It’s your time now! Given the <p i, d i> for a hotel h i, where p i stands for the price and d i is the distance from the destination of this tour, you are going to find those hotels, that either with a lower price or lower distance. Consider hotel h 1, if there is a hotel h i, with both lower price and lower distance, we would discard h1. To be more specific, you are going to find those hotels, where no other has both lower price and distance than it. And the comparison is strict.

输入:

There are some cases. Process to the end of file. 
Each case begin with N (1 <= N <= 10000), the number of the hotel. 
The next N line gives the (p i, d i) for the i-th hotel. 
The number will be non-negative and less than 10000.

输出:

First, output the number of the hotel you find, and from the next line, print them like the input( two numbers in one line). You should order them ascending first by price and break the same price by distance.

样例输入:

3
15 10
10 15
8 9

样例输出:

1
8 9

思路分析:

这个题就是求先是价格少,再是距离的酒店。

由于这里有0的情况,所以我们要先加1。

我们可以根据相同价格求最短距离来求RMQ。

之后我们通过循环来做出当前点距离比相同价格中的距离情况作比较,小的就加入ans数组。

代码实现:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
int n,m,dp1[10005][22],a[10005];
struct node{
	int p,d;
}ho[10005],ans[10005];
int Get_quary(int l,int r)
{
	int k=(int)(log(double(r-l+1))/log(double(2)));
	return min(dp1[l][k],dp1[r-(1<<k)+1][k]);
}
bool cmp(node a,node b)
{
	return a.p<b.p||(a.p==b.p&&a.d<b.d);
}
int main()
{
	while(scanf("%d",&n)!=-1&&n>0)
	{
		memset(a,0x3f,sizeof(a));
		for(int i=1;i<=n;i++)
		{
			scanf("%d%d",&ho[i].p,&ho[i].d);
			ho[i].p++;
			ho[i].d++;
			a[ho[i].p]=min(ho[i].d,a[ho[i].p]);
		}
		for(int i=0;i<=10000;i++)
			dp1[i][0]=a[i];
		for(int j=1;(1<<j)<=10000;j++)
            for(int i=0;i+(1<<j)-1<10000;i++)
        	   dp1[i][j]=min(dp1[i][j-1],dp1[i+(1<<j-1)][j-1]);
        int tot=0;
        for(int i=1;i<=n;i++)
        {
        	int t=Get_quary(0,ho[i].p-1);
        	if(t>=ho[i].d)
        	{
        		tot++;
        		ans[tot].d=ho[i].d;
        		ans[tot].p=ho[i].p;
			}
		}
		sort(ans+1,ans+tot+1,cmp);
		printf("%d\n",tot);
		for(int i=1;i<=tot;i++)
			printf("%d %d\n",ans[i].p-1,ans[i].d-1);
	}
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章