您的位置:首页 > 其它

HDU 1870 愚人节的礼物

2015-01-21 19:37 183 查看
Description

四月一日快到了,Vayko想了个愚人的好办法――送礼物。嘿嘿,不要想的太好,这礼物可没那么简单,Vayko为了愚人,准备了一堆盒子,其中有一个盒子里面装了礼物。盒子里面可以再放零个或者多个盒子。假设放礼物的盒子里不再放其他盒子。

用()表示一个盒子,B表示礼物,Vayko想让你帮她算出愚人指数,即最少需要拆多少个盒子才能拿到礼物。

Input

本题目包含多组测试,请处理到文件结束。

每组测试包含一个长度不大于1000,只包含'(',')'和'B'三种字符的字符串,代表Vayko设计的礼物透视图。

你可以假设,每个透视图画的都是合法的。

Output

对于每组测试,请在一行里面输出愚人指数。

Sample Input

((((B)()))())
(B)


Sample Output

4
1


典型的栈的应用,思路很简单,先整行输入字符串,然后从左往右开始依次遍历每个字符,如果是左括号便压人栈中,如果是右括号便弹出栈顶左括号(左右抵消),遇到B字符则遍历结束,输出栈中元素个数既是问题的解,代码如下:(写了栈类,代码稍长,因为是专题训练,不然就直接用STL了)

#include <iostream>
#include <cstdlib>

using namespace std;

typedef char anytype;

struct stacks
{
struct node	//链栈
{
anytype data;
struct node *next;
}*head;
stacks()	//构造函数
{
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
}
bool empty()	//判断空栈
{
if(head->next)
return false;
return true;
}
void push(anytype n)	//入栈
{
struct node *p;
p=(struct node *)malloc(sizeof(struct node));
p->data=n;
p->next=head->next;
head->next=p;
}
void pop()	//	出栈
{
struct node *p;
p=head->next;
if(p)
{
head->next=p->next;
free(p);
}
}
anytype top() //查询栈顶元素
{
if(!empty())
return head->next->data;
return 0;
}
int counts()	//返回栈内元素数量
{
struct node *p;
int res=0;
p=head->next;
while(p)
{
res++;
p=p->next;
}
return res;
}
};
int main()
{
ios::sync_with_stdio(false);
string str;
while(getline(cin,str,'\n'))
{
stacks s;
int len=str.length();
for(int i=0;i<len;i++)
{
if(str[i]=='(')	//左括号入栈
s.push(str[i]);
else if(str[i]==')')	//右括号则弹出栈顶元素
s.pop();
else if(str[i]=='B')	//B则结束
break;
}
cout<<s.counts()<<endl;	//输出栈内元素
}

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