codeforces Round #677 (Div. 3) 1433B Yet Another Bookshelf

Topic link

Insert picture description here

Title translation:

There is a bookshelf that can hold n books. If there is a book in the i- th position of the bookshelf , then a i =1 , otherwise a i =0 . The title guarantees that there is at least one book on the shelf.
In a move, you can select a continuous interval [ l ; r ], each position must have a book (that is, for any i, l<=i<=r, a i =1 are all true), then:

  • Move the interval one position to the right: For all subscripts i (l<=i<=r), move the book with the subscript i to the position with the subscript i+1. You can move only when r+1<=n and there is no book at the position where the subscript is r+1.
  • Move the interval one position to the left: For all subscripts i (l<=i<=r), move the book with the subscript i to the position with the subscript i-1. You can move only when l-1>=1 and there is no book at the position where the subscript is l-1.
    Your task is to calculate the minimum number of moves so that all the books on the shelf are adjacent.
    For example, for a=[0,0,1,0,1], there is a 0 interval between subscripts 3 and 5. For a=[1,1,0],a=[0,0,0], there is no interval.
    You need to answer t independent test cases.
Problem-solving ideas:

Obviously, the number of 0s between the 1 with the smallest subscript and the 1 with the largest subscript is the number of times to move.
If you can't think of it at first, you can simply simulate the process with things around you.

Code:
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<vector>
#include<map>
#include<queue>
#include<cstdio>
#include<cmath>
#define inf 0x3f3f3f3f
using namespace std;
const int N = 100;
int a[N];
int main(){
    
    
//	freopen("1.txt","r",stdin);
	int t,n;
	cin>>t;
	while(t--){
    
    
		cin>>n;
		for(int i=0;i<n;i++){
    
    
			cin>>a[i];
		}
		int l,r;
		for(int i=0;i<n;i++){
    
    
			if(a[i]){
    
    
				l=i;
				break;
			}
		}
		for(int i=n-1;i>=0;i--){
    
    
			if(a[i]){
    
    
				r=i;
				break;
			}
		}
		int sum=0;
		for(int i=l;i<=r;i++){
    
    
			if(!a[i]) sum++;
		}
		cout<<sum<<endl;
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/lmmmmmmmmmmmmmmm/article/details/109220428