イーサネットケーブルを使用してn台のコンピューターをネットワークに接続します。コンピューター番号は0からn-1です。ケーブルは接続で表されます。ここで、connections [i] = [a、b]はコンピューターaとbを接続します。
ネットワーク内の任意のコンピューターは、ネットワークを介して同じネットワーク内の他のコンピューターに直接または間接的にアクセスできます。
このコンピュータネットワークの最初の配線接続を提供するために、直接接続されている2台のコンピュータ間のケーブルを抜き、それを使用して、直接接続されていないコンピュータのペアを接続できます。すべてのコンピューターを接続するために必要な最小操作数を計算して返します。それが不可能な場合は、-1が返されます。
例1:
入力:n = 4、接続= [[0,1]、[0,2]、[1,2]]
出力:1
説明:コンピューター1と2の間のケーブルを抜き、コンピューター1と3に差し込みます。オン。
例2:
入力:n = 6、接続= [[0,1]、[0,2]、[0,3]、[1,2]、[1,3]]
出力:2
例3:
入力:n = 6、接続= [[0,1]、[0,2]、[0,3]、[1,2]]
出力:-1
説明:ケーブルの数が不足しています。
例4:
入力:n = 5、接続= [[0,1]、[0,2]、[3,4]、[2,3]]
出力:0
促す:
1 <= n <= 10 ^ 5
1 <=接続
.length <= min(n *(n-1)/ 2、10 ^ 5)接続[i] .length == 2
0 <=接続[i] [ 0]、connections [i] [1] <nconnections
[i] [0]!= connections [i] [1]
重複する接続はありません。
2台のコンピューターを複数のケーブルで接続することはありません。
出典:LeetCode
リンク:https ://leetcode-cn.com/problems/number-of-operations-to-make-network-connected
著作権はLeetCodeが所有しています。商用の再版については、公式の承認に連絡してください。非商用の再版については、出典を示してください。
アイデア:この質問セットテンプレートで十分です。自分で書いたのですが、本当に解決策がわかりませんでした。彼のサイズ配列が利用できないようです。
class Solution {
public int makeConnected(int n, int[][] connections) {
if (connections.length < n - 1) {
return -1;
}
UnionFind uf = new UnionFind(n);
for (int[] conn : connections) {
uf.union(conn[0], conn[1]);
}
return uf.Count - 1;
}
}
// 并查集模板
class UnionFind {
int[] parent;
//int[] size;
int n;
// 当前连通分量数目
int Count;
public UnionFind(int n) {
this.n = n;
this.Count = n;
this.parent = new int[n];
//this.size = new int[n];
//Arrays.fill(size, 1);
for (int i = 0; i < n; ++i) {
parent[i] = i;
}
}
public int find(int x) {
if(parent[x]!=x)
{
parent[x] = find(parent[x]);
}
return parent[x];
}
public boolean union(int x, int y) {
x = find(x);
y = find(y);
if (x == y) {
return false;
}
//if (size[x] < size[y]) {
// int temp = x;
// x = y;
// y = temp;
//}
parent[x] = y;
//size[x] += size[y];
--Count;
return true;
}
public boolean connected(int x, int y) {
x = find(x);
y = find(y);
return x == y;
}
}