1
0

Program.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. namespace D5._2
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. if (args.Length < 1) return;
  11. if (File.Exists(args[0]) == false) return;
  12. var file = File.OpenText(args[0]);
  13. string polymer = file.ReadLine();
  14. int shortest = polymer.Length;
  15. for (char i = 'A'; i <= 'Z'; i++)
  16. {
  17. var altera = AlterPolymer(polymer, i);
  18. Reduce(ref altera);
  19. if (altera.Length < shortest) shortest = altera.Length;
  20. }
  21. Console.WriteLine(shortest);
  22. }
  23. static void Reduce(ref string polymer)
  24. {
  25. for (int i = 1; i < polymer.Length; i++)
  26. {
  27. char cc = polymer[i];
  28. char cm = polymer[i - 1];
  29. if (Math.Abs(cc - cm) <= 26) continue;
  30. if (Up(cc) == Up(cm))
  31. {
  32. polymer = polymer.Remove(i - 1, 2);
  33. i = Math.Max(0, i - 2);
  34. }
  35. }
  36. }
  37. static string AlterPolymer(string polymer, char unit)
  38. {
  39. string newPolymer = string.Empty;
  40. foreach (var car in polymer)
  41. {
  42. if (Up(car) == Up(unit)) continue;
  43. newPolymer += car;
  44. }
  45. return newPolymer;
  46. }
  47. static char Up(char c)
  48. {
  49. if (c >= 'A' && c <= 'Z') return c;
  50. return (char)('A' + (c - 'a'));
  51. }
  52. }
  53. }