B - Yet Another Bookshelf

Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
Meaning of the title: 1 means one book, 0 means no book, move the book together, you can move several books together, find the minimum number of times to move all the books together at the end

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
    
    
	int n,t;
	int a[10000];
   scanf("%d",&t);
   while(t--)
   {
    
    
   	scanf("%d",&n);
   	int sum=0;
   	for(int i=1;i<=n;i++)
   	{
    
    
   		scanf("%d",&a[i]);
   		if(a[i]==1)
   		sum++;
   		
    }
    if(sum==0||sum==1)//没有书和只有一本书的情况
    printf("0\n");
    else
    {
    
    
    	 int min,max;
    for(int i=1;i<=n;i++)
    {
    
    
    	if(a[i]==1)
    	{
    
    
    		min=i;//找到第一个1的位置
    		break;
		}
	}
	for(int i=n;i>=1;i--)
	{
    
    
		if(a[i]==1)
		{
    
    
			max=i;//找到最后一个1的位置
			break;
		}
	}
   	printf("%d\n",max-min+1-sum);//求第一个1和最后一个1之间0的个数
	}
   }
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_51713993/article/details/113854701