week3 map,栈,队列

map

stl,提供一对一的hash
map<int, char> m;
m[1]='a';
m.insert(1,'a');
m.erase(1);
m.clear();//清除所有元素
m.empty();//如果为空返回1,负责返回0
m.size();//返回容器的元素个数

P3613 【深基15.例2】寄包柜

思路

这题用map就会方便很多

代码

#include<cstdio>
#include<bits/stdc++.h>
using namespace std;
int n,q,x,y,k,z;
map<int,map<int,int> > a;
int main(){
    cin>>n>>q;
    for(int i=1;i<=q;++i)
	{
		cin>>k>>x>>y;
        if(k==1)
		{
            cin>>z;
            a[x][y]=z;
        }
        else cout<<a[x][y]<<endl;
    }
	return 0;
} 

P1241 括号序列

思路

用栈来存储左括号对应的位置,检查到右括号时,从栈顶寻找与之对应的括号,找不到就说明需要另外给这个右括号配对一个左括号

代码

#include<bits/stdc++.h>
using namespace std;
int q[110],top;//q用来存储左括号对应的位置 
string s;
char a[110];//配对字符组 
int main()
{
	cin>>s;
	for (int i=0;i<s.length();i++)
	{
		if (s[i]=='(' || s[i]=='[')
		{
			q[++top]=i;//推进栈中,等待配对 
			if (s[i]=='(') a[i]=')';
			if (s[i]=='[') a[i]=']'; 
		}
		if (s[i]==')' || s[i]==']') 
		{
			if (a[q[top]]==s[i]) a[q[top]]=' ',top--;
			else 
			{
				if (s[i]==')') a[i]='(';
				if (s[i]==']') a[i]='[';
			}
		}
	}
	for (int i=0;i<s.length();i++)
	{
		if (a[i]=='(' || a[i]=='[') cout<<a[i];//输出配对
        cout<<s[i];//输出原来的字符
        if (a[i]==')' || a[i]==']') cout<<a[i];
	}
	return 0; 
}

P1449 后缀表达式

思路

用一个栈存储要运算的数字,另一个栈存储运算符号,一个符号对应两个数字

代码

#include<bits/stdc++.h>
using namespace std;
string s;
int a,b,q[100],top;
int main()
{
	cin>>s;
	for (int i=0;i<s.length();i++)
	{
		if (s[i]=='@') break;
		if (s[i]=='.')
		{
			q[++top]=a;
			a=0;
			b=0;
		}
		else if (s[i]>='0' && s[i]<='9')
		{
			a=b*10+(s[i]-'0');
			b=a;
		}
		else
		{
			int c,d;
			c=q[top]; top--;
			d=q[top]; top--;
			if (s[i]=='+') q[++top]=d+c;
			if (s[i]=='-') q[++top]=d-c;
			if (s[i]=='*') q[++top]=d*c;
			if (s[i]=='/') q[++top]=d/c;
		}
	}
	cout<<q[top]<<endl;
	return 0;
}

P1160 队列安排

思路

用结构体来实现链表,l表示左边的同学,r表示右边的同学,插入同学时,只需要更改对应同学的l和r即可

#include<bits/stdc++.h>
using namespace std;
int n,m;
struct node{
	int l,r,d; //l:左边 r:右边 d:判断是否要输出 
}a[100010];
void add(int i,int j,int p)//将i号同学插入到j号同学的左(1)/右(0)边 
{
	if (p==0)//左边
	{
		a[i].l=a[j].l;//i的左边是原本在j左边的人 
		a[i].r=j;//i的右边是j 
		a[a[j].l].r=i;//j原本左手牵的人,现在右手牵了i 
		a[j].l=i;//j的左边是i
		
	} 
	if (p==1)//右边 
	{
		a[i].l=j;//i的左边是j 
		a[i].r=a[j].r;//i的右边是原本在j右边的人
		a[a[j].r].l=i;//j原本右手牵的人,现在左手牵了i 
		a[j].r=i;//j的右边是i
	} 
}
int main()
{
	cin>>n;
	add(0,1,0); 
	for (int i=2;i<=n;i++)
	{
		int k,p;
		cin>>k>>p;
		add(i,k,p);
	}
	cin>>m;
	for (int i=1;i<=m;i++)
	{
		int x;
		cin>>x;
		a[x].d=1;
	}
	for (int i=a[0].r;i;i=a[i].r)
	{
		if (a[i].d==0) cout<<i<<" ";
	}
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值