队列、栈 2016.2.23

1、UVa 673 Parentheses Balance(括号平衡)
题意:输入字符串能两两配对或为空则正确

解题思路:用C++的stack对字符串中的元素进行判断
(1)、如果为”(”或”[”则进栈
(2)、若为”)”或”]”时
①栈为空,则标志位置1退出循环
②栈不为空,该元素如果可以与栈顶元素进行配对则出栈,否则标志位置1退出循环
(3)、判断完成后若栈为空且标志位为0,则输出”Yes”,否则输出”N0”

#include <iostream>
#include <cstdio>
#include <stack>
#include <cstring>

using namespace std;

int main()
{
    int n;
    char Parentheses[10010];

    while (cin>>n) {
        getchar();
        int len;
        int i;
        while (n--) {
            stack<char> s;
            gets(Parentheses);
            len = strlen(Parentheses);
            int flag = 0;
            for (i=0; i<len; ++i) {
                if (Parentheses[i]=='(' || Parentheses[i]=='[') {
                    s.push(Parentheses[i]);
                } else {
                    if (s.empty()) {
                        flag = 1;
                        break;
                    } else {
                        if ((Parentheses[i]==')'&&s.top()=='(') || (Parentheses[i]==']'&&s.top()=='[')) {
                            s.pop();
                        } else {
                            flag = 1;
                            break;
                        }
                    }
                }
            }
            if (0==flag && s.empty()) {
                cout<<"Yes"<<endl;
            } else {
                cout<<"No"<<endl;
            }
        }
    }
    return 0;
}

2、UVa 540 Team Queue(小团体队列)
题意:有t个团队,输入每个团队的成员个数和各个成员,再输入若干条指令,输出出队的成员

解题思路:用C++的map和queue
(1)、将t个团队放到map中
①map可以快速插入num - i 记录,i为团队编号(0到t-1),num为该团队中的成员
②map可以根据num值快速查找记录
(2)、开始队列为空,定义一个队列q和队列数组qs[], q用来对团队进行排队,qs[i]用来对该团队进队的成员排队
(3)、对于进队指令,如果该成员有队友在排队,则排到他所在团队的后面,否则排到大队列的队尾
具体做法:
①设该成员的团队编号为i,若该成员没有队友在队列中,即qs[i]为空,则先将i进到队列q中
②将该成员进到队列qs[i]中
(4)、对于出队指令,则是排在前面的团队的成员先逐一出队然后下一个团队的成员才能出队
具体做法:
①输出qs[q的队首的i]的队首的成员,再将它出队
②如果出队后qs[q的队首的i]为空,则对q进行出队

#include <iostream>
#include <queue>
#include <map>
#include <cstring>

using namespace std;

int main()
{
    int t;
    int Scenario = 1;
    int i;

    while (cin>>t && t!=0) {
        cout<<"Scenario #"<<Scenario<<endl;
        ++Scenario;
        int num, number;
        map<int, int> Map;
        for (i=0; i<t; ++i) {
            cin>>num;
            while (num--) {
                cin>>number;
                Map[number] = i;
            }
        }
        queue<int> q, qs[1010];
        char Command[10];
        cin>>Command;
        while (strcmp(Command, "STOP") != 0) {
            if (strcmp(Command, "ENQUEUE") == 0) {
                cin>>number;
                if (qs[Map[number]].empty()) {
                    q.push(Map[number]);
                }
                qs[Map[number]].push(number);
            }
            if (strcmp(Command, "DEQUEUE") == 0) {
                cout<<qs[q.front()].front()<<endl;
                qs[q.front()].pop();
                if (qs[q.front()].empty()) {
                    q.pop();
                }
            }
            cin>>Command;
        }
        cout<<endl;
    }
    return 0;
}

3、POJ 1028 Web Navigation

Description
Standard web browsers contain features to move backward and forward among the pages recently visited. One way to implement these features is to use two stacks to keep track of the pages that can be reached by moving backward and forward. In this problem, you are asked to implement this.
The following commands need to be supported:
BACK: Push the current page on the top of the forward stack. Pop the page from the top of the backward stack, making it the new current page. If the backward stack is empty, the command is ignored.
FORWARD: Push the current page on the top of the backward stack. Pop the page from the top of the forward stack, making it the new current page. If the forward stack is empty, the command is ignored.
VISIT : Push the current page on the top of the backward stack, and make the URL specified the new current page. The forward stack is emptied.
QUIT: Quit the browser.
Assume that the browser initially loads the web page at the URL http://www.acm.org/

