Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

Mark一下,将数组组成的所有“环”中的元素个数-1得到的值累加即是交换的最小步骤

Posted by lethorld at 2012-04-21 09:39:34 on Problem 1674
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:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator