uva11111-一般Matrioshka

小白书里数据结构基础线性表的训练参考

 

题目链接 http://acm.hust.edu.cn/vjudge/problem/18905

 

解题思路

用栈维护。娃娃们有两种包含方式:一个套一个或者一个套多个。

遇到负数入栈,并更新包含它的娃娃的已转载的体积(如果有包含的话)。

遇到整数出栈。

超出尺寸,最后栈非空都是非法的。

输入的时候要忽略所有的空格。可以用getchar()、ungetc(),但可能会很恶心。。。

 

代码

#include<stdio.h>
//#define LOCAL
typedef struct node {
    int size;
    int tot;
}Node;
const int maxNum = 10000;
Node stack[maxNum];
int main()
{
    #ifdef LOCAL
        freopen("data.txt", "r", stdin);
        freopen("ans.txt", "w", stdout);
    #endif
    int d;
    int c;
    int top = -1;
    bool beat = false;
    while((c=getchar())=='\n') printf(":-) Matrioshka!\n");
    ungetc(c, stdin);
    while(scanf("%d", &d) == 1) {
        if(d<0) {
            stack[++top].size = -d;
            stack[top].tot = 0;
            if(top>0) {
                stack[top-1].tot += -d;
                if(stack[top-1].tot >= stack[top-1].size) beat = true; 
            }
        }
        if(d>0) {
            if(top==-1 || stack[top].size != d) beat = true;
            else if(stack[top].size > stack[top].tot) top--;
                else beat = true;
        }
        while((c=getchar())==' ') ;
        ungetc(c, stdin);
        if((c=getchar()) == '\n' && top != -1) { printf(":-( Try again.\n"); beat = false; top = -1; } 
        else 
            while(c=='\n') 
                { if(!beat) { printf(":-) Matrioshka!\n"); c=getchar(); }
                    else { printf(":-( Try again.\n"); beat = false; top = -1; c=getchar(); }
                }
        if(beat) { 
            printf(":-( Try again.\n"); 
            while(c!='\n' && c!=EOF ) c = getchar() ; 
            beat = false; top = -1;
        }
        if(c==EOF) break;
        ungetc(c, stdin);
    }
    return 0;
}

 

posted @ 2016-08-08 00:16  啊嘞  阅读(312)  评论(0编辑  收藏  举报