32-吃货(二分+去逆序)

链接:https://www.nowcoder.com/acm/contest/105/E
来源:牛客网

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 32768K,其他语言65536K
64bit IO Format: %lld

题目描述

作为一个标准的吃货,mostshy又打算去联建商业街觅食了。
混迹于商业街已久,mostshy已经知道了商业街的所有美食与其价格,而且他给每种美食都赋予了一个美味度,美味度越高表示他越喜爱这种美食。
mostshy想知道,假如带t元去商业街,只能吃一种食物,能够品味到的美食的美味度最高是多少?

输入描述:

第一行是一个整数T(1 ≤ T ≤ 10),表示样例的个数。
以后每个样例第一行是两个整数n,m(1 ≤ n,m ≤ 30000),表示美食的种类数与查询的次数。
接下来n行,每行两个整数分别表示第i种美食的价格与美味度d
i
,c
i
(1 ≤ d
i
,c
i
 ≤ 10
9
)。
接下来m行,每行一个整数表示mostshy带t(1 ≤ t ≤ 10
9
)元去商业街觅食。

输出描述:

每个查询输出一行,一个整数,表示带t元去商业街能够品味到美食的最高美味度是多少,如果不存在这样的美食,输出0。
示例1

输入

1
3 3
1 100
10 1000
1000000000 1001
9
10
1000000000

输出

100
1000
1001

说明

大量的输入输出,请使用C风格的输入输出。

#include <bits/stdc++.h>
using namespace std;
#define ll long long

struct node {
	ll m;
	ll v;
};

node mp[30005];

bool cmp(node x, node y){
	return x.m < y.m;
}

ll er(int low, int high, int pp){
	while(low <= high){
		int mid = (low + high) >> 1;
		if(mp[mid].m == pp){
			return mp[mid].v;
		}
		else if(mp[mid].m < pp){
			low = mid + 1;
		}
		else{
			high = mid - 1;
		}
	}
	if(low == high){       //pp比最后一个mid对应的值大 
		return mp[low - 1].v;
	}
	else{ 
		return mp[high].v; //pp比最后一个mid对应的值小 
	}
}

int main(){
//	std::ios::sync_with_stdio(false);
	int t;
	cin >> t;
	while(t--){
		int n, m;
//		cin >> n >> m; 
		scanf("%d%d", &n, &m);
		for(int i = 0; i < n; i++){
//			cin >> mp[i].m >> mp[i].v;
			scanf("%d%d", &mp[i].m, &mp[i].v);
		}	
		sort(mp, mp + n, cmp);
		int max = -1;
		for(int i = 0; i < n; i++){    //思路:处理所有逆序,保证后面价格高的好感一定不低于前面的,保证不下降 
			if(max <= mp[i].v){
				max = mp[i].v;
			}
			else{
				mp[i].v = max;
			}
		}
		ll x;
		for(int i = 0; i < m; i++){
//			cin >> x;
			scanf("%d", &x);
			if(x < mp[0].m){
				cout << 0 <<endl;
				continue; 
			}
			printf("%lld
", er(0, n - 1, x));
		}
	}
	return 0;
}

  

原文地址:https://www.cnblogs.com/zhumengdexiaobai/p/8964187.html