Beautiful Lyrics (Codeforces 1182C)
Tags: Greedy, strings

You are given $$$n$$$ words, each of which consists of lowercase alphabet letters. Each word contains at least one vowel. You are going to choose some of the given words and make as many beautiful lyrics as possible.Each lyric consists of two lines. Each line consists of two words separated by whitespace. A lyric is beautiful if and only if it satisfies all conditions below.   The number of vowels in the first word of the first line is the same as the number of vowels in the first word of the second line.  The number of vowels in the second word of the first line is the same as the number of vowels in the second word of the second line.  The last vowel of the first line is the same as the last vowel of the second line. Note that there may be consonants after the vowel. Also, letters "a", "e", "o", "i", and "u" are vowels. Note that "y" is never vowel.For example of a beautiful lyric,  "hello hellooowww" "whatsup yowowowow"  is a beautiful lyric because there are two vowels each in "hello" and "whatsup", four vowels each in "hellooowww" and "yowowowow" (keep in mind that "y" is not a vowel), and the last vowel of each line is "o".For example of a not beautiful lyric,  "hey man""iam mcdic"  is not a beautiful lyric because "hey" and "iam" don't have same number of vowels and the last vowels of two lines are different ("a" in the first and "i" in the second).How many beautiful lyrics can you write from given words? Note that you cannot use a word more times than it is given to you. For example, if a word is given three times, you can use it at most three times.

Input: The first line contains single integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of words.The $$$i$$$-th of the next $$$n$$$ lines contains string $$$s_{i}$$$ consisting lowercase alphabet letters — the $$$i$$$-th word. It is guaranteed that the sum of the total word length is equal or less than $$$10^{6}$$$. Each word contains at least one vowel.

Output: In the first line, print $$$m$$$ — the number of maximum possible beautiful lyrics.In next $$$2m$$$ lines, print $$$m$$$ beautiful lyrics (two lines per lyric).If there are multiple answers, print any.

Note: In the first example, those beautiful lyrics are one of the possible answers. Let's look at the first lyric on the sample output of the first example. "about proud hooray round" forms a beautiful lyric because "about" and "hooray" have same number of vowels, "proud" and "round" have same number of vowels, and both lines have same last vowel. On the other hand, you cannot form any beautiful lyric with the word "codeforces".In the second example, you cannot form any beautiful lyric from given words.In the third example, you can use the word "same" up to three times.

Sample Inputs:
14
wow
this
is
the
first
mcdics
codeforces
round
hooray
i
am
proud
about
that

7
arsijo
suggested
the
idea
for
this
problem

4
same
same
same
differ

Sample Outputs:
3
about proud
hooray round
wow first
this is
i that
mcdics am

0

1
same differ
same same

Solution (Python):
VOWELS = {'a', 'e', 'i', 'o', 'u'}

def get_head_pair(head, words):
    pair = None
    on_pop = list()
    for (vowels_cnt, letters) in head.items():
        if len(letters) < 2:
            on_pop.append(vowels_cnt)
        else:
            ltr1 = letters.pop(-1)
            ltr2 = letters.pop(-1)
            pair = (words[f'{ltr1}{vowels_cnt}'].pop(-1), words[f'{ltr2}{vowels_cnt}'].pop(-1))
            break
    for key in on_pop:
        head.pop(key)
    return pair

def mark_word(word):
    cnt = 0
    last = None
    for ltr in word:
        if ltr in VOWELS:
            cnt += 1
            last = ltr
    return f'{last}{cnt}'

