NJU-高级算法-区间第k最小

Description

找到给定数组的给定区间内的第K小的数值。

Input

输入第一行为用例个数, 每个测试用例输入的第一行为数组,每一个数用空格隔开;第二行是区间(第几个数到第几个数,两头均包含),两个值用空格隔开;第三行为K值。

Output

结果。

Sample Input 1

1
1 2 3 4 5 6 7
3 5
2

Sample Output 1

4

 

思路

暴力

#include <iostream>
#include <vector>
#include <string.h>
#include <string>
#include <deque>
#include <sstream>
using namespace std;

int main()
{
    int t;
	cin >> t;
	for (int turn = 0; turn < t; turn++) {
		int res = 0, len;
		//将一组未知个数的数字读入一个动态数组数组vector a
		stringstream ss;
		string str;
		int sin;
		cin.ignore();
		getline(cin, str);

		vector<int> a;
		ss << str;

		while (ss >> sin) {
			a.push_back(sin);
		}
		int alen = a.size();

		cin >> len;

		//题目变为对数组a中aLen个数字进行滑动查找
		int sum = 0;
		if (len < 1 || alen < len || alen<1) {
			if (turn + 1 == t) {
				printf("%d", res);
			}
			else {
				printf("%d\n", res);
			}
		}
		else {
			int maxNum = 0;
			for (int i = len - 1; i < alen; i++) {
				maxNum = a[i];
				for (int j = i - 1; j > i - len; j--) {
					if (maxNum < a[j]) {
						maxNum = a[j];
					}
				}
				sum += maxNum;
			}
			res = sum;

			if (turn + 1 == t) {
				printf("%d", res);
			}
			else {
				printf("%d\n", res);
			}
		}
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值