Untitled
unknown
plain_text
a year ago
2.5 kB
7
Indexable
#include <bits/stdc++.h>
using namespace std;
int find(int x, vector<int>& parent)
{
if (parent[x] != x)
{
parent[x] = find(parent[x], parent);
}
return parent[x];
}
void unionByRank(int u, int v, vector<int>& parent, vector<int>& rank)
{
int rootU = find(u, parent);
int rootV = find(v, parent);
if (rootU != rootV)
{
if (rank[rootU] < rank[rootV])
{
parent[rootU] = rootV;
}
else if (rank[rootU] > rank[rootV])
{
parent[rootV] = rootU;
}
else
{
parent[rootV] = rootU;
rank[rootU]++;
}
}
}
int main()
{
int v, e;
cin >> v >> e;
vector<vector<int>> edges(e, vector<int>(3));
for (int i = 0; i < e; ++i)
{
cin >> edges[i][0] >> edges[i][1] >> edges[i][2];
edges[i][0]--;
edges[i][1]--;
}
int k;
cin >> k;
vector<int> mustIncludeIndexes(k);
for (int i = 0; i < k; ++i)
{
cin >> mustIncludeIndexes[i];
}
vector<int> parent(v);
vector<int> rank(v, 0);
for (int i = 0; i < v; ++i)
{
parent[i] = i;
}
int tot_weight = 0;
vector<vector<int>> mst;
for (int idx : mustIncludeIndexes)
{
if (idx < 0 || idx >= e)
{
cout << -1 << endl;
return 0;
}
int u = edges[idx][0];
int v = edges[idx][1];
if (find(u, parent) == find(v, parent))
{
cout << -1 << endl;
return 0;
}
mst.push_back(edges[idx]);
tot_weight += edges[idx][2];
unionByRank(u, v, parent, rank);
}
sort(edges.begin(), edges.end(), [](const vector<int>& a, const vector<int>& b)
{
return a[2] < b[2];
});
for (const auto& edge : edges)
{
int u = edge[0];
int v = edge[1];
int weight = edge[2];
if (find(u, parent) != find(v, parent))
{
mst.push_back(edge);
tot_weight += weight;
unionByRank(u, v, parent, rank);
}
}
int componentCount = 0;
for (int i = 0; i < v; ++i)
{
if (find(i, parent) == i)
{
componentCount++;
}
}
if (componentCount > 1)
{
cout << -1 << endl;
}
else
{
cout << tot_weight << endl;
}
return 0;
}
/*
6 8
1 2 2
1 3 3
2 3 1
3 4 4
4 5 5
2 5 8
5 6 6
4 6 7
3
5 6 7
*/
Editor is loading...
Leave a Comment