#include <bits/stdc++.h>
using namespace std;
const long long N = 1000 + 5, INF = 2e18 + 5;
struct Edge{
string stra, strb;
long long w;
};
Edge edges[N];
vector<pair<int, long long>> graph[N];
map<string, int> cmprss;
pair<int, int> query[N];
string str;
int n, m, q;
long long dist[N];
bool vis[N];
void compress(){
for(int i = 0; i < m; i++) cmprss[edges[i].stra] = -1, cmprss[edges[i].strb] = -1;
int cur = 1;
for(auto &p : cmprss) p.second = cur++;
for(int i = 0; i < m; i++) graph[cmprss[edges[i].stra]].push_back({cmprss[edges[i].strb], edges[i].w});
}
void dijkstra(int x){
memset(vis, 0, sizeof(vis));
for(int i = 1; i <= n; i++) dist[i] = INF;
dist[x] = 0;
priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> pq;
pq.push({0, x});
while(!pq.empty()){
int v = pq.top().second; pq.pop();
if(!vis[v]){
vis[v] = true;
for(auto e : graph[v]){
if(dist[v] + e.second < dist[e.first]){
dist[e.first] = dist[v] + e.second;
pq.push({dist[e.first], e.first});
}
}
}
}
}
int main(){
ios_base::sync_with_stdio(false);cin.tie(NULL);
cin >> n >> m;
for(int i = 0; i < m; i++) cin >> edges[i].stra >> edges[i].strb >> edges[i].w;
compress();
cin >> q;
for(int i = 0; i < q; i++){
cin >> str;
query[i].first = cmprss[str];
cin >> str;
query[i].second = cmprss[str];
}
for(int i = 0; i < q; i++){
dijkstra(query[i].first);
if(dist[query[i].second] == INF) cout << "Roger\n";
else cout << dist[query[i].second] << "\n";
}
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
332 KB |
Output is correct |
2 |
Correct |
1 ms |
332 KB |
Output is correct |
3 |
Correct |
15 ms |
588 KB |
Output is correct |
4 |
Correct |
19 ms |
612 KB |
Output is correct |
5 |
Correct |
3 ms |
672 KB |
Output is correct |
6 |
Correct |
3 ms |
588 KB |
Output is correct |
7 |
Correct |
3 ms |
588 KB |
Output is correct |