Advertisement
theo830

problem

May 29th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.55 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #include <map>
  5. using namespace std;
  6. typedef pair<int, int> ii;
  7. typedef vector<int> vi;
  8. typedef vector<ii> vii;
  9. typedef vector<int> vi;
  10. vector<vi> AdjList1;
  11. vi visited;
  12. vi taken;
  13. vector<vii> AdjList;
  14. priority_queue< ii, vector<ii>, greater<ii> > pq;
  15. int e=0;
  16. #define INF 1e5
  17. void update(int edge) {
  18. taken[edge] = 1;
  19. for (int j = 0; j < AdjList[edge].size(); j++) {
  20. ii v = AdjList[edge][j];
  21. if (taken[v.first]==0)
  22. pq.push(ii(v.second, v.first));
  23. }
  24. }
  25. void bfs(long long s){
  26. visited[s] = 1;
  27. queue<long long> q;
  28. q.push(s);
  29. while (!q.empty()) {
  30. long long u = q.front();
  31. q.pop();
  32. e++;
  33. for (long long j = 0; j < AdjList1[u].size(); j++) {
  34. long long v = AdjList1[u][j];
  35. if (visited[v] == 0){
  36. visited[v] = 1;
  37. q.push(v);
  38. }
  39. }
  40. }
  41. }
  42. int main() {
  43. ios::sync_with_stdio(false);
  44. cin.tie(0);
  45. cout.tie(0);
  46. int t;
  47. cin>>t;
  48. for(int k=0;k<t;k++){
  49. int V, a, b, w;
  50. long long E;
  51. cin >> V >> E;
  52. map<int,bool>m;
  53. int s;
  54. vector<int>qw;
  55. taken.assign(V, 0);
  56. AdjList.assign(V, vii());
  57. AdjList1.assign(V, vi());
  58. for(int i=0;i<V;i++){
  59. cin>>m[i];
  60. if(m[i] == 1){
  61. s=i;
  62. for(int j=0;j<qw.size();j++){
  63. AdjList[i].push_back(ii(qw[j],0));
  64. AdjList[qw[j]].push_back(ii(i,0));
  65. AdjList1[i].push_back(qw[j]);
  66. AdjList1[qw[j]].push_back(i);
  67. }
  68. qw.push_back(s);
  69. }
  70. }
  71. visited.assign(V, 0);
  72. for (long long i = 0; i < E; i++) {
  73. cin >> a >> b >> w;
  74. if(m[a-1] != 1 || m[b-1] != 1){
  75. AdjList[a-1].push_back(ii(b-1, w));
  76. AdjList[b-1].push_back(ii(a-1, w));
  77. }
  78. AdjList1[a-1].push_back(b-1);
  79. AdjList1[b-1].push_back(a-1);
  80. }
  81. e=0;
  82. bfs(0);
  83. if(e != V){
  84. cout<<"impossible"<<endl;
  85. }
  86. else{
  87. int cost = 0;
  88. update(s);
  89. while (!pq.empty()){
  90. ii front = pq.top();
  91. pq.pop();
  92. int w = front.first;
  93. int u = front.second;
  94. if (taken[u]==0){
  95. cost += w;
  96. }
  97. update(u);
  98. }
  99. cout<<cost<<endl;
  100. }
  101. }
  102. return 0;
  103. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement