-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1334.阈值距离内邻居最少的城市.cpp
108 lines (107 loc) · 3.18 KB
/
1334.阈值距离内邻居最少的城市.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/*
* @lc app=leetcode.cn id=1334 lang=cpp
*
* [1334] 阈值距离内邻居最少的城市
*
* https://leetcode.cn/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/description/
*
* algorithms
* Medium (53.18%)
* Likes: 171
* Dislikes: 0
* Total Accepted: 24.4K
* Total Submissions: 40.5K
* Testcase Example: '4\n[[0,1,3],[1,2,1],[1,3,4],[2,3,1]]\n4'
*
* 有 n 个城市,按从 0 到 n-1 编号。给你一个边数组 edges,其中 edges[i] = [fromi, toi, weighti] 代表
* fromi 和 toi 两个城市之间的双向加权边,距离阈值是一个整数 distanceThreshold。
*
* 返回能通过某些路径到达其他城市数目最少、且路径距离 最大 为 distanceThreshold 的城市。如果有多个这样的城市,则返回编号最大的城市。
*
* 注意,连接城市 i 和 j 的路径的距离等于沿该路径的所有边的权重之和。
*
*
*
* 示例 1:
*
*
*
*
* 输入:n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4
* 输出:3
* 解释:城市分布图如上。
* 每个城市阈值距离 distanceThreshold = 4 内的邻居城市分别是:
* 城市 0 -> [城市 1, 城市 2]
* 城市 1 -> [城市 0, 城市 2, 城市 3]
* 城市 2 -> [城市 0, 城市 1, 城市 3]
* 城市 3 -> [城市 1, 城市 2]
* 城市 0 和 3 在阈值距离 4 以内都有 2 个邻居城市,但是我们必须返回城市 3,因为它的编号最大。
*
*
* 示例 2:
*
*
*
*
* 输入:n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]],
* distanceThreshold = 2
* 输出:0
* 解释:城市分布图如上。
* 每个城市阈值距离 distanceThreshold = 2 内的邻居城市分别是:
* 城市 0 -> [城市 1]
* 城市 1 -> [城市 0, 城市 4]
* 城市 2 -> [城市 3, 城市 4]
* 城市 3 -> [城市 2, 城市 4]
* 城市 4 -> [城市 1, 城市 2, 城市 3]
* 城市 0 在阈值距离 2 以内只有 1 个邻居城市。
*
*
*
*
* 提示:
*
*
* 2
* 1
* edges[i].length == 3
* 0 i < toi < n
* 1 i, distanceThreshold
* 所有 (fromi, toi) 都是不同的。
*
*
*/
#include <bits/stdc++.h>
using namespace std;
// @lc code=start
class Solution {
public:
int findTheCity(int n, vector<vector<int>>& edges, int distanceThreshold) {
pair<int, int> ans(INT_MAX / 2, -1);
vector<vector<int>> mp(n, vector<int>(n, INT_MAX / 2));
for (auto &eg: edges) {
int from = eg[0], to = eg[1], weight = eg[2];
mp[from][to] = mp[to][from] = weight;
}
for (int k = 0; k < n; ++k) {
mp[k][k] = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
mp[i][j] = min(mp[i][j], mp[i][k] + mp[k][j]);
}
}
}
for (int i = 0; i < n; ++i) {
int cnt = 0;
for (int j = 0; j < n; ++j) {
if (mp[i][j] <= distanceThreshold) {
cnt++;
}
}
if (cnt <= ans.first) {
ans = {cnt, i};
}
}
return ans.second;
}
};
// @lc code=end