Advertisement
theo830

πριο

May 29th, 2019
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.50 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.  
  27. visited[s] = 1;
  28.  
  29. queue<long long> q;
  30.  
  31. q.push(s);
  32.  
  33. while (!q.empty()) {
  34.  
  35. long long u = q.front();
  36.  
  37. q.pop();
  38.  
  39. e++;
  40.  
  41. for (long long j = 0; j < AdjList1[u].size(); j++) {
  42.  
  43. long long v = AdjList1[u][j];
  44.  
  45. if (visited[v] == 0){
  46.  
  47. visited[v] = 1;
  48.  
  49. q.push(v);
  50.  
  51. }
  52.  
  53. }
  54.  
  55. }
  56.  
  57. }
  58. int main() {
  59. ios::sync_with_stdio(false);
  60. cin.tie(0);
  61. cout.tie(0);
  62. int t;
  63. cin>>t;
  64. for(int k=0;k<t;k++){
  65. int V, a, b, w;
  66. long long E;
  67. cin >> V >> E;
  68. map<int,bool>m;
  69. int s;
  70. bool q1=0;
  71. vector<int>qw;
  72. taken.assign(V, 0);
  73. AdjList.assign(V, vii());
  74. AdjList1.assign(V, vi());
  75. for(int i=0;i<V;i++){
  76. cin>>m[i];
  77. if(m[i] == 1){
  78. s=i;
  79. q1= 1;
  80. for(int j=0;j<qw.size();j++){
  81. AdjList[i].push_back(ii(qw[j],0));
  82. AdjList[qw[j]].push_back(ii(i,0));
  83. }
  84. qw.push_back(s);
  85. }
  86. }
  87. visited.assign(V, 0);
  88. for (long long i = 0; i < E; i++) {
  89. cin >> a >> b >> w;
  90. if(m[a-1] != 1 || m[b-1] != 1){
  91. AdjList[a-1].push_back(ii(b-1, w));
  92. AdjList[b-1].push_back(ii(a-1, w));
  93. }
  94. AdjList1[a-1].push_back(b-1);
  95. AdjList1[b-1].push_back(a-1);
  96. }
  97. e=0;
  98. bfs(0);
  99. if(e != V || q1 == 0){
  100. cout<<"impossible"<<endl;
  101. }
  102. else{
  103. int cost = 0;
  104. update(s);
  105. while (!pq.empty()){
  106. ii front = pq.top();
  107. pq.pop();
  108. int w = front.first;
  109. int u = front.second;
  110. if (taken[u]==0){
  111. cost += w;
  112. }
  113. update(u);
  114. }
  115. cout<<cost<<endl;
  116. }
  117. }
  118. return 0;
  119. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement