UOJ—47

【题目描述】:

给定一个长度为n的数列a,再给定一个长度为k的滑动窗口,从第一个数字开始依次框定k个数字,求每次框定的数字中的最大值和最小值,依次输出所有的这些值。下面有一个例子数组是 [1 3 1 3 5 6 7] , k 是3:

       窗口位置              窗口中的最小值   窗口中的最大值
[1  3  -1] -3  5  3  6  7            -1            3
 1 [3  -1  -3] 5  3  6  7            -3            3
 1  3 [-1  -3  5] 3  6  7            -3            5
 1  3  -1 [-3  5  3] 6  7            -3            5
 1  3  -1  -3 [5  3  6] 7             3            6
 1  3  -1  -3  5 [3  6  7]            3            7

【输入描述】:

第一行包含两个整数 n 和 k ,分别表示数组的长度和滑动窗口长度。

第二行n个整数,表示数列元素的值。

【输出描述】:

第一行从左到右窗口看到的最小值。

第二行从左到右窗口看到的最大值。

【样例输入】:

8 3
1 3 -1 -3 5 3 6 7

【样例输出】:

-1 -3 -3 -3 3 3
3 3 5 5 6 7

【时间限制、数据范围及描述】:

时间:1s 空间:64M

30%:n<=100 k<=20

60%:n<=5000 k<=20

100%:n<=10^6,每个元素不操过int类型

需要读入输出优化

源文件:answer

语言

C++Python2.7Java7C++11Python3Java8CPascal

使用编辑器上传

从本地文件上传

使用高级编辑器

浏览

提交

源文件:answer

语言

C++Python2.7Java7C++11Python3Java8CPascal

使用编辑器上传

从本地文件上传

使用高级编辑器

浏览

文本文件:input.txt

使用编辑器上传

从本地文件上传

使用高级编辑器

浏览

运行

#include "iostream"
#include "cstdio"
#include "cstdlib"
#include "cmath"
#include "cstring"
#include "algorithm"
using namespace std;
const int maxn = 1e6 + 10;
inline void write(int x) {
	if(x<0) putchar('-'),x=-x;
	if(x>9) write(x/10);
	putchar(x%10+'0');
}
int n, m;
struct node {
	int pos, value;
	node() {}
	node(int pos,int value) {
		this->pos = pos;
		this->value = value;
	}
} p[maxn];
int a[maxn];
void get_max() {
	int head = 0, tail = 0;
	for (int i = 1; i <= n; ++i) {
		while(head < tail && i - p[head].pos >= m) head++;
		while(head < tail && a[i] > p[tail - 1].value) tail--;
		p[tail++] = node(i,a[i]);
		if (i >= m) {
			write(p[head].value);
			putchar(i == n?'\n':' ');
		}//printf("%d%c", p[head].value, i == n?'\n':' ');
	}
}
void get_min() {
	int head = 0, tail = 0;
	for (int i = 1; i <= n; ++i) {
		while(head < tail && i - p[head].pos >= m) head++;
		while(head < tail && a[i] < p[tail - 1].value) tail--;
		p[tail++] = node(i, a[i]);
		if (i >= m) {
			write(p[head].value);
			putchar(i == n?'\n':' ');
		} //printf("%d%c", p[head].value, i == n?'\n':' ');
	}
}
int main() {
	while(scanf("%d%d", &n, &m) != EOF) {
		for (int i = 1; i <= n; ++i)
			scanf("%d", &a[i]);
		get_min();
		get_max();
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/to_more_excellent/article/details/81589610
47