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 }
  • 相关阅读:
    HDOJ骨头的诱惑
    DP Big Event in HDU
    hoj1078
    poj2728
    hoj1195
    poj2739
    poj2726
    海量并发也没那么可怕,运维准点下班全靠它!
    云上安全工作乱如麻,等保2.0来一下
    实践案例丨教你一键构建部署发布前端和Node.js服务
  • 原文地址:https://www.cnblogs.com/wangyiming/p/6655281.html
Copyright © 2011-2022 走看看