while True: n,m=map(int,input().split()) a=[0 for i in range(n+1)] count=1 for i in range(m): j,k=map(int,input().split()) if a[j]==0 and a[k]==0: a[j]=count a[k]=count count+=1 elif a[j]!=0 and a[k]==0: a[k]=a[j] elif a[k]!=0 and a[j]==0: a[j]=a[k] elif a[j]!=a[k] and a[j]!=0 and a[k]!=0: if a[j]<a[k]: for p in range(1,n+1): if a[p]==a[k]: a[p]=a[j] else: for p in range(1,n+1): if a[p]==a[j]: a[p]=a[k] r=0 flag=0 for i in range(1,n+1): if a[i]==0: r+=1 for i in range(1,count): flag=0 for j in range(1,n+1): if a[j]==i: flag=1 break if flag==1: r+=1 print(r)转Java
时间: 2024-02-04 20:04:08 浏览: 158
你好,以下是将Python代码转换成Java代码的结果:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
int n = scanner.nextInt();
int m = scanner.nextInt();
int[] a = new int[n + 1];
int count = 1;
for (int i = 0; i < m; i++) {
int j = scanner.nextInt();
int k = scanner.nextInt();
if (a[j] == 0 && a[k] == 0) {
a[j] = count;
a[k] = count;
count++;
} else if (a[j] != 0 && a[k] == 0) {
a[k] = a[j];
} else if (a[k] != 0 && a[j] == 0) {
a[j] = a[k];
} else if (a[j] != a[k] && a[j] != 0 && a[k] != 0) {
if (a[j] < a[k]) {
for (int p = 1; p <= n; p++) {
if (a[p] == a[k]) {
a[p] = a[j];
}
}
} else {
for (int p = 1; p <= n; p++) {
if (a[p] == a[j]) {
a[p] = a[k];
}
}
}
}
}
int r = 0;
int flag = 0;
for (int i = 1; i <= n; i++) {
if (a[i] == 0) {
r++;
}
}
for (int i = 1; i < count; i++) {
flag = 0;
for (int j = 1; j <= n; j++) {
if (a[j] == i) {
flag = 1;
break;
}
}
if (flag == 1) {
r++;
}
}
System.out.println(r);
}
}
}
```
请注意,Java 代码中的输入方式是使用 `Scanner` 类实现的,如果您的 Python 代码中使用了其他输入方式,需要根据实际情况进行修改。同时,Java 代码中的数组下标从 0 开始,而 Python 代码中的数组下标从 1 开始,需要注意将数组下标进行适当的调整。
阅读全文