Yet Another Bookshelf

There is a bookshelf which can fit n books. The i-th position of bookshelf is ai=1 if there is a book on this position and ai=0 otherwise. It is guaranteed that there is at least one book on the bookshelf.

In one move, you can choose some contiguous segment [l;r] consisting of books (i.e. for each i from l to r the condition ai=1 holds) and:

Shift it to the right by 1: move the book at index i to i+1 for all l≤i≤r. This move can be done only if r+1≤n and there is no book at the position r+1.
Shift it to the left by 1: move the book at index i to i−1 for all l≤i≤r. This move can be done only if l−1≥1 and there is no book at the position l−1.
Your task is to find the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without any gaps).

For example, for a=[0,0,1,0,1] there is a gap between books (a4=0 when a3=1 and a5=1), for a=[1,1,0] there are no gaps between books and for a=[0,0,0] there are also no gaps between books.

You have to answer t independent test cases.

Input
The first line of the input contains one integer t (1≤t≤200) — the number of test cases. Then t test cases follow.

The first line of the test case contains one integer n (1≤n≤50) — the number of places on a bookshelf. The second line of the test case contains n integers a1,a2,…,an (0≤ai≤1), where ai is 1 if there is a book at this position and 0 otherwise. It is guaranteed that there is at least one book on the bookshelf.

Output
For each test case, print one integer: the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without gaps).

Example
Input
5
7
0 0 1 0 1 0 1
3
1 0 0
5
1 1 0 0 1
6
1 0 0 0 0 1
5
1 1 0 1 1
Output
2
0
2
4
1
这个题其实本质上并不难,关键我是真的不会历遍,这个题的大致思维是找到第一个一和最后一个一之间0的个数。但是历遍的方式多种多样。
第一种我想的是从头历遍一次,碰到第一个1停止;再从尾历遍一次,碰到最后一个1停止,然后再查询其中有多少个0;
结果——超时;
第二种我想的是从头历遍的同时进行判断,保留第一个1和最后一个1的位置,再查询其中有多少的0;
结果——超时;
最终我还是想到了不超时的方法,不断计算两个1之间的0,这样就可以计算出了0的个数。
代码如下:

#include<stdio.h>
int main()
{	int woc,c;
	scanf("%d",&woc);
	for(int woaidaima=0;woaidaima<woc;woaidaima++)
	{
		int n,a[210],count=0;
		scanf("%d",&n);
		for(int i=0;i<n;i++)
		{
			scanf("%d",&a[i]);
		}
		for(int i=0;i<n;i++)
		{
			int erta=0;//初始化差值
			if(a[i]==1)//一旦有一个数为一
			{
				for(int j=i+1;j<n;j++)
				{
					if(a[j]==1)//寻找第二个为一的数
					{
						erta=j-i-1;//计算两个为一的数的差值
						count=count+erta;//将差值储存在count中
						i=j-1;//下一次从j处开始查找
						break;
					}
				}
			}	
		}
		printf("%d\n",count);
	}
}

由于这个大水题让我用了将近12个小时,变量的名称设置的有点奇怪。。。
return code;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值