站点图标 陌路寒暄

简易占座

简易占座

时间: 1ms        内存:128M

描述:

新学期开始了,小明提早到自习教室帮同学占座,一本书可以占两个相邻座位,小明只想占一整排座位,求总共需要几本书来占满这一排空余座位?

输入:

题目有多组测试数据

先输入一个数据n,表示这一排总共有多少个座位,再输入一行座位状态,"*"为不能占座,"@"为可以占座。

输出:

输出需要几本书占座,如果没有座位可以来占座,则输出"Oh no!"

示例输入:

1
*
6
@**@@@

示例输出:

Oh no!
3

提示:

参考答案(内存最优[752]):

#include<stdio.h>
int aa(char a[],int n)
{
	int i;
	int s=0;
	for(i=0;i<n;)
	{
		if(a[i]=='@'&&a[i+1]=='@')
		{
			s++;
			i+=2;
		}
		else if(a[i]=='@'&&a[i+1]!='@')
		{
			s++;
			i++;
		}
		else if(a[i]=='*')
			i++;
	}
	return s;
}
int main()
{
	int n,i,s;
	char a[100];
	while(scanf("%d",&n)!=EOF)
	{
		if(n==0)
		{
			printf("Oh no!\n");
			continue;
		}
		getchar();
		for(i=0;i<n;i++)
		{
			scanf("%c",&a[i]);
		}
		a[i]='\0';
		s=aa(a,n);
		if(s==0)
			printf("Oh no!\n");
		else
			printf("%d\n",s);
	}
	return 0;
}

参考答案(时间最优[0]):

#include <iostream>
#include <string>
using namespace std;
int main()
{
    int n,i,j,num;
    string str;
    while(cin>>n)
    {
        cin>>str;
        num=j=0;
        for(i=0; i<n; ++i)
        {
            if(str[i]=='*')
            {
                j=0;
                continue;
            }
            else if(str[i]=='@')
            {
                if(j==0)
                {
                    ++num;
                    ++j;
                }
                else if(j==1)
                {
                    j=0;
                }
            }
        }
        if(!num)	cout<<"Oh no!"<<endl;
        else	cout<<num<<endl;

    }
    return 0;
}

题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。

退出移动版