Vladik and chat (Codeforces 754C)
Tags: Implement, strings

Recently Vladik discovered a new entertainment — coding bots for social networks. He would like to use machine learning in his bots so now he want to prepare some learning data for them.At first, he need to download t chats. Vladik coded a script which should have downloaded the chats, however, something went wrong. In particular, some of the messages have no information of their sender. It is known that if a person sends several messages in a row, they all are merged into a single message. It means that there could not be two or more messages in a row with the same sender. Moreover, a sender never mention himself in his messages.Vladik wants to recover senders of all the messages so that each two neighboring messages will have different senders and no sender will mention himself in his messages.He has no idea of how to do this, and asks you for help. Help Vladik to recover senders in each of the chats!

Input: The first line contains single integer t (1 ≤ t ≤ 10) — the number of chats. The t chats follow. Each chat is given in the following format.The first line of each chat description contains single integer n (1 ≤ n ≤ 100) — the number of users in the chat.The next line contains n space-separated distinct usernames. Each username consists of lowercase and uppercase English letters and digits. The usernames can't start with a digit. Two usernames are different even if they differ only with letters' case. The length of username is positive and doesn't exceed 10 characters.The next line contains single integer m (1 ≤ m ≤ 100) — the number of messages in the chat. The next m line contain the messages in the following formats, one per line:   <username>:<text> — the format of a message with known sender. The username should appear in the list of usernames of the chat.  <?>:<text> — the format of a message with unknown sender. The text of a message can consist of lowercase and uppercase English letter, digits, characters '.' (dot), ',' (comma), '!' (exclamation mark), '?' (question mark) and ' ' (space). The text doesn't contain trailing spaces. The length of the text is positive and doesn't exceed 100 characters.We say that a text mention a user if his username appears in the text as a word. In other words, the username appears in a such a position that the two characters before and after its appearance either do not exist or are not English letters or digits. For example, the text "Vasya, masha13 and Kate!" can mention users "Vasya", "masha13", "and" and "Kate", but not "masha".It is guaranteed that in each chat no known sender mention himself in his messages and there are no two neighboring messages with the same known sender.

Output: Print the information about the t chats in the following format:If it is not possible to recover senders, print single line "Impossible" for this chat. Otherwise print m messages in the following format:<username>:<text>If there are multiple answers, print any of them.


Sample Inputs:
1
2
Vladik netman
2
?: Hello, Vladik!
?: Hi

1
2
netman vladik
3
netman:how are you?
?:wrong message
vladik:im fine

2
3
netman vladik Fedosik
2
?: users are netman, vladik, Fedosik
vladik: something wrong with this chat
4
netman tigerrrrr banany2001 klinchuh
4
?: tigerrrrr, banany2001, klinchuh, my favourite team ever, are you ready?
klinchuh: yes, coach!
?: yes, netman
banany2001: yes of course.

Sample Outputs:
netman: Hello, Vladik!
Vladik: Hi

Impossible

Impossible
netman: tigerrrrr, banany2001, klinchuh, my favourite team ever, are you ready?
klinchuh: yes, coach!
tigerrrrr: yes, netman
banany2001: yes of course.

Solution (Python):
import sys
import re

def mentioned_usernames(line):
    return {x for x in re.split('[^A-Za-z0-9]+', line)}
t = int(input())
for ti in range(t):
    possible_users = []
    messages = []
    n = int(input())
    usernames = set(input().split())
    m = int(input())
    for i in range(m):
        (user, text) = input().split(':')
        messages.append(text)
        if user == '?':
            mu = mentioned_usernames(text)
            possible_users.append(usernames - mentioned_usernames(text))
        else:
            possible_users.append({user})
    is_fixed = [False] * m
    for i in range(m - 1):
        if len(possible_users[i]) == 1:
            possible_users[i + 1].difference_update(possible_users[i])
            is_fixed = True
    for i in range(m - 1, 0, -1):
        if len(possible_users[i]) == 1:
            possible_users[i - 1].difference_update(possible_users[i])
            is_fixed = True
    res = []
    is_possible = True
    prev_user = '$'
    for i in range(m):
        if possible_users[i]:
            pusers = possible_users[i] - {prev_user}
            resx = next(iter(pusers))
            res.append(resx)
            prev_user = resx
        else:
            is_possible = False
            break
    if is_possible:
        for i in range(m):
            print('{}:{}'.format(res[i], messages[i]))
    else:
        print('Impossible')

