stl的经典例题
- set和map很容易掌握。就不多赘述了。重点学习stack(栈)和 queue(队列)。
1.stack(栈)
结构特点:
后进先出(FILO)
常用的方法:
stack<char> s;
s.push()------入栈,压栈;
s.pop()------出栈,弹出;
s.empty()----判栈空;
s.top()----得到栈顶元素;
应用范围:
DFS,迷宫问题等等。
经典例题:
Train Problem I
火车按照给定顺序进站,判断是否可以按给定顺序出站,若能这输出YES.和 in,out的顺序和最后FINISH,否则输出NO.和FINISH
题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1022
AC代码如下:
#include<stdio.h>
#include<string.h>
#include<stack>
using namespace std;
int main()
{
int n, i, j, k, flag[50];//记录in out的数组
char s1[15], s2[15];
stack <char> s;
while(~scanf("%d %s%s",&n,s1,s2))
{
while(!s.empty())
s.pop(); //清空栈,类似于set.clear();
memset(flag,-1,sizeof(flag));
j = k = 0;
for(i = 0; i < n; i++)
{
s.push(s1[i]);
flag[k++] = 1;
while(!s.empty() && s.top() == s2[j])
{
flag[k++] = 0;//当栈顶元素与s2(出站顺序一样时就出站);
s.pop();
j++;
}
}
if(j == n) //当所有元素都出站,就符合要求;
{
printf("Yes.\n");
for(i = 0; i < k; i++)
{
if(flag[i])
printf("in\n");
else
printf("out\n");
}
}
else
printf("No.\n");
printf("FINISH\n");
}
return 0;
}
2. queue(队列)
结构特点:
先进先出(FIFO)
常用的方法:
queue<int> q;
q.push()------入队;
q.pop()------出队;
q.empty()----判队空;
q.front()----得到队头元素;
q.back()----得到队尾元素;
应用范围:
BFS,搜索问题等等。
经典例题
A strange lift
此电梯每层只有上下两个按钮,且只能跨越固定的楼数,给出出发点A和目的地B,求最少按电梯多少次?
题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1548
AC代码:
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int T,N,A,B;
int mp[220],f[220];
//mp表示每层楼的跨度,f表示该楼层是按第几次按钮到达的;
void BFS_Find(){
queue<int>q;
q.push(A);
f[A]=1;
int t;
while(!q.empty()){
t=q.front();
q.pop();
if(t==B)break; //对于每个上下的选择造成的二叉树进行遍历。
int next=t+mp[t];
if(next>=1&&next<=B&&f[next]==0){
q.push(next);
f[next]=f[t]+1;
}
next=t-mp[t];
if(next>=0&&next<=B&&f[next]==0){
q.push(next);
f[next]=f[t]+1;
}
}
if(t!=B)
f[B]=0;
}
int main()
{
int i,j;
while(scanf("%d",&N)&&N){
if(N==0)break;
scanf("%d%d",&A,&B);
for(i=1;i<=N;i++)
scanf("%d",&mp[i]);
memset(f,0,sizeof(f));
BFS_Find();
printf("%d\n",f[B]-1);
}
return 0;
}
3. 其他STL
- priority_queue(优先队列)
- 定义:
优先队列与队列的差别在于优先队列不是按照入队的顺序出队,而是按照队列中元素的优先权顺序出队(默认为大者优先,也可以通过指定算子来指定自己的优先顺序); - 应用:
个人认为讲的比较好的优先队列博客链接参考:
http://blog.youkuaiyun.com/chao_xun/article/details/8037438
- 定义: