classSolution: defnumberOfSets(self, n: int, maxDistance: int, roads: List[List[int]]) -> int: # Build graph g = [[float('inf')] * n for _ inrange(n)] for i inrange(n): g[i][i] = 0 for u, v, w in roads: g[u][v] = min(g[u][v], w) g[v][u] = min(g[v][u], w) ans = 0 for mask inrange(1 << n): # 狀態壓縮 g2 = [[] for _ inrange(n)] # subgraph for i inrange(n): if mask >> i & 1: g2[i] = g[i][:] # copy # Floyd-Warshall for k inrange(n): if mask >> k & 1 == 0: continue for i inrange(n): if mask >> i & 1 == 0: continue for j inrange(n): if g2[i][k] + g2[k][j] < g2[i][j]: g2[i][j] = g2[i][k] + g2[k][j] # Check flag = True for i inrange(n): if mask >> i & 1 == 0: continue for j inrange(n): if mask >> j & 1 == 0: continue if g2[i][j] > maxDistance: flag = False break ifnot flag: break ans += flag return ans
classSolution { public: intnumberOfSets(int n, int maxDistance, vector<vector<int>>& roads){ // Build graph vector<vector<int>> g(n, vector<int>(n, INT_MAX / 2)); for (int i = 0; i < n; i++) g[i][i] = 0; for (auto& r : roads) { g[r[0]][r[1]] = min(g[r[0]][r[1]], r[2]); g[r[1]][r[0]] = min(g[r[1]][r[0]], r[2]); } int ans = 0; for (int mask = 0; mask < (1 << n); mask++) { // Subgraph vector<vector<int>> g2(n); for (int i = 0; i < n; i++) { if (mask >> i & 1) g2[i] = g[i]; } // Floyd Warshall for (int k = 0; k < n; k++) { if (!(mask >> k & 1)) continue; for (int i = 0; i < n; i++) { if (!(mask >> i & 1)) continue; for (int j = 0; j < n; j++) { if (g2[i][k] + g2[k][j] < g2[i][j]) { g2[i][j] = g2[i][k] + g2[k][j]; } } } } // Check bool flag = true; for (int i = 0; i < n && flag; i++) { if (!(mask >> i & 1)) continue; for (int j = 0; j < n && flag; j++) { if (!(mask >> j & 1)) continue; if (g2[i][j] > maxDistance) flag = false; } } ans += flag; } return ans; } };
寫在最後
masterpiece, best quality, high quality, extremely detailed CG unity 8k wallpaper, extremely detailed, High Detail,
1 girl, solo, long hair, black hair, blue eyes, skirt, shirt, school uniform, standing, white shirt, short sleeves, pleated skirt, outdoors, sky, serafuku, (pink serafuku, pink school uniform), day, sailor collar, blurry, arm up, neckerchief, long skirt, girl