fork download
  1. using System;
  2.  
  3. public class Test
  4. {
  5. private static int[,] Assing(int[] subjects, int[] controls, int count) {
  6. if (count * subjects.Length > controls.Length) {
  7. throw new ArgumentException();
  8. }
  9. Array.Sort(subjects);
  10. Array.Sort(controls);
  11. var subjTimesCount = new int[subjects.Length*count];
  12. for (var i = 0 ; i < subjects.Length ; i++) {
  13. for (var j = 0 ; j != count ; j++) {
  14. subjTimesCount[i*count + j] = subjects[i];
  15. }
  16. }
  17. var mem = new int[subjTimesCount.Length,controls.Length];
  18. for (var i = 0; i < subjects.Length; i++) {
  19. for (var j = 0; j != count; j++) {
  20. mem[i,j] = -1;
  21. }
  22. }
  23. var assignments = new int[subjTimesCount.Length];
  24. var x = RecAssign(subjTimesCount, controls, mem, 0, 0, assignments);
  25. Console.WriteLine(x);
  26. var res = new int[subjects.Length,count];
  27. for (var i = 0; i < subjects.Length; i++) {
  28. for (var j = 0; j != count; j++) {
  29. res[i, j] = assignments[i*count + j];
  30. }
  31. }
  32. return res;
  33. }
  34. private static int RecAssign(int[] subjects, int[] controls, int[,] mem, int sp, int cp, int[] assignments) {
  35. if (sp == subjects.Length) {
  36. return 0;
  37. }
  38. if (mem[sp, cp] > 0) {
  39. return mem[sp, cp];
  40. }
  41. var res = Math.Abs(subjects[sp] - controls[cp])
  42. + RecAssign(subjects, controls, mem, sp + 1, cp + 1, assignments);
  43. assignments[sp] = cp;
  44. if (cp+1+subjects.Length-sp < controls.Length) {
  45. var alt = RecAssign(subjects, controls, mem, sp, cp + 1, assignments);
  46. if (alt < res) {
  47. res = alt;
  48. } else {
  49. assignments[sp] = cp;
  50. }
  51. }
  52. mem[sp, cp] = res;
  53. return res;
  54. }
  55. static void Main() {
  56. var subj = new[] {190, 100};
  57. var ctrl = new[] {70, 180, 220, 240, 500, 600, 600};
  58. var res = Assing(subj, ctrl, 2);
  59. for (var i = 0 ; i != subj.Length ; i++) {
  60. for (var j = 0; j != 2; j++) {
  61. Console.Error.WriteLine(
  62. "{0}:{1} -- subj={2} loc={3} diff:{4}"
  63. , i
  64. , j
  65. , subj[i]
  66. , ctrl[res[i,j]]
  67. , Math.Abs(subj[i] - ctrl[res[i,j]])
  68. );
  69. }
  70. }
  71. }
  72. }
Success #stdin #stdout 0.04s 34016KB
stdin
Standard input is empty
stdout
190