fork download
  1. // Author: Ivan Kazmenko (gassa@mail.ru)
  2. // construct a chain of observations by repeatedly finding the closest one
  3. module solution;
  4. import std.algorithm, std.array, std.conv, std.stdio, std.string;
  5.  
  6. immutable int infinity = int.max / 2;
  7.  
  8. int dist (int [] u, int [] v)
  9. {
  10. int res = infinity;
  11. foreach (i; 0..u.length)
  12. if (u[i] && v[i] && u[i] > v[i])
  13. res = min (res, u[i] - v[i]);
  14. return res;
  15. }
  16.  
  17. int solve (int n, int m, int [] [] a)
  18. {
  19. int [] cur = a[0];
  20. int res = 0;
  21. do
  22. {
  23. int [] next = a.minElement !(p => dist (cur, p));
  24. int delta = dist (cur, next);
  25. if (delta == infinity)
  26. return -1;
  27. res += delta;
  28. cur = next;
  29. }
  30. while (cur != a[0]);
  31. return res;
  32. }
  33.  
  34. void main ()
  35. {
  36. int n, m;
  37. readf (" %s %s", &n, &m);
  38. readln;
  39. int [] [] a;
  40. foreach (k; 0..m)
  41. a ~= readln.split.map !(x => x == "X" ? 0 : x.to!int).array;
  42. writeln (solve (n, m, a));
  43. }
  44.  
Success #stdin #stdout 0s 16456KB
stdin
4 5
X 3 5 7
X 2 4 6
X 3 5 7
1 6 X X
4 X 1 3
stdout
10