200228题(网易(排序+二分))

在这里插入图片描述
在这里插入图片描述

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <unordered_map>
using namespace std;
const int maxn = 100000;
struct node
{
	int hardness;
	int salary;
}partners[maxn], works[maxn];//创建结构体数组变量

int cmp(node a, node b) {//升序
	if (a.hardness == b.hardness)
	{
		return a.salary > b.salary;
	}
	return a.hardness < b.hardness;
}

int binarySearch(node a[], int low, int high, int target)//在升序数组中找到target的下标(如果有),没有就找小于target的最大值下标
{
	while (low <= high)
	{
		int mid = (low + high) / 2;
		if (a[mid].hardness == target)
		{
			return mid;
		}
		else if (a[mid].hardness < target)
		{
			low = mid + 1;
		}
		else
			high = mid - 1;
	}
	return high;//注意
}
int main()
{
	int M, N;
	cin >> N >> M;//N个工作,M个小伙伴
	for (int i = 0; i < N; i++)
	{
		cin >> works[i].hardness >> works[i].salary;
	}
	sort(works, works + N, cmp);
	//工作难度不一定与报酬成正比(这tm贼坑啊,浪费我好多时间)
	//更新每个工作的报酬为当前难度所能获取的最大报酬
	for (int i = 1; i < N; i++) {
		works[i].salary = max(works[i - 1].salary, works[i].salary);

	}

	for (int i = 0; i < M; i++)
	{
		cin >> partners[i].hardness;
		//二分查找选择工作并输出工资
		int index = binarySearch(works, 0, N - 1, partners[i].hardness);
		if (index == -1)
			cout << 0 << endl;
		else
			cout << works[index].salary << endl;
	}


	system("pause");
	return 0;
}

发布了212 篇原创文章 · 获赞 4 · 访问量 8813

猜你喜欢

转载自blog.csdn.net/ShenHang_/article/details/104436112