比如:我用c++实现了下面图片的功能:
现改用java实现需要做很大改动吗?若有有缘人用JAVA改写本程序,或做出解答感激不尽
c++源码:
#include <cstdio>
int father[10001];
bool mark[10001];
//找到根节点
int find(int x){
return x==father[x] ? x : father[x]=find(father[x]);
}
//检查两点是否连通。
void check(){
int a,b;
scanf("%d %d",&a,&b);
int x=find(a),y=find(b);
if(y==x) printf("yes\n");
else printf("no\n");
}
//连接两点。
void connect(){
int a,b;
scanf("%d %d",&a,&b);
int x=find(a),y=find(b);
//a,b两点的根节点已经相同,已经相连。
if(x==y) return;
//将x的根节点更新为y,向x,y两个集合左归并为x一个。
father[y]=x;
}
void judge(int n){
int cnt=0;
for(int i=1;i<=n;i++){
int f=find(i);
//两个根节点不同,并且另外一个根节点未标记,则连通集+1。
if(!mark[f]){
mark[f]=true;
cnt++;
}
}
if(cnt!=1){
printf("There are %d components.\n\n",cnt);
}else{
printf("The network is connected.\n\n");
}
}
//给定相应的字符作出相应的指令。
bool order(char c,int n){
if(c=='C'){
check();
}else if(c=='I'){
connect();
}else if(c=='S'){
judge(n);
return false;
}
return true;
}
int main(int argc, char** argv) {
int n;
//循环读取n,直到遇到EOF或者n==0退出。
while(~(scanf("%d",&n)) && n){
//重置数组记录
for(int i=1;i<=n;i++){
father[i]=i;
mark[i]=false;
}
char c;
//读取换行符。
scanf("%c",&c);
do{
scanf("%c",&c);
}while(order(c,n));
}
return 0;
}
在java里面变成了对象的引用,只要对象传值就可以返回的。