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;
}