求全源最短路,对于每个城市,求所有到它的距离小于distanceThreshold的城市,所有城市取最小值即可。
1、Floyd
class Solution {
public:
int findTheCity(int n, vector<vector<int>>& edges, int distanceThreshold) {
int g[n][n];
memset(g,0x3f,sizeof g);
for(auto p:edges) g[p[0]][p[1]]=g[p[1]][p[0]]=p[2];
for(int k=0;k<n;k++){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
g[i][j]=min(g[i][j],g[i][k]+g[k][j]);
}
}
}
int mx=n,ans;
for(int i=0;i<n;i++){
int c=0;
for(int j=0;j<n;j++){
if(i!=j&&g[i][j]<=distanceThreshold) c++;
}
if(c<=mx){
mx=c;
ans=i;
}
}
return ans;
}
};
2、Dijkstra
class Solution {
public:
int findTheCity(int n, vector<vector<int>>& edges, int distanceThreshold) {
int g[n][n];
memset(g,-1,sizeof g);
for(auto p:edges) g[p[0]][p[1]]=g[p[1]][p[0]]=p[2];
auto sum=[&](int x){
int vis[n];
int d[n];
memset(vis,0,sizeof vis);
memset(d,0x3f,sizeof d);
priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> q;
q.push({0,x});
while(!q.empty()){
auto [dst,y]=q.top();
q.pop();
if(vis[y]) continue;
vis[y]=1;
for(int i=0;i<n;i++){
if(!vis[i]&&g[y][i]!=-1&&dst+g[y][i]<d[i]){
d[i]=dst+g[y][i];
q.push({d[i],i});
}
}
}
int res=0;
for(int i=0;i<n;i++){
if(d[i]<=distanceThreshold){
res++;
}
}
return res;
};
int mx=n,ans;
for(int i=0;i<n;i++){
int t=sum(i);
if(t<=mx){
mx=t;
ans=i;
}
}
return ans;
}
};