Guest User

Untitled

a guest
Dec 14th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. //O(M * 2^M), here M = 2 * N.
  2. #include <algorithm> // if you have problems with this C++ code,
  3. #include <cmath> // consult your programming text books first...
  4. #include <cstdio>
  5. #include <cstring>
  6. using namespace std;
  7. int N, target; // but it is OK for competitive programming
  8. double dist[20][20], memo[1 << 16]; // 1 << 16 = 2^16, note that max N = 8
  9. double matching(int bitmask) { // DP state = bitmask
  10. // we initialize ‘memo’ with -1 in the main function
  11. if (memo[bitmask] > -0.5) // this state has been computed before
  12. return memo[bitmask]; // simply lookup the memo table
  13. if (bitmask == target) // all students are already matched
  14. return memo[bitmask] = 0; // the cost is 0
  15. double ans = 2000000000.0; // initialize with a large value
  16. int p1, p2;
  17. for (p1 = 0; p1 < 2 * N; p1++)
  18. if (!(bitmask & (1 << p1)))
  19. break; // find the first bit that is off
  20. for (p2 = p1 + 1; p2 < 2 * N; p2++) // then, try to match p1
  21. if (!(bitmask & (1 << p2))) // with another bit p2 that is also off
  22. ans = min(ans, // pick the minimum
  23. dist[p1][p2] + matching(bitmask | (1 << p1) | (1 << p2)));
  24. return memo[bitmask] = ans; // store result in a memo table and return
  25. }
  26. int main() {
  27. int i, j, caseNo = 1, x[20], y[20];
  28. while (scanf("%d", &N), N) { // yes, we can do this :)
  29. for (i = 0; i < 2 * N; i++)
  30. scanf("%*s %d %d", &x[i], &y[i]); // ’%*s’ skips names
  31. for (i = 0; i < 2 * N - 1; i++) // build pairwise distance table
  32. for (j = i + 1; j < 2 * N; j++) // have you used ‘hypot’ before?
  33. dist[i][j] = dist[j][i] = hypot(x[i] - x[j], y[i] - y[j]);
  34. // use DP to solve min weighted perfect matching on small general graph
  35. for (i = 0; i < (1 << 16); i++) memo[i] = -1.0; // set -1 to all cells
  36. target = (1 << (2 * N)) - 1;
  37. printf("Case %d: %.2lf\n", caseNo++, matching(0));
  38. }
  39. }
Add Comment
Please, Sign In to add comment