初学双端队列

今天做了一道滑动窗口,感触很多,原本用最为朴素的方式写出来,但是在vjudege上面7发TLE。我人都傻了,后面我到洛谷找题,一发就过了。然后没办法,就把双端队列给学了。

这是题目:

 题意很明确,在窗口找最大最小值。

这个是我7发没过的代码

const int inf = 0x3f3f3f3f;
#include<iostream>
#include<cstdio>
using namespace std;
#define MAX 1000000
int counter[MAX] = { 0 };
int Max[MAX] = { 0 };
int a = 0, b = 0;
int temp1 = 0;
int temp2 = 0;

void com(int n[], int head, int end)
{
	int mi = inf;
	int ma = -inf;
	if (temp1 != 0 && temp2 != 0)
	{
		if (temp1 < head)
			temp1 = 0;
		else
		{
			if (n[temp1] > n[end])
			{
				mi = n[end];
				temp1 = end;
			}
			else
			{
				mi = n[temp1];
			}
		}

		if (temp2 < head)
			temp2 = 0;
		else
		{
			if (n[temp2] < n[end])
			{
				ma = n[end];
				temp2 = end;
			}
			else
			{
				ma = n[temp2];
			}

		}
	}
	if(temp1==0||temp2==0)
	{
		for (int i = head; i <= end; i++)
		{
			if (mi > n[i])
			{
				mi = n[i];
				temp1 = i;
			}
			if (ma < n[i])
			{
				ma = n[i];
				temp2 = i;
			}
		}
	}

	
	cout << mi << " ";
	Max[b] = ma;
	b++;
}
int main()
{
	int n, k;
	cin >> n >> k;
	for (int i = 0; i < n; i++)
	{
		//scanf("%d", &counter[i]);
		cin>>counter[i];
		if (n - k > 0 && i - k >= -1)
		{
			com(counter, i - k + 1, i);
		}
	}
	if(n - k <= 0)
	{
		com(counter, 0, n - 1);
	}
	cout << endl;

	for (int i = 0; i < b; i++)
	{
		cout << Max[i] << " ";
	}

	return 0;
}

scanf 读取数据的速度比 cin要快!!!!

但是,在vjudge会TLE的!!!上面的代码最主要的缺点是,寻找最大最小值时,很容易把那些没用的数据多次遍历,导致时间复杂度上去了。因此,我们利用双端队列来解决,会快很多

//解释变量:
//1.arr[]是Window position 的数据
//2.n是数据总数
//3.k是滑动窗口的窗口长度
//这里要用到头文件<deque>

//代码函数展示:

void sq(int arr[],int n,int k)
{
    deque<int>max_queue;
    for(int i=0;i<n;i++)
    {
        while(!max_queue.empty() && max_queue.front<i-k+1)
                max_queue.pop_front();//将队头不在串口里面的元素出队列
        while(!max_queue.empty() && arr[max_queue.back()]<arr[i])
                max-queue.pop_back();
        //后面的数据时效性更高,如果比原队尾大,那就不是满足条件的出队列
        max_queue.push_back(i);//将满足的入队
        if(i>=k-1)
            cout<<arr[max_queue.front]<<" ";
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值