#include <bits/stdc++.h>
using namespace std;
using pii = pair<int,int>;
struct Edge { int u,v,w; };
struct DSU {
int n;
vector<int> p, sz;
DSU(int n=0){ init(n); }
void init(int n_){
n=n_;
p.resize(n+1);
sz.resize(n+1);
for(int i=1;i<=n;i++){ p[i]=i; sz[i]=1; }
}
int find(int x){
while (p[x]!=x){ p[x]=p[p[x]]; x=p[x]; }
return x;
}
bool unite(int a,int b){
a=find(a); b=find(b);
if (a==b) return false;
if (sz[a]<sz[b]) swap(a,b);
p[b]=a; sz[a]+=sz[b];
return true;
}
};
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
freopen("tinhcldd.inp","r",stdin);
freopen("tinhcldd.out","w",stdout);
int n; long long m; int q;
if (!(cin>>n>>m>>q)) return 0;
vector<Edge> E;
E.reserve((size_t)min<long long>(m, 5000000LL));
int u,v,w;
int maxW = -1;
for(long long i=0;i<m;i++){
cin>>u>>v>>w;
E.push_back({u,v,w});
if (w>maxW) maxW=w;
}
// sort edges by descending weight (maximum spanning)
sort(E.begin(), E.end(), [](const Edge &a, const Edge &b){
return a.w > b.w;
});
DSU dsu(n);
dsu.init(n);
// build maximum spanning forest (only n-1 edges needed)
vector<vector<pair<int,int>>> adj(n+1);
adj.assign(n+1, {});
adj.reserve(n+1);
int added = 0;
for(size_t i=0;i<E.size() && added < n-1; ++i){
if (dsu.unite(E[i].u, E[i].v)){
adj[E[i].u].push_back({E[i].v, E[i].w});
adj[E[i].v].push_back({E[i].u, E[i].w});
++added;
}
}
// BFS/DFS from node 1 to compute min-edge-on-path to 1
const int NEG = -1;
vector<int> ans(n+1, NEG);
if (n >= 1){
// If there are no edges, let's define ans[1] = maxW (if exists) else -1
if (maxW == -1) ans[1] = -1;
else ans[1] = maxW;
// iterative stack DFS
vector<int> st;
vector<int> parent(n+1, 0);
st.reserve(n);
st.push_back(1);
parent[1]=1;
// For node 1, ans[1] already set to maxW; for its neighbors compute min
while(!st.empty()){
int x = st.back(); st.pop_back();
for (auto &pr : adj[x]){
int y = pr.first;
int wt = pr.second;
if (parent[y]==0){ // unvisited
parent[y]=x;
if (x==1) ans[y] = wt;
else ans[y] = min(ans[x], wt);
st.push_back(y);
}
}
}
}
// answer queries
for(int i=0;i<q;i++){
int p; cin>>p;
cout << ans[p] << '\n';
}
return 0;
}
Compilation message (stderr)
sightseeing.cpp: In function 'int main()':
sightseeing.cpp:30:16: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
30 | freopen("tinhcldd.inp","r",stdin);
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~
sightseeing.cpp:31:16: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
31 | freopen("tinhcldd.out","w",stdout);
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~| # | 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... |