远景8.29笔试

1.题目描述:给定一个排序好的数组,两个整数k和x,从数组中找到最靠近想x(两数之差最小)的k个数。

返回结果必须是升序拍好的。

如果两个数与x的差值一样,优先选择数值较小的那个数。

 

输入描述:

第一行为排好的数组arr

第二行为查找的个数k

第三行为基准值x

 

输出描述:

升序数组

 

示例:

输入

1,2,3,4,5

4

3

输出

1,2,3,4

#include<iostream>
#include<vector>
using namespace std;
void func(vector<int>& array, int& k, int& x) {
	vector<int>ans = array;
	while (ans.size() > k) {
		if ((x - *ans.begin()) <= (*(ans.end() - 1) - x)) {
			ans.pop_back();
		}
		else {
			ans.erase(ans.begin());
		}
	}
	for (int i = 0; i < ans.size() - 1; i++) {
		cout << ans[i] << ",";
	}
	cout << ans[ans.size() - 1] << endl;
}
int main() {
	vector<int>array;
	int temp = 0;
	//-----------------------注意这种输入方式
	cin >> temp;
	array.push_back(temp);
	while (cin.get() != '\n') {
		cin >> temp;
		array.push_back(temp);
	}
	//-----------------------
	int k = 0, x = 0;
	cin >> k;
	cin >> x;
	func(array, k, x);
	return 0;
}

2.

题目描述:

某风电场每台风机的发电量和距离升压站的距离各不相同,如风机1:发电量30,距离2;风机2:发电量35,距离25....,要求在输电总距离限定(如小于100)的前提下,选择风机向升压站输电,使得输送的发电量最大。

 

输入描述:

风机离升压站的距离,如20 30 40

风机的发电量,如20 30 40

输电总距离的限制,如50

 

输出描述:

输送电量的最大值

 

示例:

输入

30 20 35 40

20 18 25 30

50

输出

38

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void beibao(vector<int>& dis, vector<int>& value, int capacity) {
	vector<int>array(capacity + 1, 0);
	vector<vector<int>>matrix(dis.size() + 1, array);
	for (int i = 1; i < matrix.size(); i++) {//①前i个物品
		for (int j = 0; j < matrix[0].size(); j++) {//②容量为j
			//计算前i个物品 容量为j 的最大价值K(i,j)

			if (j >= dis[i - 1]) {//能容纳第i个物品可选择放或者不放 K(i,j)=max(K(i-1,j),K(i-1,j-dis_i)+value_i)
				matrix[i][j] = max(matrix[i - 1][j], matrix[i - 1][j - dis[i - 1]] + value[i - 1]);
			}
			else {//不能容纳第i个物品 K(i,j)=K(i-1,j)
				matrix[i][j] = matrix[i - 1][j];
			}
		}
	}
	cout << matrix[matrix.size()-1][matrix[0].size()-1] << endl;
}
int main() {
	vector<int>dis;
	vector<int>value;
	int temp = 0;
	//输入风机距离
	cin >> temp;
	dis.push_back(temp);
	while (cin.get() != '\n') {
		cin >> temp;
		dis.push_back(temp);
	}
	//输入风机发电量
	cin >> temp;
	value.push_back(temp);
	while (cin.get() != '\n') {
		cin >> temp;
		value.push_back(temp);
	}
	//输入距离限制
	int capacity = 0;
	cin >> capacity;
	beibao(dis, value, capacity);
	return 0;
}

典型的背包问题:http://www.imooc.com/article/details/id/283103

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值