Leetcode-2959

Number of Possible Sets of Closing Branches

 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
#include <iostream>
#include <vector>
#include <algorithm>

const int INF = 0x3fff'ffff;

class Solution {
public:
    int numberOfSets(int n, int maxDistance, std::vector<std::vector<int>>& roads) {
        int res = 0, num = (1 << n);
        bool opened[1024] = { 0 };
        std::vector<std::vector<int>> dist(n, std::vector<int>(n, INF));
        
        for (int mask = 0; mask < num; ++mask) {
            for (int i = 0; i < n; ++i) {
                opened[i] = (mask & (1 << i)) == 0;
            }
            for (auto& ln : dist) {
                std::fill(ln.begin(), ln.end(), INF);
            }
            for (auto& e : roads) {
                if (opened[e[0]] && opened[e[1]]) {
                    dist[e[0]][e[1]] = std::min(dist[e[0]][e[1]], e[2]);
                    dist[e[1]][e[0]] = std::min(dist[e[1]][e[0]], e[2]);
                }
            }
            
            for (int k = 0; k < n; ++k) {
                if (!opened[k]) {
                    continue;
                }
                for (int i = 0; i < n; ++i) {
                    if (!opened[i]) {
                        continue;
                    }
                    for (int j = 0; j < n; ++j) {
                        if (!opened[i]) {
                            continue;
                        }
                        dist[i][j] = std::min(dist[i][j], dist[i][k] + dist[k][j]);
                    }
                }
            }
            
            ++res;
            for (int ij = 0; ij < n * n; ++ij) {
                if (!opened[ij / n] || !opened[ij % n]) {
                    continue;
                }
                if (ij / n == ij % n) {
                    continue;
                }
                if (dist[ij / n][ij % n] > maxDistance) {
                    --res;
                    std::cout << mask << " " << ij << std::endl;
                    break;
                }
            }
        }
        return res;
    }
};

Leetcode-2959