| ||||||||||
| Online Judge | Problem Set | Authors | Online Contests | User | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest | |||||||||
Mark一下,将数组组成的所有“环”中的元素个数-1得到的值累加即是交换的最小步骤import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException,
IllegalAccessException {
Main engine = new Main();
engine.init();
while (engine.load()) {
engine.doWork();
}
}
private void doWork() {
System.out.println(getMovement());
}
private void init() throws FileNotFoundException {
s = new Scanner(System.in);
// s = new Scanner(new FileInputStream("input.txt"));
cases = s.nextInt();
}
private boolean load() {
if (cases == 0) return false;
int length = s.nextInt();
permutation = new int[length];
for (int i=0; i<length; i++)
permutation[i] = s.nextInt() - 1;
cases--;
return true;
}
private int getMovement() {
int total = 0;
boolean[] visited = new boolean[permutation.length];
for (int i=0; i<permutation.length; i++) {
if (visited[i]) continue;
visited[i] = true;
int cnt = 0;
int j = permutation[i];
while (j != i) {
visited[j] = true;
j = permutation[j];
cnt++;
}
total += cnt;
}
return total;
}
private Scanner s;
private int cases;
private int[] permutation;
}
Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator