Skip to content

Commit 6d925c4

Browse files
committed
floyed algo added.
1 parent 95e5de2 commit 6d925c4

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed

1334-Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance/cpp-1334/CMakeLists.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,4 @@ project(cpp_1334)
33

44
set(CMAKE_CXX_STANDARD 14)
55

6-
add_executable(cpp_1334 main.cpp)
6+
add_executable(cpp_1334 main2.cpp)
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/// Source : https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/
2+
/// Author : liuyubobobo
3+
/// Time : 2020-03-06
4+
5+
#include <iostream>
6+
#include <vector>
7+
#include <map>
8+
#include <queue>
9+
10+
using namespace std;
11+
12+
13+
/// Floyed
14+
/// Time Complexity: O(V^3)
15+
/// Space Complexity: O(V^2)
16+
class Solution {
17+
public:
18+
int findTheCity(int n, vector<vector<int>>& edges, int distanceThreshold) {
19+
20+
vector<vector<int>> dis(n, vector<int>(n, INT_MAX));
21+
for(const vector<int>& e: edges)
22+
dis[e[0]][e[1]] = dis[e[1]][e[0]] = e[2];
23+
24+
for(int i = 0; i < n; i ++) dis[i][i] = 0;
25+
for(int t = 0; t < n; t ++)
26+
for(int v = 0; v < n; v ++)
27+
for(int w = 0; w < n; w ++)
28+
if(dis[v][t] != INT_MAX && dis[t][w] != INT_MAX)
29+
dis[v][w] = min(dis[v][w], dis[v][t] + dis[t][w]);
30+
31+
int minNum = INT_MAX, res = -1;
32+
for(int i = 0; i < n; i ++){
33+
int num = 0;
34+
for(int v = 0; v < n; v ++)
35+
if(v != i) num += (dis[i][v] <= distanceThreshold);
36+
if(num <= minNum) minNum = num, res = i;
37+
}
38+
return res;
39+
}
40+
};
41+
42+
43+
int main() {
44+
45+
vector<vector<int>> edges = {
46+
{0,1,2},{0,4,8},{1,2,3},{1,4,2},{2,3,1},{3,4,1}
47+
};
48+
cout << Solution().findTheCity(5, edges, 2) << endl;
49+
// 0
50+
51+
return 0;
52+
}

0 commit comments

Comments
 (0)