-
Notifications
You must be signed in to change notification settings - Fork 0
/
floydwarshall.cpp
110 lines (109 loc) · 2.62 KB
/
floydwarshall.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
108
109
110
#include <iostream>
#include <cmath>
#include <stack>
#include <cstring>
#include <stdlib.h>
#include <unordered_set>
#include <vector>
#include <map>
#include <set>
#include <unordered_map>
#include <algorithm>
#include <queue>
using namespace std;
#define vi vector<int>
#define vvi vector<vi>
#define pii vector<int, int>
#define vii vector<pii>
#define rep(i, a, b) for (int i = a; i < b; i++)
#define ff first
#define ss second
/*multi source shortest path
can detect negative cycles*/
/*given adjacency matrix of a graph update min distance from
each node to other for in place*/
void shortest_distance(vector<vector<int>> &matrix)
{
int n = matrix.size();
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (matrix[i][j] == -1)
matrix[i][j] = 1e9;
if (i == j)
matrix[i][j] = 0;
}
}
for (int k = 0; k < n; k++)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
matrix[i][j] = min(matrix[i][j],
matrix[i][k] + matrix[k][j]);
}
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (matrix[i][j] == 1e9)
matrix[i][j] = -1;
}
}
}
/*
City With the Smallest Number of Neighbors at a Threshold Distance
*/
int findCity(int n, int m, vector<vector<int>> &edges, int distanceThreshold)
{
vector<vector<int>> dist(n, vector<int>(n, INT_MAX));
for (auto it : edges)
{
dist[it[0]][it[1]] = it[2];
dist[it[1]][it[0]] = it[2];
}
for (int i = 0; i < n; i++)
{
dist[i][i] = 0;
}
for (int k = 0; k < n; k++)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (dist[i][k] == INT_MAX || dist[k][j] == INT_MAX)
{
continue;
}
else
{
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);
}
}
}
}
int countcity = n;
int city = -1;
for (int i = 0; i < n; i++)
{
int cnt = 0;
for (int j = 0; j < n; j++)
{
if (dist[i][j] <= distanceThreshold)
{
cnt++;
}
}
if (cnt <= countcity)
{
countcity = cnt;
city = i;
}
}
return city;
}