Face The Right Way POJ - 3276

Face The Right Way

Question link: POJ - 3276
Question meaning: There is a row of dairy cows, some with their heads forward and some with their heads backward, and it is required to turn k consecutive dairy cows each time. After m operations, all the cows are facing forward, and find the minimum time of m , k is the minimum value;
first k must be from 1 to n, and then for each k to find an m, the beginning of my idea is to flip a cow to change the state of k-1 cows behind him, which is the complexity of n^3 , resolutely TE;
and then resolutely searched for the solution;
when we operate on i, it only affects the interval of i~i+k-1, and when we reach j, as long as we know how many previous operations have an impact on j, we can judge The state of j is out at this time;
maintaining a sum means that there are several operations in front of i that will affect i; how to maintain it is a problem...
Think carefully about the impact of i operation on the following k-1, but when After the distance between j and i exceeds k-1, i will not affect j, so sum can subtract the operation at i;
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int INF = 0x3f3f3f3f;
int n;
int cow[5100], t[5100];
int cnt(int k){
	memset(t, 0, sizeof(t));
	int res=0, sum=0;
	for(int i=0; i+k<=n; i++){
		if((cow[i]+sum)%2){
			res++;
			t[i]=1;
		}
		sum+=t[i];
		if(i-k+1>=0) sum-=t[i-k+1];
	}
	for(int i=n-k+1; i<=n; i++){
		if((cow[i]+sum)%2) return INF;
		if(i-k+1>=0) sum-=t[i-k+1];	
	}
	return res;
}
void solve(){
	int ans_k=0, ans_m=INF;
	for(int k=1; k<=n; k++){
		int tmp=cnt(k);
		if(tmp<ans_m){
			ans_m=tmp;
			ans_k=k;
		}
	}
	printf("%d %d\n", ans_k, ans_m);
}
int main(){
	scanf("%d", &n);
	char s[5];
	for(int i=0; i<n; i++){
		scanf("%s", s);
		if(s[0]=='F') cow[i]=0;
		else cow[i]=1;
	}
	solve();
	return 0;
}



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325782672&siteId=291194637