-
Notifications
You must be signed in to change notification settings - Fork 0
/
City With the Smallest Number of Neighbors at a Threshold Distance.cpp
92 lines (74 loc) · 2.19 KB
/
City With the Smallest Number of Neighbors at a Threshold Distance.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
//{ Driver Code Starts
// Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
class Solution {
public:
int dijkstra(int curr, int& n, int& distThreshold, vector<vector<pair<int, int>>>& graph) {
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
vector<int> vis(n, 0);
pq.push({0, curr});
int cnt = 0;
while (!pq.empty()) {
int dist = pq.top().first;
int node = pq.top().second;
pq.pop();
if (vis[node])
continue;
vis[node] = 1;
if (dist > distThreshold)
continue;
++cnt;
for (auto itr : graph[node]) {
int nodeDist = itr.first;
int nextNode = itr.second;
if (!vis[nextNode])
pq.push({dist + nodeDist, nextNode});
}
}
return cnt;
}
int findCity(int n, int m, vector<vector<int>>& edges, int distThreshold) {
vector<vector<pair<int, int>>> graph(n);
for (auto &itr : edges) {
graph[itr[0]].push_back({itr[2], itr[1]});
graph[itr[1]].push_back({itr[2], itr[0]});
}
int out = -1, nax = INT_MAX;
for (int i = 0; i < n; ++i) {
int cnt = dijkstra(i, n, distThreshold, graph);
if (cnt <= nax) {
nax = cnt;
out = i;
}
}
return out;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
int n, m;
cin >> n >> m;
vector<vector<int>> adj;
// n--;
for (int i = 0; i < m; ++i) {
vector<int> temp;
for (int j = 0; j < 3; ++j) {
int x;
cin >> x;
temp.push_back(x);
}
adj.push_back(temp);
}
int dist;
cin >> dist;
Solution obj;
cout << obj.findCity(n, m, adj, dist) << "\n";
}
}
// } Driver Code Ends