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

来源:互联网 发布:2016年电信诈骗数据 编辑:程序博客网 时间:2024/05/16 19:10

   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;}



原创粉丝点击