题解:P13992 【MX-X19-T1】「FeOI Round 4.5」五字神人

· · 题解

洛谷 P13992

解题思路:

这题考查贪心。不难发现,如果字符串长度不超过 5,那么,答案就是 5 - |s|,否则答案就是以下三种情况的最小值:

  1. 判断大写字母有多少个,如果不超过五个,就可以把小写改大写;

  2. 把字符串删成长度为五;

  3. 大写字母超过五个,把大写字母删成五个。

    AC 代码:

    #include<bits/stdc++.h>
    using namespace std;
    int t;
    int main() {
     cin >> t;
    
     while (t--) {
         string s;
         cin >> s;
         int s1 = 0, s2 = 0;
    
         for (int i = 0; i < s.size(); i++) {
             if (s[i] >= 'a' && s[i] <= 'z') {
                 s1++;
             } else if (s[i] >= 'A' && s[i] <= 'Z') {
                 s2++;
             }
         }
    
         int n = s.size();
    
         if (n == 5 || s2 == 5) {
             cout << 0 << endl;
             continue;
         }
    
         if (n < 5) {
             cout << 5 - n << endl;
             continue;
         }
    
         int ans = 0x3f3f3f3f;
         ans = min(ans, n - 5);
    
         if (s2 < 5) {
             ans = min(ans, 5 - s2);
         } else {
             ans = min(ans, s2 - 5);
         }
    
         cout << ans << endl;
     }
    
     return 0;
    }