zoukankan      html  css  js  c++  java
  • hihocoder 分隔相同字符

    思路:

    枚举,贪心。

    在“合法”的前提下放置越排在前边的字母越好。

    “合法”:'a' - 'z'中没有一个字母的个数超过当前串剩余长度的一半(偶数情况下)或长度的一半加1(奇数情况下)。

    实现:

     1 #include <iostream>
     2 #include <cstdio>
     3 #include <string>
     4 using namespace std;
     5 
     6 string s;
     7 int n, cnt[26];
     8 
     9 bool check(int x)
    10 {
    11     for (int i = 0; i < 26; i++)
    12     {
    13         if (cnt[i] > x / 2 + (x & 1))
    14         {
    15             return false;
    16         }
    17     }
    18     return true;
    19 }
    20 
    21 int main()
    22 {
    23     cin >> s;
    24     n = s.length();
    25     int m = n;
    26     for (int i = 0; i < n; i++)
    27     {
    28         cnt[s[i] - 'a']++;
    29     }
    30     if (!check(n))
    31     {
    32         puts("INVALID");
    33         return 0;
    34     }
    35     int last = -1;
    36     for (int i = 0; i < n; i++)
    37     {
    38         for (int j = 0; j < 26; j++)
    39         {
    40             if (cnt[j] && j != last)
    41             {
    42                 cnt[j]--;
    43                 if (check(m - 1))
    44                 {
    45                     putchar('a' + j);
    46                     last = j;
    47                     m--;
    48                     break;
    49                 }
    50                 else
    51                     cnt[j]++;
    52             }
    53         }
    54     }
    55     puts("");
    56     return 0;
    57 }
  • 相关阅读:
    NSLocalizedString用法
    4-27学习心得
    手势学习
    plist处理
    数据存储
    initWithFrame方法
    控制器跳转小常识
    UIGestureRecognizer学习笔记
    博客资源
    检测手机wifi有没有打开
  • 原文地址:https://www.cnblogs.com/wangyiming/p/6655281.html
Copyright © 2011-2022 走看看