Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.54 KB | None | 0 0
  1. #include <iostream>
  2. #include <set>
  3. #include <vector>
  4. #include <algorithm>
  5.  
  6. using namespace std;
  7.  
  8. #define MAXN 14
  9.  
  10. long long dst[MAXN][MAXN];
  11.  
  12. int main() {
  13. // Read input
  14. int N;
  15. long long L;
  16. cin >> N >> L;
  17. for(int i = 0; i < N; i++)
  18. for(int j = 0; j < N; j++)
  19. cin >> dst[i][j];
  20.  
  21. // Meet in the middle approach, try to make a route
  22. // from 0 to midpoint in two distinct ways
  23. bool possible = false;
  24. for(int midpoint = 1; midpoint < N; midpoint++) {
  25. // Loop over every set of (N-2)/2 nodes
  26. int half = (N - 2) / 2;
  27. for(int mask = 0; mask < (1<<N); mask++) {
  28. if(mask & 1) continue; // Contains start
  29. if(mask & (1<<midpoint)) continue; // Contains midpoint
  30. if(__builtin_popcount(mask) != half) continue; // Number of nodes not correct
  31.  
  32. // For this set of half of the points, store all possible lengths
  33. set<long long> found;
  34.  
  35. for(int k = 0; k < 2; k++) {
  36. // Find all current nodes (those in mask for k = 0,
  37. // or those not in mask for k = 1)
  38. vector<int> curroute;
  39. curroute.push_back(0);
  40. for(int i = 1; i < N; i++) {
  41. if(i == midpoint) continue;
  42. if((k == 0) == ((mask & (1<<i)) > 0))
  43. curroute.push_back(i);
  44. }
  45. curroute.push_back(midpoint);
  46.  
  47. // Loop over all permutations
  48. do {
  49. // Find the length
  50. long long len = 0;
  51. for(int i = 0; len < L && i < (int)curroute.size() - 1; i++)
  52. len += dst[curroute[i]][curroute[i+1]];
  53. if(len > L) continue; // Can never lead to a correct route
  54.  
  55.  
  56. if(k == 0) {
  57. // Insert into list of found lengths
  58. found.insert(len);
  59. }
  60. else {
  61. // Check if we can match this with an opposite route
  62. if(found.find(L - len) != found.end())
  63. possible = true;
  64. }
  65.  
  66. } while(next_permutation(curroute.begin() + 1, curroute.end() - 1));
  67. }
  68. }
  69. }
  70.  
  71. cout << (possible ? "possible" : "impossible") << endl;
  72.  
  73. return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement