首页 > ACM题库 > HDU-杭电 > HDU 3363-Ice-sugar Gourd-枚举-[解题报告]HOJ
2014
03-16

HDU 3363-Ice-sugar Gourd-枚举-[解题报告]HOJ

Ice-sugar Gourd

问题描述 :

Ice-sugar gourd, “bing tang hu lu”, is a popular snack in Beijing of China. It is made of some fruits threaded by a stick. The complicated feeling will be like a both sour and sweet ice when you taste it. You are making your mouth water, aren’t you?
Fix
I have made a huge ice-sugar gourd by two kinds of fruit, hawthorn and tangerine, in no particular order. Since I want to share it with two of my friends, Felicia and his girl friend, I need to get an equal cut of the hawthorns and tangerines. How many times will I have to cut the stick so that each of my friends gets half the hawthorns and half the tangerines? Please notice that you can only cut the stick between two adjacent fruits, that you cannot cut a fruit in half as this fruit would be no good to eat.

输入:

The input consists of multiply test cases. The first line of each test case contains an integer, n(1 <= n <= 100000), indicating the number of the fruits on the stick. The next line consists of a string with length n, which contains only ‘H’ (means hawthorn) and ‘T’ (means tangerine).
The last test case is followed by a single line containing one zero.

输出:

The input consists of multiply test cases. The first line of each test case contains an integer, n(1 <= n <= 100000), indicating the number of the fruits on the stick. The next line consists of a string with length n, which contains only ‘H’ (means hawthorn) and ‘T’ (means tangerine).
The last test case is followed by a single line containing one zero.

样例输入:

4
HHTT
4
HTHT
4
HHHT
0

样例输出:

2
1 3
1
2
-1

#include<stdio.h>
#define N 100001
int n;
char ice[N];

void solve()
{
    int i,t_tol=0,h_tol=0,h=0,t=0,m=n>>1;
    for(i=0;i<n;++i)
        if(ice[i]=='H')
            h_tol++;
        else
            t_tol++;

    if((h_tol%2)||(t_tol%2))
    {
        printf("-1\n");
        return ;
    }
    for(i=0;i<m;++i)
        if(ice[i]=='H')
            ++h;
        else
            ++t;
    if(h*2==h_tol&&t*2==t_tol)
    {
        printf("1\n%d\n",m);
        return ;
    }
    for(;i<n;++i)
    {
        if(ice[i]=='H')
            h++;
        else
            t++;
        if(ice[i-m]=='H')
            --h;
        else
            --t;
        if(h*2==h_tol && t*2==t_tol)
        {
            printf("2\n%d %d\n",i-m+1,i+1);
            return ;
        }
    }
    printf("-1\n");
}
int main()
{
    while(scanf("%d",&n)==1&&n)
    {
        scanf("%s",ice);
        solve();
    }
    return 0;
}
/**
解题大意:
给你一个串,串中有H跟T两种字符,然后切任意刀,使得能把H跟T各自分为原来的一半。
解题思路:
把串想象成一个环,只要满足H跟T都为偶数个,那么就可以做一条过圆心的直线把H跟T平分掉,
过直线,只要考虑平分H或者T中的一个就可以了,因为直线本来就把环平分,而此时平分了H或者T,
那么剩下的那个也是平分掉的。

代码:枚举每个位置

*/

参考:http://blog.csdn.net/cscj2010/article/details/7462063


  1. 这道题这里的解法最坏情况似乎应该是指数的。回溯的时候
    O(n) = O(n-1) + O(n-2) + ….
    O(n-1) = O(n-2) + O(n-3)+ …
    O(n) – O(n-1) = O(n-1)
    O(n) = 2O(n-1)