栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

1021. 可旋栈

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

1021. 可旋栈



第一次见到这种写法所以补充一下

思路:
这道题一开始用的办法就是最傻的办法
1,2就不用说了吧,3的话就把数组整个换个顺序

#include 
#include 
using namespace std;
int n;
struct STACK
{
	int top,data[1111111]={-1};
	void init()
	{
		top=0;
	}
	int size()
	{
		return top;
	}
	void pop()
	{
		top--;
	}
	void push(const int &x)
	{
		top++;
		data[top]=x;
	}
}st;
int main()
{
	int x,y;
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>x;
		if(x==1)
		{
			cin>>y;
			st.push(y);
            cout< 

看了看数据范围这是显然会超时的

然后了解还有种办法:可以搞个flag标记到底哪里是正着放还是反着放,数组只要稍微开大一点就行。
我写的代码:

#include 
#include 
using namespace std;
struct QUEUE
{
	int head,tail,data[6666666];
	void init()
	{
		head=300000;
		tail=300000;
	}
	int  size()
	{
		return tail-head;
	}
	int front()
	{
		return data[head];
	}
	int back()
	{
		return data[tail-1];
	}
	void pop_back()
	{
		tail--;
	}
	void pop_front()
	{
		head++;
	}
	void push_back(const int &x)
	{
		data[tail]=x;
		tail++;
	}
	void push_front(const int &x)
	{
		head--;
		data[head]=x;
	}
}qu;
int main()
{
	int q;
	cin>>q;
	int flag=0;
	qu.init();
	for(int i=1;i<=q;i++)
	{
		int x;
		cin>>x;
		if(x==1)
		{
			int y;
			cin>>y;
			if(flag==0) qu.push_back(y);
			if(flag==1) qu.push_front(y);
		}
		if(x==2)
		{
			if(qu.size()==0) continue;
			if(flag==0) qu.pop_back();
			if(flag==1) qu.pop_front();
		}
		if(x==3) flag=flag^1;
		if(qu.size()==0) cout<<"-1"< 

大佬的代码:
简洁版:

#include 
int a[666666],head,tail,q;
bool status=0;
int main()
{
	head=tail=300010;
	tail--;
	scanf("%d",&q);
	for (int i=1;i<=q;i++)
	{
		int op;//option
		scanf("%d",&op);
		if (op==1)
		{
			int x;
			scanf("%d",&x);
			tail+=status^1;
			head-=status;
			a[status?head:tail]=x;
		}
		else if (op==2)
		{
			tail-=status^1;
			head+=status;
		}
		else status^=1;
		printf("%dn",head>tail?-1:a[status?head:tail]);
	}
	return 0;
}

规范版:

#include 
struct deque
{
	int a[666666],head=300010,tail=300010-1;
	void push_back(const int &x)
	{
		a[++tail]=x;
	}
	void push_front(const int &x)
	{
		a[--head]=x;
	}
	void pop_back()
	{
		--tail;
	}
	void pop_front()
	{
		++head;
	}
	int back()
	{
		return a[tail];
	}
	int front()
	{
		return a[head];
	}
	bool empty()
	{
		return head>tail;
	}
}de;
bool status=0;
int q;
int main()
{
	scanf("%d",&q);
	for (int i=1;i<=q;i++)
	{
		int op;//option
		scanf("%d",&op);
		if (op==1)
		{
			int x;
			scanf("%d",&x);
			if (!status) de.push_back(x);
			else de.push_front(x);
		}
		else if (op==2)
		{
			if (!status) de.pop_back();
			else de.pop_front();
		}
		else status^=1;
		printf("%dn",de.empty()?-1:(status?de.front():de.back()));
	}
	return 0;
}

tips:
虽然是第一次见,但是还是渐渐对这个^(异或)有了一定的感觉
1^1=0;
1^0=1;
能够很巧妙的在1和0之间转换

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/312309.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号