codeforces 46C Hamsters and Tigers(枚举)

题目链接

Hamsters and Tigers
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Today there is going to be an unusual performance at the circus — hamsters and tigers will perform together! All of them stand in circle along the arena edge and now the trainer faces a difficult task: he wants to swap the animals' positions so that all the hamsters stood together and all the tigers also stood together. The trainer swaps the animals in pairs not to create a mess. He orders two animals to step out of the circle and swap places. As hamsters feel highly uncomfortable when tigers are nearby as well as tigers get nervous when there's so much potential prey around (consisting not only of hamsters but also of yummier spectators), the trainer wants to spend as little time as possible moving the animals, i.e. he wants to achieve it with the minimal number of swaps. Your task is to help him.

Input

The first line contains number n (2 ≤ n ≤ 1000) which indicates the total number of animals in the arena. The second line contains the description of the animals' positions. The line consists of n symbols "H" and "T". The "H"s correspond to hamsters and the "T"s correspond to tigers. It is guaranteed that at least one hamster and one tiger are present on the arena. The animals are given in the order in which they are located circle-wise, in addition, the last animal stands near the first one.

Output

Print the single number which is the minimal number of swaps that let the trainer to achieve his goal.

Sample test(s)
input
3
HTH
output
0
input
9
HTHTHTHHT
output
2

题意:输入一个字符串,H代表仓鼠的位置,T代表老虎的位置。第一个字符和最后一个字符是相邻的,也就是一个环。每次可以交换两个动物的位置,求最少交换多少次使得所有仓鼠站在一起,所有的老虎站在一起?

题解:统计出老虎的个数和仓鼠的个数。枚举老虎站在一起所在的区间,假设为[l,r] ,那么最少交换的次数就是 [l,r] 中仓鼠的个数。由于是一个环,所以要用同样的方法枚举仓鼠站在一起所在的区间。我们可以先处理出所有前缀的仓鼠的个数和老虎的个数,就可以O(1)查询一个区间中老虎或者仓鼠的个数。

代码如下:

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<string>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<stdlib.h>
#include<vector>
#define inff 0x3fffffff
#define nn 110000
#define mod 1000000007
typedef long long LL;
const LL inf64=inff*(LL)inff;
using namespace std;
int n;
char s[nn];
int h[nn],t[nn];
int main()
{
    int i;
    int ans;
    while(scanf("%d",&n)!=EOF)
    {
        scanf("%s",s+1);
        ans=inff;
        h[0]=t[0]=0;
        for(i=1;i<=n;i++)
        {
            h[i]=h[i-1];
            t[i]=t[i-1];
            if(s[i]=='H')
                h[i]++;
            else
                t[i]++;
        }
        for(i=1;i+h[n]-1<=n;i++)
        {
            ans=min(ans,t[i+h[n]-1]-t[i-1]);
        }
        for(i=1;i+t[n]-1<=n;i++)
        {
            ans=min(ans,h[i+t[n]-1]-h[i-1]);
        }
        printf("%d\n",ans);
    }
    return 0;
}


你可能感兴趣的:(枚举,ACM,codeforces)