【C++】c++中栈 队列 的应用

C++中提供了STL模板statck 在使用的时候更为方便

除了一般的队列外 还有STL更有双向队列可以使用 #include<deque> 声明:deque <type > name

应用举例1:铁轨问题

Description

There is a famous railway station in PopPush City. Country there is incredibly hilly. The station was built in last century. Unfortunately, funds were extremely limited that time. It was possible to establish only a surface track. Moreover, it turned out that the station could be only a dead-end one (see picture) and due to lack of available space it could have only one track. 

The local tradition is that every train arriving from the direction A continues in the direction B with coaches reorganized in some way. Assume that the train arriving from the direction A has N <= 1000 coaches numbered in increasing order 1, 2, ..., N. The chief for train reorganizations must know whether it is possible to marshal coaches continuing in the direction B so that their order will be a1, a2, ..., aN. Help him and write a program that decides whether it is possible to get the required order of coaches. You can assume that single coaches can be disconnected from the train before they enter the station and that they can move themselves until they are on the track in the direction B. You can also suppose that at any time there can be located as many coaches as necessary in the station. But once a coach has entered the station it cannot return to the track in the direction A and also once it has left the station in the direction B it cannot return back to the station.

Input

The input consists of blocks of lines. Each block except the last describes one train and possibly more requirements for its reorganization. In the first line of the block there is the integer N described above. In each of the next lines of the block there is a permutation of 1, 2, ..., N. The last line of the block contains just 0.

The last block consists of just one line containing 0.

Output

The output contains the lines corresponding to the lines with permutations in the input. A line of the output contains Yes if it is possible to marshal the coaches in the order required on the corresponding line of the input. Otherwise it contains No. In addition, there is one empty line after the lines corresponding to one block of the input. There is no line in the output corresponding to the last ``null‘‘ block of the input.

Sample Input

5
1 2 3 4 5
5 4 1 2 3
0
6
6 5 4 3 2 1
0
0

Sample Output

Yes
No

Yes

/*************************************************************************
    > File Name: 6_2.cpp
    > Author:KID_XiaoYuan
    > Mail:[email protected]
    > Created Time: 2017年06月05日 星期一 18时41分08秒
    > 算法描述:Rails :判断输入的数字能否通过栈的方式后输出 如果可以 输出YES否则输出NO
    > 样例输入: 5
                 1 2 3 4 5
                 3 4 5 2 1
    > 样例输出:YES
    > 参考更高效代码:p141
 ************************************************************************/
#include<stack>
#include<iostream>
#define MAX 100
using namespace std;
int input[MAX];
int input2[MAX];

int main()
{
    stack<int> s;
    int n,j = 0,k = 0 ;
    scanf("%d",&n);
    for(int i = 0; i < n; i++)
    {
        scanf("%d",&input[i]);
    }

    for(int i =0; i < n; i++)
    {
        scanf("%d",&input2[i]);
    }
    while(j < n)
    {
        s.push(input[j]);
        while(k < n && (s.top() == input2[k]))
        {
            s.pop();
            k++;
        }
        j++;
    }
    printf("%s\n",(s.empty()?"YES":"NO"));

    return 0;
}

改进版本:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<stack>
#include<algorithm>
using namespace std;
int main()
{
    int n;
    int target[2200];
    while(~scanf("%d",&n))///输入也是个大问题啊。。
    {
        if(n == 0) return 0;
        while(~scanf("%d",&target[1]))
        {
            if(target[1] == 0)///首先判断输入的第一个数
            {
                puts("");///不要忘记换行.
                break;
            }
            for(int i = 2; i <= n; i++)
                scanf("%d",&target[i]);
            int a,b;
            a = b = 1;
            stack<int> s;
            bool mark = true;
            while(b <= n)///这就是判断是否符合出栈规则的核心;
            {
                if(a == target[b])///判断重位的元素;
                {
                    a++;
                    b++;
                }
                else if(!s.empty() && s.top() == target[b])///判断先进后出的规则,可以想象成倒叙。
                {
                    s.pop();
                    b++;
                }
                else if(a <= n)///之所以能这样,关键是因为入栈的顺序是连续的1~n数字;
                {
                    s.push(a);
                    a++;
                }
                else
                {
                    mark = false;
                    break;
                }
            }
            if(mark == true) printf("Yes\n");
            else printf("No\n");
        }

    }

}

