UVa:1610 Party Games(字符串处理)

题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=845&page=show_problem&problem=4485

题意:输入一个n(2
≤n≤1000,n是偶数)个字符串的集合D,找一个长度最短的字符串(不一定在D中出现)S,使得D中恰好一半串小于等于S,另一半串大于S。如果有多解,输出字典序最小的解。例如,对于{JOSEPHINE,JERRY},输出JF;对于{FRED,FREDDIE}输出FRED。(本段摘自《算法竞赛入门经典(第2版)》)

分析:基本想法是是对字符串按字典序排序,然后只需处理中间的两个字符串就可以了。主要是对细节的处理要注意。

代码:

#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>
#include <queue>
#include <cmath>
#include <algorithm>
#include <set>
#include <string>

using namespace std;

const int maxn = 1005;

int n, l, l1, l2;
string s, s1, s2, tmp;
string a[maxn];

int main()
{
    while (~scanf("%d", &n), n)
    {
        s = "";
        for (int i = 0; i < n; ++i)
            cin >> a[i];
        sort(a, a + n);
        s1 = a[n / 2 - 1];
        s2 = a[n / 2];
        l1 = s1.size();
        l2 = s2.size();
        l = min(l1, l2);
        for (int i = 0; i < l; ++i)
            if (s1[i] == s2[i])
                s += s1[i];
            else
            {
                tmp = s + (char)(s1[i] + 1);
                if (tmp == s2)
                {
                    s += s1[i++];
                    while (i < l1 - 1 && s1[i] == 'Z')
                        s += s1[i++];
                    if (i < l1 - 1)
                        s += (char)(s1[i] + 1);
                    else
                        s = s1;
                }
                else
                {
                    if (tmp.size() == l1)
                        s = s1;
                    else
                        s = tmp;
                }
                break;
            }
        cout << s << '\n';
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值