이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
using namespace std;
#define fi first
#define se second
typedef long long ll;
typedef pair<int,int> pii;
const int maxn=1e5+5;
const int inf=1e9;
int n,m,k,q,x,y,z,w,a[maxn];
vector<pair<int,int>> adj[maxn];
int dist[maxn];
int parent[maxn],id[maxn],sz[maxn];
set<int> s[maxn];
int ans[maxn];
bool mark[maxn];
void dijkstra()
{
fill(dist+1,dist+n+1,inf);
priority_queue<pii,vector<pii>,greater<pii>> pq;
for (int i=1;i<=k;i++)
{
dist[a[i]]=0;
pq.push({0,a[i]});
}
while (!pq.empty())
{
int u=pq.top().se;
int t=pq.top().fi;
pq.pop();
if (t>dist[u]) continue;
for (auto e:adj[u])
{
int v=e.fi;
int w=e.se;
if (dist[v]>dist[u]+w)
{
dist[v]=dist[u]+w;
pq.push({dist[v],v});
}
}
}
}
int find_set(int u)
{
if (u==parent[u]) return u;
return parent[u]=find_set(parent[u]);
}
void union_set(int u,int v)
{
u=find_set(u);
v=find_set(v);
if (u==v) return;
parent[v]=u;
for (int x:s[v])
{
if (s[u].find(x)!=s[u].end())
{
s[u].erase(x);
ans[x]=w;
}
else s[u].insert(x);
}
}
bool cmp(int a,int b)
{
return dist[a]>dist[b];
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);cout.tie(0);
cin>>n>>m;
while (m--)
{
cin>>x>>y>>z;
adj[x].push_back({y,z});
adj[y].push_back({x,z});
}
cin>>k;
for (int i=1;i<=k;i++)
{
cin>>a[i];
}
dijkstra();
cin>>q;
for (int i=1;i<=q;i++)
{
cin>>x>>y;
s[x].insert(i);
s[y].insert(i);
}
for (int i=1;i<=n;i++)
{
id[i]=i;
parent[i]=i;
}
sort(id+1,id+n+1,cmp);
memset(mark,0,sizeof(mark));
for (int i=1;i<=n;i++)
{
x=id[i];
mark[x]=true;
w=dist[x];
for (auto it:adj[x])
{
y=it.fi;
if (mark[y]) union_set(x,y);
}
}
for (int i=1;i<=q;i++) cout<<ans[i]<<'\n';
return 0;
}
# | 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... |