应用实例2:

Matrix multiplication problem is a typical example of dynamical programming.

Suppose you have to evaluate an expression like A*B*C*D*E where A,B,C,D and E arematrices. Since matrix multiplication is associative, the order in which multiplications areperformed is arbitrary. However, the number of elementary multiplications neededstrongly depends on the evaluation order you choose.
For example, let A be a 50*10 matrix, B a 10*20 matrix and C a 20*5 matrix.
There are two different strategies to compute A*B*C, namely (A*B)*C and A*(B*C).
The first one takes 15000 elementary multiplications, but the second one only 3500.

Your job is to write a program that determines the number of elementary multiplicationsneeded for a given evaluation strategy.

Input Specification

Input consists of two parts: a list of matrices and a list of expressions.
The first line of the input file contains one integer n (1 <= n <= 26),representing the number of matrices in the first part.The next n lines each contain one capital letter, specifying thename of the matrix, and two integers, specifying the number of rows and columns of the matrix.
The second part of the input file strictly adheres to the following syntax (given in EBNF):

SecondPart = Line { Line } <EOF>
Line       = Expression <CR>
Expression = Matrix | "(" Expression Expression ")"
Matrix     = "A" | "B" | "C" | ... | "X" | "Y" | "Z"

Output Specification

For each expression found in the second part of the input file, print one line containingthe word "error" if evaluation of the expression leads to an error due to non-matching matrices.Otherwise print one line containing the number of elementary multiplications needed to evaluate the expression in the way specified by the parentheses.

Sample Input

9
A 50 10
B 10 20
C 20 5
D 30 35
E 35 15
F 15 5
G 5 10
H 10 20
I 20 25
A
B
C
(AA)
(AB)
(AC)
(A(BC))
((AB)C)
(((((DE)F)G)H)I)
(D(E(F(G(HI)))))
((D(EF))((GH)I))

Sample Output

0
0
0
error
10000
error
3500
15000
40500
47500
15125
/*************************************************************************
    > File Name: 6_3.cpp
    > Author:KID_XiaoYuan
    > Mail:[email protected]
    > Created Time: 2017年06月05日 星期一 19时25分21秒
 ************************************************************************/

#include<iostream>
#include<string>
#include<stack>

using namespace std;

typedef struct Data
{
    public:
    char name;
    int a,b;

    /*void input (char &name ,int &a , int &b)
    {
        name = name;
        a = a;
        b = b;
    }*/

}data;

int main()
{
    data m[26];
    stack<data> s;
    int n;
    cin>>n;//输入元素个数
    for(int i = 0; i < n; i++)//输入元素信息
    {
        char name;
        cin>>name;
        cin>>m[name- ‘A‘].a>>m[name-‘A‘].b;
    }
    bool error = false;
    string str;//输入计算字符串
    cin>>str;
    int ans = 0;
   for(int i =0; i < str.length();i++)
    {
       if(isalpha(str[i]))//判断是否为字母
        {
            s.push(m[ str[i] - ‘A‘] );
        }
        else if( str[i] == ‘)‘)//如果是)则需要计算
        {
            data m1, m2;
            m2 = s.top();
            s.pop();
            m1 = s.top();
            s.pop();

            if(m1.b != m2.a)
            {
                printf("ERROR DATA : M1.B = %d M2.A = %d\n",m1.b,m2.a);
                error = true;
                break;
            }
            ans += m1.a * m1.b * m2.b;
            data c;
            c.a = m1.a;
            c.b = m2.b;
            s.push(c);
        }

    }
    error ? (printf("error\n")) : (printf("%d\n",ans));
    return 0;
}
时间: 2024-11-05 10:32:22

【C++】c++中栈 队列 的应用的相关文章

STL中栈和队列的使用方法

 STL 中优先队列的使用方法(priority_queu) 基本操作: empty() 如果队列为空返回真 pop() 删除对顶元素 push() 加入一个元素 size() 返回优先队列中拥有的元素个数 top() 返回优先队列对顶元素 在默认的优先队列中,优先级高的先出队.在默认的int型中先出队的为较大的数. 使用方法: 头文件: #include <queue> 声明方式: 1.普通方法: priority_queue<int>q; //通过操作,按照元素从大到小的顺

C++中 栈和队列的使用方法

C++中 栈和队列已经被封装好,我们使用时只需要按照如下步骤调用即可. 1.包含相关的头文件 包含栈头文件: #include<stack> 包含队列头文件: #include<queue> 2.作相关定义 定义栈如下: stack<int> stk; 定义队列如下: queue<int> q; 3.使用相关操作 栈提供了如下的操作: s.empty() 如果栈为空返回true,否则返回falses.size() 返回栈中元素的个数s.pop() 删除栈顶元

&lt;数据结构与算法分析 C++描述&gt; 表/栈/队列

这一章主要内容: * 抽象数据类型(ADT)的概念 * 实现表/栈/队列 * 了解这三个数据结构的应用场景 1. ADT ADT: abstract data type, 是抽象的数学模型,在该模型上定义了一系列的操作.使用它的人,不需要了解它的存储方式,只关心它的逻辑特征.可以使用三元组的方法来表示(D,S,P),D是数据对象,S是数据之间的关系,P是对数据的基本操作,具体介绍,可以参考帖子:点击打开链接 2. 表ADT 表的数据自然是单个元素,而元素之间的关系是前驱与后继,操作包括查找/插入

【C/C++学院】0828-STL入门与简介/STL容器概念/容器迭代器仿函数算法STL概念例子/栈队列双端队列优先队列/数据结构堆的概念/红黑树容器

STL入门与简介 #include<iostream> #include <vector>//容器 #include<array>//数组 #include <algorithm>//算法 using namespace std; //实现一个类模板,专门实现打印的功能 template<class T> //类模板实现了方法 class myvectorprint { public: void operator ()(const T &

C语言栈队列实现二-十/二-八进制转换

C语言栈队列实现二-十/二-八进制转换 2015-04-05 Lover雪儿 1 //利用栈来求取二进制数的十进制与八进制的结果 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <math.h> 5 6 #define STACK_INIT_SIZE 20 //初始栈大小 7 #define STACK_INCREMENT 10 //扩充栈时每次增加的内存 8 9 typedef char ElemType;

java面向对象的栈 队列 优先级队列的比较

栈 队列 有序队列数据结构的生命周期比那些数据库类型的结构(比如链表,树)要短得多.在程序操作执行期间他们才被创建,通常用他们去执行某项特殊的任务:当完成任务之后,他们就会被销毁.这三个数据结构还有一个特点就是访问是受到限制的,即在特定时刻只有一个数据项可以被读取或者被删除,但是所谓的移除并不是真的删除,数据项依然在这些数据结构中,只不过因为指针已经指向其他数据项,没有办法访问到,当添加新的数据项时,当初移除的数据项被替代从而永远消失. 栈 队列 优先级队列的模拟思想 1.栈:栈遵循先进后出(F

java 集合 Connection 栈 队列 及一些常用

800x600 Normal 0 7.8 磅 0 2 false false false EN-US ZH-CN X-NONE MicrosoftInternetExplorer4 /* Style Definitions */ table.MsoNormalTable {mso-style-name:普通表格; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priori

java中使用队列:java.util.Queue (转)

Queue接口与List.Set同一级别,都是继承了Collection接口.LinkedList实现了Queue接 口.Queue接口窄化了对LinkedList的方法的访问权限(即在方法中的参数类型如果是Queue时,就完全只能访问Queue接口所定义的方法 了,而不能直接访问 LinkedList的非Queue的方法),以使得只有恰当的方法才可以使用.BlockingQueue 继承了Queue接口. 队列是一种数据结构.它有两个基本操作:在队列尾部加人一个元素,和从队列头部移除一个元素就

栈&队列的简单实现

栈的定义---Stack 栈只允许在栈的末端进行插入和删除的线性表.栈具有先进后出的特性. 栈可用顺序表实现也可用链表实现. 但: 由于栈只能在末端进行操作,应使用顺序表实现. 用顺序表实现,有如下优点: (1)方便管理 (2)效率高 (3)cpu高速缓冲存取利用率高 实现如下: 测试如下: 队列的定义---Queue 队列只允许在队尾插入,队头删除.具有先进先出的特性. 队列的实现可用顺序表也可用链表. 若采用顺序表,删除时需要移动元素.为了操作方便,采取链表实现. 实现如下: 测试如下: 栈