uva 1610 Party Games (貪心+STL字符串)

   You’ve been invited to a party. The host wants to divide the guests into 2 teams for party games, withexactly the same number of guests on each team. She wants to be able to tell which guest is on whichteam as she greets them when they arrive. She’d like to do so as easily as possible, without having totake the time to look up each guest’s name on a list.

   Being a good computer scientist, you have an idea: give her a single string, and all she has to do iscompare the guest’s name alphabetically to that string. To make this even easier, you would like thestring to be as short as possible.

   Given the unique names of n party guests (n is even), find the shortest possible string S such thatexactly half the names are less than or equal to S, and exactly half are greater than S. If there aremultiple strings of the same shortest possible length, choose the alphabetically smallest string fromamong them.

Input

   There may be multiple test cases in the input.

                     Each test case will begin with an even integer n (2 ≤ n ≤ 1, 000) on its own line.

    On the next n lines will be names, one per line. Each name will be a single word consisting only ofcapital letters and will be no longer than 30 letters.

    The input will end with a ‘0’ on its own line.


Output

    For each case, print a single line containing the shortest possible string (with ties broken in favor of thealphabetically smallest) that your host could use to separate her guests. The strings should be printedin all capital letters.

Sample Input

4

FRED

SAM

JOE

MARGARET

2

FRED

FREDDIE

2

JOSEPHINE

JERRY

2

LARHONDA

LARSEN

0

Sample Output

K

FRED

JF

LARI


這道題目還是比較好想,我的方法是先排序,然後對半分取少半部分最大的一個串,我造的串必須比他短或一樣,比他小或一樣。

然後取這個串的長度接着,用貪心的想法一個個嘗試。假如str長度到了l-1這個時候,我們就只能取這個串本身作爲我們的答案。

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
    int n;
    while(cin>>n&&n)
    {
        string s[1010];
        for(int i=0;i<n;i++){cin>>s[i];}
        sort(s,s+n);
        int m=n/2;
        int l=s[m-1].size();
        string str="";
        for(int i=0;i<l;i++)
        {
            int j;
            if(i==l-1)           
            {
                str="";
                str=s[m-1];              //這個時候他本身便是我們的最優解

            }
            else
            {
                if(s[m-1][i]=='Z'||s[m-1][i]=='z'){str+=s[m-1][i];continue;}     //Z已經最大了,再加一就不是字母了。
                str+=s[m-1][i]+1;
                for(j=m;j<n;j++)
                {
                    if(s[j]<=str)
                    {
                        str[i]=s[m-1][i];
                        break;
                    }
                }
                if(j==n){break;}         //說明已經找到了答案,即輸出
            }
        }
        cout<<str<<endl;
    }
    return 0;
}



發佈了48 篇原創文章 · 獲贊 8 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章