Input
Input is a sequence of commands. The command keywords BACK, FORWARD, VISIT, and QUIT are all in uppercase. URLs have no whitespace and have at most 70 characters. You may assume that no problem instance requires more than 100 elements in each stack at any time. The end of input is indicated by the QUIT command.

Output
For each command other than QUIT, print the URL of the current page after the command is executed if the command is not ignored. Otherwise, print “Ignored”. The output for each command should be printed on its own line. No output is produced for the QUIT command.

Sample Input

VISIT http://acm.ashland.edu/
VISIT http://acm.baylor.edu/acmicpc/
BACK
BACK
BACK
FORWARD
VISIT http://www.ibm.com/
BACK
BACK
FORWARD
FORWARD
FORWARD
QUIT

Sample Output

http://acm.ashland.edu/
http://acm.baylor.edu/acmicpc/
http://acm.ashland.edu/
http://www.acm.org/
Ignored
http://acm.ashland.edu/
http://www.ibm.com/
http://acm.ashland.edu/
http://www.acm.org/
http://acm.ashland.edu/
http://www.ibm.com/
Ignored

#include <iostream>
#include <stack>
#include <cstdio>
#include <cstring>

using namespace std;

int main()
{
//    freopen("in.txt","r",stdin);
//    freopen("out.txt","w",stdout);
    stack<string>Stack1;
    stack<string>Stack2;
    char cmd[10];
    char web[80];
    Stack1.push("http://www.acm.org/");

    while (cin>>cmd && strcmp(cmd, "QUIT")!=0) {
        if (strcmp(cmd, "VISIT") == 0) {
            cin>>web;
            cout<<web<<endl;
            Stack1.push(web);
            while (!Stack2.empty()) {
                Stack2.pop();
            }
        } else if (strcmp(cmd, "BACK") == 0) {
            if (Stack1.size() <= 1) {
                cout<<"Ignored"<<endl;
            } else {
                Stack2.push(Stack1.top());
                Stack1.pop();
                cout<<Stack1.top()<<endl;
            }
        } else if (strcmp(cmd, "FORWARD") == 0) {
            if (Stack2.empty()) {
                cout<<"Ignored"<<endl;
            } else {
                cout<<Stack2.top()<<endl;
                Stack1.push(Stack2.top());
                Stack2.pop();
            }
        }
    }
    return 0;
}

4、POJ 1250 Tanning Salon
Description
Tan Your Hide, Inc., owns several coin-operated tanning salons. Research has shown that if a customer arrives and there are no beds available, the customer will turn around and leave, thus costing the company a sale. Your task is to write a program that tells the company how many customers left without tanning.

Input
The input consists of data for one or more salons, followed by a line containing the number 0 that signals the end of the input. Data for each salon is a single line containing a positive integer, representing the number of tanning beds in the salon, followed by a space, followed by a sequence of uppercase letters. Letters in the sequence occur in pairs. The first occurrence indicates the arrival of a customer, the second indicates the departure of that same customer. No letter will occur in more than one pair. Customers who leave without tanning always depart before customers who are currently tanning. There are at most 20 beds per salon.

Output
For each salon, output a sentence telling how many customers, if any, walked away. Use the exact format shown below.

Sample Input

2 ABBAJJKZKZ
3 GACCBDDBAGEE
3 GACCBGDDBAEE
1 ABCBCA
0

Sample Output

All customers tanned successfully.
1 customer(s) walked away.
All customers tanned successfully.
2 customer(s) walked away.

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

int main()
{
//    freopen("in.txt", "r", stdin);
//    freopen("out.txt", "w", stdout);
    int n;
    char s[100000];
    int len;
    int num[30];
    int leave_num[30];

    while (cin>>n && n!=0) {
        memset(num, 0, sizeof(num));
        memset(leave_num, 0, sizeof(leave_num));
        cin>>s;
        len = strlen(s);
        int i;
        int count = 0;
        int sum = 0;
        for (i=0; i<len; ++i) {
            if (num[s[i]-'A'] == 1) {
                num[s[i]-'A'] = 0;
                --sum;
            } else {
                if (sum == n) {
                    if (leave_num[s[i]-'A'] == 0) {
                        ++count;
                        leave_num[s[i]-'A'] = 1;
                    }
                } else {
                    num[s[i]-'A'] = 1;
                    ++sum;
                }
            }
        }
        if (count == 0) {
            cout<<"All customers tanned successfully."<<endl;
        } else {
            cout<<count<<" customer(s) walked away."<<endl;
        }
    }
    return 0;
}

5、UVa 11111 Generalized Matrioshkas(俄罗斯套娃)

#include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>

using namespace std;

int num[100000];

struct node {
    int value;
    int sum;
};

int judge(int len);

int main()
{
//    freopen("in.txt", "r", stdin);
//    freopen("out.txt", "w", stdout);
    int a;
    char c;
    int len = 0;
    while (scanf("%d%c", &a, &c) != EOF) {
        num[len] = a;
        ++len;
        if (c == '\n') {
            if (judge(len) == 1) {
                cout<<":-) Matrioshka!"<<endl;
            } else {
                cout<<":-( Try again."<<endl;
            }
            len = 0;
        }
    }
    return 0;
}

int judge(int len)
{
    node Node;
    stack<node>Stack;
    int i;
    for (i=0; i<len; ++i) {
        Node.value = num[i];
        Node.sum = 0;
        if (num[i] < 0) {
            if (Stack.empty()) {
                Stack.push(Node);
            } else {
                Stack.top().sum += Node.value;
                if (Stack.top().sum <= Stack.top().value) {
                    return 0;
                } else {
                    Stack.push(Node);
                }
            }
        } else {
            if (Stack.empty()) {
                return 0;
            } else if (num[i] == -Stack.top().value) {
                Stack.pop();
            } else {
                return 0;
            }
        }
    }
    if (!Stack.empty()) {
        return 0;
    }
    return 1;
}
#include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>

using namespace std;

int flag = 1;

struct node {
    int value;
    int sum;
};

stack<node>Stack;

void judge(int a);

int main()
{
//    freopen("in.txt", "r", stdin);
//    freopen("out.txt", "w", stdout);
    int a;
    char c;
    while (scanf("%d%c", &a, &c) != EOF) {
        judge(a);
        if (c == '\n') {
            if (flag && Stack.empty()) {
                cout<<":-) Matrioshka!"<<endl;
            } else {
                cout<<":-( Try again."<<endl;
            }
            flag = 1;
            while (!Stack.empty()) {
                Stack.pop();
            }
        }
    }
    return 0;
}

void judge(int a)
{
    if (flag) {
        node Node;
        Node.value = a;
        Node.sum = 0;
        if (a < 0) {
            if (Stack.empty()) {
                Stack.push(Node);
            } else {
                Stack.top().sum += Node.value;
                if (Stack.top().sum <= Stack.top().value) {
                    flag = 0;
                } else {
                    Stack.push(Node);
                }
            }
        } else {
            if (Stack.empty()) {
                flag = 0;
            } else if (a == -Stack.top().value) {
                Stack.pop();
            } else {
                flag = 0;
            }
        }
    }
}
#include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>

using namespace std;

struct Node {
    int sum;
    int val;
};

