A. Silent Classroom

链接:https://codeforces.com/contest/1166/problem/A

题意:

There are nn students in the first grade of Nlogonia high school. The principal wishes to split the students into two classrooms (each student must be in exactly one of the classrooms). Two distinct students whose name starts with the same letter will be chatty if they are put in the same classroom (because they must have a lot in common). Let xx be the number of such pairs of students in a split. Pairs (a,b)(a,b) and (b,a)(b,a) are the same and counted only once.

For example, if there are 66 students: "olivia", "jacob", "tanya", "jack", "oliver" and "jessica", then:

  • splitting into two classrooms ("jack", "jacob", "jessica", "tanya") and ("olivia", "oliver") will give x=4x=4 (33 chatting pairs in the first classroom, 11 chatting pair in the second classroom),
  • splitting into two classrooms ("jack", "tanya", "olivia") and ("jessica", "oliver", "jacob") will give x=1x=1 (00 chatting pairs in the first classroom, 11 chatting pair in the second classroom).

You are given the list of the nn names. What is the minimum xx we can obtain by splitting the students into classrooms?

Note that it is valid to place all of the students in one of the classrooms, leaving the other one empty.

思路:

计算每个首字母出现的次数,均匀分配到两个教室,求每边的配对数即可。

代码:

#include <bits/stdc++.h>
using namespace std;

typedef long long LL;

int dic[30];

int main()
{
    int n;
    string s;
    cin >> n;
    for (int i = 1;i <= n;i++)
    {
        cin >> s;
        char w = s[0];
        w = tolower(w);
        dic[w-'a']++;
    }
    int res = 0;
    for (int i = 0;i < 26;i++)
    {
        int l = dic[i]/2;
        int r = dic[i]-l;
        l--;
        r--;
        if (l > 0)
            res += (1+l)*l/2;
        if (r > 0)
            res += (1+r)*r/2;
    }
    cout << res << endl;

    return 0;
}

  

上一篇:一篇文章教你读懂UI绘制流程


下一篇:【算法概论】贪心算法:区间划分问题