CSES - Shared codeLink to this code:
https://cses.fi/paste/e7410f352b317deb8159d1/
#include <bits/stdc++.h>
using namespace std;
long long n,m,q;
const long long INF = 2000000000000000000LL;
const long long maxN = 550;
vector<long long> D[maxN];
vector<long long> W[maxN];
void floyd_warshall(int n)
{
for(int i=1;i<=n;i++) D[i] = W[i];
for(int k=1;k<=n;k++)
{
for(int u=1;u<=n;u++)
{
for(int v=1;v<=n;v++)
{
if (D[u][v]>D[u][k]+D[k][v]) D[u][v] = D[u][k] + D[k][v];
}
}
}
}
int main()
{
ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
cin >> n >> m >> q;
for(int i=1;i<=n;i++)
{
D[i].resize(n+1,INF);
W[i].resize(n+1,INF);
}
int l,r,w;
for(int i=1;i<=m;i++)
{
cin >> l >> r >> w;
if (W[l][r] > w) W[l][r] = W[r][l] = w;
}
floyd_warshall(n);
int u,v;
for(int i=1;i<=q;i++)
{
cin >> u >> v;
long long res;
if (u==v) res = 0;
else res = D[u][v]!=INF ? D[u][v]:-1;
cout << res << '\n';
}
}