def main():
    n = int(input())
    mark_cnt = dict()
    words = dict()
    for _ in range(n):
        word = input()
        mark = mark_word(word)
        if mark not in mark_cnt:
            mark_cnt[mark] = 0
        mark_cnt[mark] += 1
        if mark not in words:
            words[mark] = list()
        words[mark].append(word)
    tail = dict()
    for (mark, cnt) in mark_cnt.items():
        if cnt < 2:
            continue
        if mark not in tail:
            tail[mark] = 0
        tail[mark] += cnt // 2 * 2
        mark_cnt[mark] = cnt % 2
    head = dict()
    for (mark, cnt) in mark_cnt.items():
        if cnt != 1:
            continue
        letter = mark[0]
        vowels_cnt = int(mark[1:])
        if vowels_cnt not in head:
            head[vowels_cnt] = list()
        head[vowels_cnt].append(letter)
    result = list()
    stop = False
    for (mark, cnt) in tail.items():
        if stop:
            break
        for _ in range(cnt // 2):
            head_pair = get_head_pair(head, words)
            if head_pair is None:
                stop = True
                break
            tail_pair = (words[mark].pop(-1), words[mark].pop(-1))
            tail[mark] -= 2
            result.append(f'{head_pair[0]} {tail_pair[0]}\n{head_pair[1]} {tail_pair[1]}')
    if stop:
        subres = list()
        for (mark, cnt) in tail.items():
            if cnt == 0:
                continue
            for _ in range(cnt // 2):
                if len(subres) == 4:
                    result.append(f'{subres[0]} {subres[2]}\n{subres[1]} {subres[3]}')
                    subres = list()
                subres.append(words[mark].pop(-1))
                subres.append(words[mark].pop(-1))
            if len(subres) == 4:
                result.append(f'{subres[0]} {subres[2]}\n{subres[1]} {subres[3]}')
                subres = list()
        if len(subres) == 4:
            result.append(f'{subres[0]} {subres[2]}\n{subres[1]} {subres[3]}')
    print(len(result))
    print('\n'.join(result))
main()

Solution (Python):
from sys import stdin
input = stdin.readline

def pre(s):
    last = None
    cnt = 0
    for i in s:
        if i in 'aeiou':
            last = i
            cnt += 1
    return (cnt, last)
from collections import defaultdict
n = int(input())
q = []
for i in range(n):
    s = input().strip()
    (cnt, last) = pre(s)
    q.append((s, cnt, last))
d = defaultdict(lambda : defaultdict(list))
for (s, cnt, last) in q:
    d[cnt][last].append(s)
f = defaultdict(list)
l = []
for cnt in d:
    bad = []
    for last in d[cnt]:
        if len(d[cnt][last]) % 2 == 1:
            f[cnt].append(d[cnt][last].pop(0))
            if len(d[cnt][last]) == 0:
                bad.append(last)
        while len(d[cnt][last]) >= 2:
            a = d[cnt][last].pop()
            b = d[cnt][last].pop()
            l.append((a, b))
ans = []
for cnt in f:
    while len(f[cnt]) >= 2:
        a = f[cnt].pop()
        b = f[cnt].pop()
        ans.append([(a, b)])
cnt = 0
for (id, word) in enumerate(ans):
    if len(l):
        b = l.pop()
        ans[id].append(b)
        cnt += 1
    else:
        break
while len(l) >= 2:
    a = l.pop()
    b = l.pop()
    ans.append([a, b])
    cnt += 1
print(cnt)
if cnt:
    for i in ans:
        if len(i) == 1:
            continue
        (a, b) = (i[0], i[1])
        try:
            print(a[0], b[0])
            print(a[1], b[1])
        except Exception as e:
            print(e)

Solution (Python):
import sys
import itertools
from collections import defaultdict
vowels = 'aeiou'

def getvowelindex(word):
    count = 0
    for c in word:
        if c in vowels:
            count += 1
            lastvowel = c
    return (count, lastvowel)
n = int(sys.stdin.readline().strip())
words = (line.strip() for line in sys.stdin.readlines())
collected = defaultdict(list)
for word in words:
    collected[getvowelindex(word)].append(word)
rhymepairs = []
normalpairs = []
remaining = defaultdict(list)
for (key, s) in collected.items():
    while bool(s):
        first = s.pop()
        if bool(s):
            second = s.pop()
            rhymepairs.append((first, second))
        else:
            remaining[key[0]].append(first)
for s in remaining.values():
    while bool(s):
        first = s.pop()
        if bool(s):
            normalpairs.append((first, s.pop()))
outputstrings = []
while bool(rhymepairs):
    rhyme = rhymepairs.pop()
    if bool(normalpairs):
        normal = normalpairs.pop()
    elif bool(rhymepairs):
        normal = rhymepairs.pop()
    else:
        break
    outputstrings.append(f'{normal[0]} {rhyme[0]}' + '\n' + f'{normal[1]} {rhyme[1]}')
print(len(outputstrings))
for str in outputstrings:
    print(str)