DS Homework 7-1 Sort with Swap(0, i)
2017-12-23 14:01
106 查看
Problem:
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.
Analysis:
According to the mean of the question, the only operation we can use is Swap(0, *), however we must use T(N) to find where the 0 is, so the sort program may use T(N^2), which is unacceptable.In my program, I use
while (A[0] != 0)to make A[0]=0, then find the first number which is not in right place to change with A[0]. Besides I use a static variable i in function FindNot to save much time.
Code:
#include <stdio.h> #include <stdlib.h> int FindNot(int* A, int N); int main(void) { //freopen("test.txt", "r", stdin); int N, Temp, i, count = 0; scanf("%d", &N); int A ; for (i = 0; i < N; i++) scanf("%d", &A[i]); while (1) { while (A[0] != 0) { Temp = A[0]; A[0] = A[Temp]; A[Temp] = Temp; count++; } Temp = FindNot(A, N); if (Temp == 0) break; A[0] = A[Temp]; A[Temp] = 0; count++; } printf("%d\n", count); return 0; } int FindNot(int* A, int N) { int i; for (i = 1; i < N; i++) if (A[i] != i) return i; return 0; }
相关文章推荐
- PAT-A 1067. Sort with Swap(0,*) (25)
- 5-16 Sort with Swap(0, i)
- 08-排序5. Sort with Swap(0,*) (25)
- PAT_1067. Sort with Swap(0,*)
- 1067. Sort with Swap(0,*) (25)
- 1067. Sort with Swap(0,*) (25) PAT甲级
- 1067. Sort with Swap(0,*) (25)【贪心】——PAT (Advanced Level) Practise
- PAT A1067. Sort with Swap(0,*) (25)
- PAT (Advanced Level) Practise 1067 Sort with Swap(0,*) (25)
- PAT 1067 Sort with Swap(0,*)
- pat 1067 Sort with Swap(0,*) (25)
- PAT (Advanced Level) Practise 1067 Sort with Swap(0,*) (25)
- PAT1067 Sort with Swap(0,*)
- PAT-A-1067. Sort with Swap(0,*) (25)
- PAT A1067. Sort with Swap(0,*) (25)
- 浙大pat | 牛客网甲级 1025 Sort with Swap(0) (25)排序
- 1067. Sort with Swap(0,*) (25)
- 1067. Sort with Swap(0,*) (25)
- pat--Sort with Swap(0, i)
- 10-排序6 Sort with Swap(0, i)