abdukodir

Untitled

Oct 24th, 2015
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #define doShift(planetMap,lastVisitedPlanet) ((planetMap) - (1 << (lastVisitedPlanet)))
  5. using namespace std;
  6.  
  7. int costOfFly[20][20];
  8. int minCostOfWay[1000000][20];
  9. int path[1000000][20];
  10. int planetCount;
  11.  
  12. int TravellingMan(int planetMap, int lastVisitedPlanet)
  13. {
  14. if (!doShift(planetMap,lastVisitedPlanet))
  15. {
  16. path[planetMap][lastVisitedPlanet] = -1;
  17. minCostOfWay[planetMap][lastVisitedPlanet] = 0;
  18. return 0;
  19. }
  20. if (path[planetMap][lastVisitedPlanet])
  21. {
  22. return minCostOfWay[planetMap][lastVisitedPlanet];
  23. }
  24. int inf =(1LL<<16) - 1LL;
  25. minCostOfWay[planetMap][lastVisitedPlanet] = inf;
  26. for (int planet = 0; planet < planetCount; planet++)
  27. {
  28. if (planet != lastVisitedPlanet && ((planetMap >> planet)&1))
  29. {
  30. int tmp = TravellingMan(doShift(planetMap,lastVisitedPlanet), planet) + costOfFly[planet][lastVisitedPlanet];
  31. if (minCostOfWay[planetMap][lastVisitedPlanet] > tmp)
  32. {
  33. minCostOfWay[planetMap][lastVisitedPlanet] = tmp;
  34. path[planetMap][lastVisitedPlanet] = planet + 1;
  35. }
  36. }
  37. }
  38. return minCostOfWay[planetMap][lastVisitedPlanet];
  39. }
  40.  
  41. void printPath(int t, int resLastVisitedPlanet)
  42. {
  43. if (resLastVisitedPlanet < 0)
  44. {
  45. return;
  46. }
  47. resLastVisitedPlanet--;
  48. printPath(doShift(t, resLastVisitedPlanet), path[t][resLastVisitedPlanet]);
  49. cout << resLastVisitedPlanet + 1 << " ";
  50. }
  51. main()
  52. {
  53. ios_base::sync_with_stdio(0);
  54. freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout);
  55. cin >> planetCount;
  56. for(int i = 0; i < planetCount; i++)
  57. {
  58. for(int j = 0; j < planetCount; j++)
  59. {
  60. cin >> costOfFly[i][j];
  61. }
  62. }
  63.  
  64. int resLastVisitedPlanet = 0;
  65. int visitedAllPlanets = (1 << planetCount) - 1;
  66.  
  67. for (int tryEndPlanet = 0; tryEndPlanet < planetCount; tryEndPlanet++)
  68. {
  69. int tmp = TravellingMan(visitedAllPlanets, tryEndPlanet);
  70. if (tmp < minCostOfWay[visitedAllPlanets][resLastVisitedPlanet])
  71. {
  72. resLastVisitedPlanet = tryEndPlanet;
  73. }
  74. }
  75. cout << minCostOfWay[visitedAllPlanets][resLastVisitedPlanet] << endl;
  76. printPath(visitedAllPlanets, resLastVisitedPlanet+1);
  77. return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment