1067. Sort with Swap(0,*) (25)
时间限制150 ms
内存限制65536 kB
代码长度限制16000 B
判题程序Standard作者CHEN, Yue
Given any permutation of the numbers {0, 1, 2,..., N-1}, it is easy to sort them in increasing order. But what if Swap(0, *) is the ONLY operation that is allowed to use? For example, to sort {4, 0, 2, 1, 3} we may apply the swap operations in the following way:
Swap(0, 1) => {4, 1, 2, 0, 3}
Swap(0, 3) => {4, 1, 2, 3, 0}
Swap(0, 4) => {0, 1, 2, 3, 4}Now you are asked to find the minimum number of swaps need to sort the given permutation of the first N nonnegative integers.
Input Specification:
Each input file contains one test case, which gives a positive N (<=105) followed by a permutation sequence of {0, 1, ..., N-1}. All the numbers in a line are separated by a space.
Output Specification:
For each case, simply print in a line the minimum number of swaps need to sort the given permutation.
Sample Input:10 3 5 7 2 6 4 9 0 8 1Sample Output:9N个数 接着是当前【数】放在序号i=0~N-1;
问通过0来交换,最少多少次;
通过存放的编号和存放的数为下一个编号,最终可以弄成一个环,而利用0来交换的最小次数为。当0在这个交换的环中,那么只要环的长度-1;如果不在则长度+1
例子;
存放的器0-3-2-7
存放的数3-2-7-0此时这个环为0-3-2-7-0~ 有0;通过从右边起,0-7交换,7-2交换……交换最短 环长度-1=4;
存放的器1-5-4-6-9
存放的数5-4-6-9-1此时这个环为1-5-4-6-9-1~ 有无;通过从右边起先把0-1换,接着0-9交换,0-6交换……最后再0-1交换回来,交换最短 环长度+1=5;
评测结果
时间 | 结果 | 得分 | 题目 | 语言 | 用时(ms) | 内存(kB) | 用户 |
---|---|---|---|---|---|---|---|
8月14日 00:03 | 答案正确 | 25 | 1067 | C++ (g++ 4.7.2) | 32 | 820 | datrilla |
测试点
测试点 | 结果 | 用时(ms) | 内存(kB) | 得分/满分 |
---|---|---|---|---|
0 | 答案正确 | 1 | 184 | 15/15 |
1 | 答案正确 | 32 | 820 | 3/3 |
2 | 答案正确 | 15 | 564 | 3/3 |
3 | 答案正确 | 1 | 360 | 2/2 |
4 | 答案正确 | 1 | 308 | 1/1 |
5 | 答案正确 | 1 | 308 | 1/1 |
#include <iostream> #include<vector> using namespace std; int main() { int N,index,sum,min,temp,now; bool Flag; cin >> N; vector<int>swapsort(N); for (index = 0; index < N; index++) { cin >> swapsort[index]; } sum = 0; for (index = 0; index < N; index++) { if (swapsort[index] != index) { now = index; Flag = false; min = 0; while (swapsort[now] != now) { if (now == 0)Flag = true; temp = swapsort[now]; swapsort[now] = now; now= temp; min++; } if (Flag)min--; else min++; sum += min; } } cout << sum << endl; system("pause"); return 0; }