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);
	}
}

 

 

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