您的位置:首页 > 理论基础 > 数据结构算法

数据结构 uva-11111-Generalized Matrioshkas

2013-01-15 17:02 218 查看
题目链接:

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2052



题目意思:

as the problem statement is too long,i haven't read the problem statement Completely during the Contest, consider you have some boxes that some of them are nested in some other boxes , each box should begin with negative
number and end with the absolute value of that negative number , the absolute value shows the size of box , and the sum of size of inside boxes should be less than the outside boxes , you are given sequence of the numbers , you should check
whether it violates the above rules or not, that's all .Hope it helps !



解题思路:

用一个栈模拟,其中遇到负数时进栈,遇到正数处理,如果和当前栈顶元素互补,并且栈顶元素的“和”小于当前正数,则出栈满足要求,并且出栈后将该值加到当前的栈顶的“和”中。详见代码。



代码:

#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<algorithm>
#include<vector>
#include<map>
#define eps 1e-6
#define INF (1<<20)
#define PI acos(-1.0)
using namespace std;

struct Stack
{
    int top,flag;   //flag记录满不满足题目要求
    int save[200][2];  //save[i][0]表示当前负数的值,save[i][1]表示当前负数所辖领域的总和

    void push(int n)
    {
        ++top;
        save[top][0]=n;  //初始化
        save[top][1]=0;
    }
    int pop()
    {
        return save[top--][0];  //出栈
    }
    bool empty()
    {
        if(top)
            return false;
        return true;
    }
    void set()
    {
        top=flag=0;
    }
}stack;

int main()
{
    int cur;

    while(scanf("%d",&cur)!=EOF)
    {
        stack.set();

        int last=cur;
        char temp=getchar();

        if(cur<0)
            stack.push(cur);
        else     //如果一开始就为正数,肯定不行
            stack.flag=1;

        while(temp!='\n')
        {
            scanf("%d%c",&cur,&temp);

            if(cur<0)   //如果是负数,则直接压栈
                stack.push(cur);
            else
            {
                int temptop=stack.top;

                if(stack.save[temptop][0]+cur==0) //如果与当前栈顶元素互补
                {
                    if(stack.save[temptop][1]<cur) //如果当前栈顶“和”小于当前值,则满足要求
                    {
                        stack.pop();
                        if(!stack.empty())
                            stack.save[stack.top][1]+=cur;
                    }                          //不满足要求
                    else
                        stack.flag=1;
                }
                else   //不满足要求
                    stack.flag=1;
            }
        }
        if(stack.flag==1||!stack.empty())
            printf(":-( Try again.\n");
        else
            printf(":-) Matrioshka!\n");
    }

    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: