ACM Row

Row 题目如下
You’re given a row with n chairs. We call a seating of people “maximal” if the two following conditions hold:

1.There are no neighbors adjacent to anyone seated.
2. It’s impossible to seat one more person without violating the first rule.

The seating is given as a string consisting of zeros and ones (00 means that the corresponding seat is empty, 11 — occupied). The goal is to determine whether this seating is “maximal”.

Note that the first and last seats are not adjacent (if n≠2).

Input
The first line contains a single integer n (1≤n≤1000) — the number of chairs.

The next line contains a string of n characters, each of them is either zero or one, describing the seating.

Output
Output “Yes” (without quotation marks) if the seating is “maximal”. Otherwise print “No”.

Examples
input output
3
101 Yes

4
1011 No

5
10001 No

Note
In sample case one the given seating is maximal.

In sample case two the person at chair three has a neighbour to the right.

In sample case three it is possible to seat yet another person into chair three.

题意:一排有n座的椅子,0表示未坐人,1表示坐人,当满足以下两个条件时输出Yes,否则输出No

1.坐了人的位置旁边不能再坐人,即1旁边不能有1
2.在不违反第一个条件的情况下,不能再多坐一个人,即0的两边必然有一个1

以下是我做题时的思路
思路一(错误):
判断相邻两个数是否相同,相同则No,too easy,WA
思路二(错误):
继续考虑相邻两个数,将n=1-5的情况下Yes的情况列下
n=1: 1
n=2: 10,01
n=3:101,010
n=4:1010,0101,1001
n=5:10101,01010
其中粗体是一开始没有考虑到的
总结规律如下:
①n为偶数时相邻两个不相同②n为奇数时满足第一位为1且相邻两数不相同
满足上述任一点就Yes。easy,WA
很明显规律是错的,因为1001同样符合
思路三:
放弃相邻两数,开始考虑连续的三个数,已知
1.连续3个0
2.连续两个1必然是No
3.当连续两个0在最左侧和最右侧时也是No
除开这三种情况其他都是Yes,1和2好判定,主要是3不好下手。结合1的情况,发现在输入的字符串两侧各添一个0,就可以用1的方法判断3
这样判定之后,AC
PS:不要忘了n=0的情况,当n=0时,第二行是不需要输入的,Windows上按enter键不代表输入结束,先按enter键,再按Ctrl+Z,最后按enter键表示输入结束
PPS:n=3时010和n=5时01010是对的,因为符合最上面的两个条件。作为新手的我下意识以为需要排出一个最大的容量(010换成101),先入为主没看懂题,导致WA了半天

贴上代码
#include <stdio.h>
int main()

#include <stdio.h>
int main()
{
	int n,i,flag=1;
	char str[1005];//str存放座位情况 
	scanf("%d",&n);
	scanf("%s",str+1);//从str的第二位开始存放,第一位放0 
	str[0]=str[n+1]='0';//在表示座位的一串数字前后各加一个0,方便下文判断

	if(n==0)
		flag=0;
	else
	{
		for(i=1;i<=n;i++)
			//在首尾各加一个0的情况下,三个连续的0和两个连续的1导致No 
			if((str[i-1]=='0'&&str[i]=='0'&&str[i+1]=='0')||(str[i-1]=='1'&&str[i]=='1'))
			{
				flag=0;break;
			}
	} 
	if(flag==0)
		printf("No");
	else
		printf("Yes");
} 

猜你喜欢

转载自blog.csdn.net/qq_42906647/article/details/88431633
Row
ACM