• Source
    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Text;
    5. using System.IO;
    6.  
    7. namespace Protsyk.Puzzles.StudiousStudent {
    8. class Program {
    9. static int N;
    10.  
    11. static void Main(string[] args) {
    12. string s = new StreamReader(Console.OpenStandardInput()).ReadToEnd();
    13. string[] splits = s.Split(new char[] { '\n', '\r' },
    14. StringSplitOptions.RemoveEmptyEntries);
    15.  
    16. N = int.Parse(splits[0]);
    17. for (int i = 1; i < N + 1; i++) {
    18. string[] words = splits[i]
    19. .Split(' ')
    20. .Skip(1)
    21. .ToArray();
    22.  
    23. Console.WriteLine(Solve(words));
    24. }
    25. }
    26.  
    27. private static string Solve(string[] words) {
    28. string prefix = string.Empty;
    29. List<string> sorted = new List<string>(words);
    30.  
    31. while (true) {
    32. sorted = sorted.OrderBy(x => x).ToList();
    33. if (sorted.Count == 0) break;
    34.  
    35. string pr = sorted.First();
    36. string sf = sorted.Skip(1)
    37. .Where(a => a.StartsWith(pr))
    38. .Select(s => s.Substring(pr.Length))
    39. .Where(s => !string.IsNullOrEmpty(s))
    40. .OrderBy(x => x + pr)
    41. .FirstOrDefault();
    42.  
    43. if (string.Compare(pr + pr, pr + sf) < 0)
    44. sf = null;
    45.  
    46. prefix += pr + sf;
    47. sorted.Remove(pr + sf);
    48. }
    49.  
    50. return prefix;
    51. }
    52. }
    53. }