Solution (Python):
def solve():
    global msg, rem, m
    flag = True
    while flag:
        flag = False
        for i in range(m):
            if msg[i][0] == ' ':
                if len(rem[i]) == 0:
                    return False
                elif len(rem[i]) == 1:
                    flag = True
                    msg[i][0] = rem[i][0]
                    if i > 0:
                        try:
                            rem[i - 1].remove(rem[i][0])
                        except ValueError:
                            pass
                    if i < m - 1:
                        try:
                            rem[i + 1].remove(rem[i][0])
                        except ValueError:
                            pass
    for i in range(m):
        if len(rem[i]) >= 1:
            msg[i][0] = rem[i][0]
            if i > 0:
                try:
                    rem[i - 1].remove(rem[i][0])
                except ValueError:
                    pass
            if i < m - 1:
                try:
                    rem[i + 1].remove(rem[i][0])
                except ValueError:
                    pass
    return True
t = int(input())
for _ in range(t):
    global msg, rem, m
    n = int(input())
    names = input().split()
    m = int(input())
    msg = list()
    sm = list()
    for i in range(m):
        sm.append(input())
        msg.append(sm[-1].replace('.', ' ').replace(',', ' ').replace('!', ' ').replace('?', ' ').split(':'))
        msg[-1][1] = msg[-1][1].split()
    for (i, data) in enumerate(msg):
        if data[0] != ' ':
            if i > 0:
                msg[i - 1][1].append(data[0])
            if i < m - 1:
                msg[i + 1][1].append(data[0])
    rem = [[s for s in names if not s in msg[i][1]] if msg[i][0] == ' ' else [] for i in range(m)]
    if solve():
        for i in range(m):
            if sm[i][0] == '?':
                print(msg[i][0] + sm[i][1:])
            else:
                print(sm[i])
    else:
        print('Impossible')

Solution (Python):
def main():
    n = int(input())
    names = input().split()
    m = int(input())
    msg = [input().split(':') for _ in range(m)]
    texts = []
    for i in msg:
        texts.append(i[1])
        i[1] = i[1].replace(',', ' ').replace('.', ' ').replace('!', ' ').replace('?', ' ').split()
        if i[0] == '?':
            i.append([])
            for name in names:
                if name not in i[1]:
                    i[2].append(name)
            if len(i[2]) == 0:
                print('Impossible')
                return
    go_on = True
    while go_on:
        go_on = False
        for i in range(len(msg)):
            if msg[i][0] != '?':
                continue
            if i - 1 > -1 and msg[i - 1][0] in msg[i][2]:
                msg[i][2].remove(msg[i - 1][0])
                go_on = True
            if i + 1 < m and msg[i + 1][0] in msg[i][2]:
                msg[i][2].remove(msg[i + 1][0])
                go_on = True
            if len(msg[i][2]) == 0:
                print('Impossible')
                return
            if len(msg[i][2]) == 1:
                msg[i][0] = msg[i][2][0]
                del msg[i][2]
                go_on = True
    for i in range(len(msg)):
        if msg[i][0] == '?':
            msg[i][0] = msg[i][2][0]
            if i < m - 1 and len(msg[i + 1]) == 3 and (msg[i][0] in msg[i + 1][2]):
                msg[i + 1][2].remove(msg[i][0])
        print(msg[i][0], ':', texts[i], sep='')
t = int(input())
for _ in range(t):
    main()