POJ-3276:Face The Right Way

题目:

Farmer John has arranged his N (1 ≤ N ≤ 5,000) cows in a row and many of them are facing forward, like good cows. Some of them are facing backward, though, and he needs them all to face forward to make his life perfect.

Fortunately, FJ recently bought an automatic cow turning machine. Since he purchased the discount model, it must be irrevocably(不可改变地) preset to turn K (1 ≤ KN) cows at once, and it can only turn cows that are all standing next to each other in line. Each time the machine is used, it reverses the facing direction of a contiguous group of K cows in the line (one cannot use it on fewer than K cows, e.g., at the either end of the line of cows). Each cow remains in the same *location* as before, but ends up facing the *opposite direction*. A cow that starts out facing forward will be turned backward by the machine and vice-versa(反之亦然).

Because FJ must pick a single, never-changing value of K, please help him determine the minimum value of K that minimizes the number of operations required by the machine to make all the cows face forward. Also determine M, the minimum number of machine operations required to get all the cows facing forward using that value of K.

Input
Line 1: A single integer: N
Lines 2.. N+1: Line i+1 contains a single character, F or B, indicating whether cow i is facing forward or backward.
Output
Line 1: Two space-separated integers: K and M
Sample Input
7
B
B
F
B
F
B
B
Sample Output
3 3
Hint
For K = 3, the machine must be operated three times: turn cows (1,2,3), (3,4,5), and finally (5,6,7)

概译:N头牛有的朝前有的朝后,调转牛方向的机器每次只能且必须改变相邻的K头牛,改变后牛的方向与之前相反,要求最后调转得全部朝前。

输入:N代表牛数量,F代表初始朝前,B代表初始朝后。

输出:最小的调转次数对应的K值,最小的调转次数M。

分析:如果对K从1到N枚举,对于每个K再遍历牛群,对于每只牛需要调转时再遍历修改i到i+k-1,复杂度为O(n³);如果我们对于是否反转的过程进行优化,只用之前i被反转次数的奇偶性来判断它的朝向,则无需反复修改,复杂度为O(n²),详细请见《挑战程序设计竞赛》151页。更多解释见代码:

#include<cstdio>
#include<cstring>
#define inf 0x7fffffff

int n,K,M=inf,dir[5005],f[5005];
//K,M是最后要输出的设定长度和翻转次数,dir是初始方向,f是翻转次数(只有0和1次) 
char ch;

int cal(int k)
{
	memset(f,0,sizeof(f));
	//最开始都是为翻转过 
	int sum=0,res=0;
	//sum是i-k+1到i范围(长度为k)内翻转的次数和,res是总次数和即当前的m 
	for(int i=0;i+k-1<n;i++)//此过程用样例在纸上写写有助理解 
	{
		if((sum+dir[i])&1)//sum是这一段翻过的次数,dir是本来朝向,如果加和是奇数代表朝后,要翻一次 
		{
			res++;
			f[i]=1;
		}
		//下面是对sum随段移动的更新,加上当前的,减去马上离开的 
		sum+=f[i];
		if(i-k+1>=0)
			sum-=f[i-k+1];
	}
	//对最后几个进行检查 
	for(int i=n-k+1;i<n;i++)
	{
		if((sum+dir[i])&1)//还有朝后的,由于要翻只能一段一起翻,这是最后一段已经翻过了,所以无解 
			return -1;
		if(i-k+1>=0)
			sum-=f[i-k+1];
	}
	return res;
}
int main()
{
	//输入 
	scanf("%d",&n);
	for(int i=0;i<n;i++)
	{
		getchar();
		ch=getchar();
		dir[i]=ch=='F'?0:1;
		//将朝前设置为0,将朝后设置为1,主要为了核心部分取模而设置 
	}
	//枚举k 
	for(int k=1;k<=n;k++)
	{
		int m=cal(k);//cal函数计算当前k所需m,若为-1则意为无解 
		if(m>=0&&m<M)//更新所需结果 
		{
			M=m;
			K=k;
		}
	}
	//输出 
	printf("%d %d",K,M);
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章