#include <bits/stdc++.h>
using namespace std;
int n, m;
map<string, int> nn;
vector<int> g[5000];
int dst[5000][5000];
int dist(int st, int fi) {
int dist[5000] = {};
set<pair<int, int>> s;
for (int i = 1; i <= n; i++) {
dist[i] = (i == st ? 0 : 2000000000);
}
s.insert(make_pair(dist[st], st));
while (!s.empty()) {
int v = (*s.begin()).second;
s.erase(s.begin());
for (int u : g[v]) {
int len = dst[v][u];
if (dist[v] + len < dist[u]) {
s.erase(make_pair(dist[u], u));
dist[u] = dist[v] + len;
s.insert(make_pair(dist[u], u));
}
}
}
return dist[fi] == 2000000000 ? -1 : dist[fi];
}
int main() {
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
dst[i][j] = 2000000000;
}
}
int ii = 0;
for (int i = 0; i < m; i++) {
string u, v;
cin >> u >> v;
int t;
cin >> t;
if (nn[u] == 0) {
nn[u] = ++ii;
}
if (nn[v] == 0) {
nn[v] = ++ii;
}
g[nn[u]].push_back(nn[v]);
dst[nn[u]][nn[v]] = min(dst[nn[u]][nn[v]], t);
}
int qq;
cin >> qq;
while (qq--) {
string a, b;
cin >> a >> b;
if (nn[a] == 0) {
nn[a] = ++ii;
}
if (nn[b] == 0) {
nn[b] = ++ii;
}
int r = dist(nn[a], nn[b]);
if (r == -1) {
cout << "Roger" << '\n';
}
else {
cout << r << '\n';
}
}
return 0;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
572 KB |
Output is correct |
2 |
Correct |
1 ms |
460 KB |
Output is correct |
3 |
Correct |
25 ms |
844 KB |
Output is correct |
4 |
Correct |
53 ms |
1352 KB |
Output is correct |
5 |
Correct |
14 ms |
7628 KB |
Output is correct |
6 |
Correct |
12 ms |
7700 KB |
Output is correct |
7 |
Correct |
11 ms |
8672 KB |
Output is correct |