../ Competitive Programming
-rw-r--r--aguang1.5 KiB1 min read

Leet Code Daily 2024-07-26 - Find the City with the Smallest Number of Neighbors at a Threshold Distance

Solution

Floyd-Warshall Algorithm.

Code

c++
constexpr int kFarAway = 1000000;

class Solution {
public:
    int findTheCity(int n, vector<vector<int>>& edges, int distanceThreshold) {

        auto distance = vector<vector<int>>(n, vector<int>(n, kFarAway));
        for (int i = 0; i < n; i++) {
            distance[i][i] = 0;
        }
        for (const auto& edge : edges) {
            distance[edge[0]][edge[1]] =
                min(distance[edge[0]][edge[1]], edge[2]);
            distance[edge[1]][edge[0]] =
                min(distance[edge[1]][edge[0]], edge[2]);
        }

        for (int k = 0; k < n; k++) {
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    distance[i][j] =
                        min(distance[i][j], distance[i][k] + distance[k][j]);
                }
            }
        }

        auto count = vector<int>(n, 0);
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (distance[i][j] <= distanceThreshold) {
                    count[i]++;
                }
            }
        }

        int ret = 0;
        for (int i = 1; i < n; i++) {
            if (count[i] <= count[ret]) {
                ret = i;
            }
        }
        return ret;
    }
};

COMMAND INTERFACE

↑ ↓ navigate · Enter execute · Esc exit · try “whoami”

Loading filesystem…

:help aguang.xyz

A personal website disguised as an operating system.

Ctrl / Cmd + K
Command palette + full-text search
Tab / Shift + Tab
Move between links and controls
Enter
Open a focused link or search result
↑ / ↓ in search
Navigate search results
In a directory filter
Enter/Done or ↓ focuses a result; Esc clears the filter
Esc
Clear a search or close a window