This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include<bits/stdc++.h>
using namespace std;
int n,m,q,w;
pair< int, pair<int,int> > ed[100005];
vector<int> used[100005], used2[100005], v[100005];
int dsu[505];
int find(int x) {
if(dsu[x]==x) return x;
else return dsu[x] = find(dsu[x]);
}
void merge(int x, int y) {
dsu[find(x)] = find(y);
}
bool cmp(int x, int y) {
return abs(w-ed[x].first) < abs(w-ed[y].first);
}
int main() {
ios::sync_with_stdio(false);
cin >> n >> m;
for(int i=0; i<m; i++) {
cin >> ed[i].second.first >> ed[i].second.second >> ed[i].first;
}
sort(ed, ed+m);
for(int i=1; i<=m; i++) {
for(int j=1; j<=n; j++) dsu[j] = j;
used[i].push_back(i-1);
merge(ed[i-1].second.first, ed[i-1].second.second);
for(int j:used[i-1]) {
if(find(ed[j].second.first) != find(ed[j].second.second)) {
merge(ed[j].second.first, ed[j].second.second);
used[i].push_back(j);
}
}
}
for(int i=m-1; i>=0; i--) {
for(int j=1; j<=n; j++) dsu[j] = j;
used2[i].push_back(i);
merge(ed[i].second.first, ed[i].second.second);
for(int j:used2[i+1]) {
if(find(ed[j].second.first) != find(ed[j].second.second)) {
merge(ed[j].second.first, ed[j].second.second);
used2[i].push_back(j);
}
}
}
for(int i=0; i<=m; i++) {
for(int j:used[i]) v[i].push_back(j);
for(int j:used2[i]) v[i].push_back(j);
}
cin >> q;
while(q--) {
cin >> w;
int pos = upper_bound(ed, ed+m, make_pair(w, make_pair((int)1e9, (int)1e9))) - ed;
sort(v[pos].begin(), v[pos].end(), cmp);
for(int i=1; i<=n; i++) dsu[i] = i;
long long ans = 0;
for(int i:v[pos]) {
if(find(ed[i].second.first) != find(ed[i].second.second)) {
ans += abs(w-ed[i].first);
merge(ed[i].second.first, ed[i].second.second);
}
}
cout << ans << "\n";
}
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |