Approach
Direct simulation
For Find the City With the Smallest Number of Neighbors at a Threshold Distance, the implementation follows the problem’s operations directly while maintaining only the state needed for the next decision.
- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 46 lines of C++ from the credited upstream file 1334.cpp.
- The implementation visibly relies on sequence storage.
- 7 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int findTheCity(int n, vector<vector<int>>& edges, int distanceThreshold) {4 int ans = -1;5 int minCitiesCount = n;6 const vector<vector<int>> dist = floydWarshall(n, edges, distanceThreshold);7 8 for (int i = 0; i < n; ++i) {9 int citiesCount = 0;10 for (int j = 0; j < n; ++j)11 if (dist[i][j] <= distanceThreshold)12 ++citiesCount;13 if (citiesCount <= minCitiesCount) {14 ans = i;15 minCitiesCount = citiesCount;16 }17 }18 19 return ans;20 }21 22 private:23 vector<vector<int>> floydWarshall(int n, const vector<vector<int>>& edges,24 int distanceThreshold) {25 vector<vector<int>> dist(n, vector<int>(n, distanceThreshold + 1));26 27 for (int i = 0; i < n; ++i)28 dist[i][i] = 0;29 30 for (const vector<int>& edge : edges) {31 const int u = edge[0];32 const int v = edge[1];33 const int w = edge[2];34 dist[u][v] = w;35 dist[v][u] = w;36 }37 38 for (int k = 0; k < n; ++k)39 for (int i = 0; i < n; ++i)40 for (int j = 0; j < n; ++j)41 dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);42 43 return dist;44 }45};46