int main()
{
//    freopen("in.txt", "r", stdin);
    int n;
    char c;
    stack<Node> Stack;
    Node node;
    bool flag = true;
    while (scanf("%d%c", &n, &c) != EOF) {
        if (flag) {
            if (n < 0) {
                node.sum = 0;
                node.val = n;
                if (Stack.empty()) {
                    Stack.push(node);
                } else {
                    Stack.top().sum += node.val;
                    if (Stack.top().sum > Stack.top().val) {
                        Stack.push(node);
                    } else {
                        flag = false;
                    }
                }
            } else {
                if (Stack.empty()) {
                    flag = false;
                } else if (n == -Stack.top().val) {
                    Stack.pop();
                } else {
                    flag = false;
                }
            }
        }
        if (c == '\n') {
            if (flag && Stack.empty()) {
                cout<<":-) Matrioshka!"<<endl;
            } else {
                cout<<":-( Try again."<<endl;
            }
            while (!Stack.empty()) {
                Stack.pop();
            }
            flag = true;
        }
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 初始化顺序 顺序的初始化包括两部分:动态申请空间和初始化顶指针。假设顺序的元素类型为 int,的最大容量为 MAXSIZE,则初始化顺序的代码如下: ```c++ #define MAXSIZE 100 // 定义的最大容量 typedef struct { int data[MAXSIZE]; // 存放元素的数组 int top; // 顶指针 } SqStack; void InitStack(SqStack &S) { S.top = -1; // 初始化顶指针为 -1,表示为空 } ``` 2. 插入元素 在顺序中插入元素的操作被称为入。入的过程包括两部分:满检测和元素插入。如果已满,则插入操作失败;否则,将元素插入到顶,并更新顶指针。入的代码如下: ```c++ bool Push(SqStack &S, int x) { if (S.top == MAXSIZE - 1) { // 已满,插入失败 return false; } S.data[++S.top] = x; // 将元素插入到顶,顶指针加 1 return true; } ``` 3. 删除顶元素 在顺序中删除元素的操作被称为出。出的过程包括两部分:空检测和元素删除。如果已空,则删除操作失败;否则,删除顶元素,并更新顶指针。出的代码如下: ```c++ bool Pop(SqStack &S, int &x) { if (S.top == -1) { // 已空,删除失败 return false; } x = S.data[S.top--]; // 删除顶元素,顶指针减 1 return true; } ``` 4. 取顶元素 取顶元素的操作不涉及元素的插入或删除,只需要返回顶元素的值。如果已空,则取值操作失败。取值的代码如下: ```c++ bool GetTop(SqStack S, int &x) { if (S.top == -1) { // 已空,取值失败 return false; } x = S.data[S.top]; // 返回顶元素的值 return true; } ``` 5. 遍历顺序 遍历顺序的过程就是依次输出中的所有元素。由于顺序是一个后进先出的结构,所以需要从顶开始输出。遍历的代码如下: ```c++ void TraverseStack(SqStack S) { for (int i = S.top; i >= 0; i--) { cout << S.data[i] << " "; } cout << endl; } ``` 6. 置空顺序 置空顺序的过程就是将顶指针重新设置为 -1,表示已为空。置空的代码如下: ```c++ void ClearStack(SqStack &S) { S.top = -1; // 将顶指针置为 -1,表示已为空 } ``` 7. 初始化并建立链队列队列的初始化需要动态申请一个头结点,并将头结点的指针域置为空。建立链队列需要定义链队列的结点类型,并在插入元素时动态申请结点空间。假设链队列的元素类型为 int,链队列的头结点为 L,则初始化并建立链队列的代码如下: ```c++ typedef struct QNode { int data; // 存放队列元素的值 struct QNode *next; // 指向下一个结点的指针 } QNode, *QueuePtr; typedef struct { QueuePtr front; // 指向队头结点的指针 QueuePtr rear; // 指向队尾结点的指针 } LinkQueue; void InitQueue(LinkQueue &Q) { Q.front = Q.rear = new QNode; // 动态申请头结点空间 Q.front->next = NULL; // 头结点的指针域置为空 } ``` 8. 入链队列 在链队列中插入元素的操作被称为入队。入队的过程包括两部分:申请结点空间和元素插入。假设要插入的元素值为 x,则入队的代码如下: ```c++ void EnQueue(LinkQueue &Q, int x) { QueuePtr p = new QNode; // 动态申请结点空间 p->data = x; // 将元素插入到新结点中 p->next = NULL; // 新结点的指针域置为空 Q.rear->next = p; // 将新结点插入到队尾,更新队尾指针 Q.rear = p; } ``` 9. 出链队列 在链队列中删除元素的操作被称为出队。出队的过程包括两部分:队空检测和元素删除。如果队已空,则删除操作失败;否则,删除队头元素,并更新队头指针。出队的代码如下: ```c++ bool DeQueue(LinkQueue &Q, int &x) { if (Q.front == Q.rear) { // 队已空,删除失败 return false; } QueuePtr p = Q.front->next; // 获取队头结点 x = p->data; // 返回队头元素的值 Q.front->next = p->next; // 删除队头结点,更新队头指针 if (Q.rear == p) { // 如果队列中只有一个元素,更新队尾指针 Q.rear = Q.front; } delete p; // 释放已删除的结点空间 return true; } ``` 10. 遍历链队列 遍历链队列的过程就是依次输出队列中的所有元素。由于链队列是一个先进先出的结构,所以需要从队头开始输出。遍历的代码如下: ```c++ void TraverseQueue(LinkQueue Q) { QueuePtr p = Q.front->next; // 获取队头结点 while (p != NULL) { // 循环遍历队列中的每个元素 cout << p->data << " "; p = p->next; } cout << endl; } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值