首页 > 其他 > 详细

hdu 1870 愚人节的礼物 (栈)

时间:2015-05-19 14:49:53      阅读:170      评论:0      收藏:0      [点我收藏+]

愚人节的礼物

Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 6260    Accepted Submission(s): 3788


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

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

Input
本题目包含多组测试,请处理到文件结束。
每组测试包含一个长度不大于1000,只包含‘(‘,‘)‘和‘B‘三种字符的字符串,代表Vayko设计的礼物透视图。
你可以假设,每个透视图画的都是合法的。
 

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

Sample Input
((((B)()))()) (B)
 

Sample Output
4 1
 

Author
Kiki
 

Source
 


不是栈的方法

#include <stdio.h>
#include <string.h>
int main()
{
	int len,sum;
	char str[1005];
	while(gets(str)!=NULL)
	{
		len=strlen(str);
		sum=0;
		for(int i=0;i<len;i++)
		{
			if(str[i]=='(')
			sum++;
			if(str[i]==')'&&sum)
			sum--;
			if(str[i]=='B')
			break;
		}
		printf("%d\n",sum);
	}
	return 0;
}

栈的方法

#include <stdio.h>
#include <stack>
#include <string.h>
using namespace std;
int main()
{
	int len,sum;
	char str[1005];
	stack<char>s;
	while(gets(str)!=NULL)
	{
		len=strlen(str);
		s.push('a');//避免str[0]==')',s.pop()访问到未知区域
		for(int i=0;i<len;i++)
		{
			if(str[i]=='(')
			s.push(str[i]);
			if(str[i]==')'&&s.top()!='a')
			s.pop();
			if(str[i]=='B')
			break;
		}
		sum=0;
		while(s.top()!='a')
		sum++,s.pop();
		printf("%d\n",sum);
	}
	return 0;
}


hdu 1870 愚人节的礼物 (栈)

原文:http://blog.csdn.net/su20145104009/article/details/45843427

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!