这是我的代码。我有 1 个错误。请帮我。
Try this input:
8
1 2 3 4 5 6 7 8
..................................................... …………………………………………………………………………………………………………………………………………
import java.io.*;
public class permutation
{
public static void main (String []args) throws IOException
{
BufferedReader dataIn = new BufferedReader(new InputStreamReader( System.in) );
String n="";
int parsen=0, parsenum=0;
System.out.println(n);
n = dataIn.readLine();
parsen=Integer.parseInt(n);
String num[]= new String [1000];
int visited[]=new int [1000];
int vindex[]=new int [2000];
int a=0;
for(int i=1;i<=parsen;i++){
num[i-1]=dataIn.readLine();
parsenum=Integer.parseInt(num[i-1]);
}
int t_visited=0, cycles=0, start=0, index=0;
while(t_visited<parsen)
{
for(int i=1; i<=parsen;i++)
{
if(visited[i]==0)
{
vindex[start]=i;
visited[i]=1;
t_visited++;
index=start;
break;
}
}
while(true)
{
index++;
vindex[index]=parsenum[vindex[index-1]];
if(vindex[index]==vindex[start])
break;
visited[vindex[index]]=1;
t_visited++;
vindex[++index]=0;
start=index+1;
cycles++;
}
System.out.println(cycles+vindex[0]);
for(int i=0;i<(parsen+2*cycles);i++)
{
if(vindex[i]==0)
{
System.out.println();
}else{
System.out.println(vindex[i]);
}
}
}
}
}
谢谢!
另一个代码:工作但输出错误。请帮助...我将 num 声明为整数。
import java.io.*;
public class permutation
{
public static void main (String []args) throws IOException
{
BufferedReader dataIn = new BufferedReader(new InputStreamReader( System.in) );
String n="";
int parsen=0;
System.out.println(n);
n = dataIn.readLine();
parsen=Integer.parseInt(n);
int num[]= new int [1000];
int visited[]=new int [1000];
int vindex[]=new int [2000];
int a=0;
for(int i=1;i<=parsen;i++){
num[i-1] = Integer.parseInt(System.console().readLine());
}
int t_visited=0, cycles=0, start=0, index=0;
while(t_visited<parsen)
{
for(int b=1; b<=parsen;b++)
{
if(visited[b]==0)
{
vindex[start]=b;
visited[b]=1;
t_visited++;
index=start;
break;
}
}
while(true)
{
index++;
vindex[index]=num[vindex[index-1]];
if(vindex[index]==vindex[start])
break;
visited[vindex[index]]=1;
t_visited++;
vindex[++index]=0;
start=index+1;
cycles++;
}
System.out.println(cycles+vindex[0]);
for(int c=0;c<(parsen+2*cycles);c++)
{
if(vindex[c]==0)
{
System.out.println();
}else{
System.out.print(vindex[c]);
}
}
}
}
}
输出必须是
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8