add1ctus

Untitled

Mar 6th, 2016
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. #include <cstdio>
  2. #include <vector>
  3. #include <utility>
  4. #include <cstring>
  5.  
  6. using namespace std;
  7.  
  8. int n,m;
  9. int graph[101][101];
  10.  
  11. bool visited[101];
  12. int dist[101];
  13. int source[101];
  14.  
  15. vector<pair<int,int> > used;
  16.  
  17. int doMST(bool record)
  18. {
  19. memset(visited,0,sizeof(visited));
  20. for(int i = 0 ; i < 101 ; ++i)
  21. dist[i] = 99999999;
  22. dist[1] = 0;
  23. int totalCost = 0;
  24. for(int i = 0; i < n ; ++i)
  25. {
  26. int smallest = -1;
  27. for(int j = 1 ; j <= n ; ++j)
  28. if(!visited[j] && (smallest == -1 || dist[smallest]>dist[j]))
  29. smallest = j;
  30. visited[smallest] = true;
  31. // printf("Next smallest is %d with dist %d\n",smallest,dist[smallest]);
  32. if(record && smallest != 1)
  33. used.push_back(make_pair(smallest, source[smallest]));
  34. // printf("Connected %d with %d\n",smallest,source[smallest]);
  35. totalCost += dist[smallest];
  36. for(int j = 1 ; j <= n ; ++j)
  37. if(graph[smallest][j] != -1)
  38. if(graph[smallest][j] < dist[j])
  39. {
  40. dist[j] = graph[smallest][j];
  41. source[j] = smallest;
  42. }
  43. }
  44. return totalCost;
  45. }
  46.  
  47. int main()
  48. {
  49. memset(graph,-1,sizeof(graph));
  50.  
  51. scanf("%d%d",&n,&m);
  52. for(int i = 0 ; i < m ; ++i)
  53. {
  54. int a,b,c;
  55. scanf("%d%d%d",&a,&b,&c);
  56. graph[a][b] = graph[b][a] = c;
  57. }
  58.  
  59. printf("%d ",doMST(true));
  60. int best = 999999999;
  61. for(int i = 0 ; i < used.size() ; ++i)
  62. {
  63. int a = used[i].first;
  64. int b = used[i].second;
  65. // printf("%d - %d\n",a,b);
  66. int remember = graph[a][b];
  67. graph[a][b] = graph[b][a] = -1;
  68. best = min(best, doMST(false));
  69. graph[a][b] = graph[b][a] = remember;
  70. }
  71. printf("%d",best);
  72.  
  73. return 0;
  74. }
Add Comment
Please, Sign In to add comment