DS Homework 7-1 Sort with Swap(0, i)
来源:互联网 发布:白寿彝 知乎 编辑:程序博客网 时间:2024/06/05 20:56
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 usewhile (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[N]; 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;}
- DS Homework 7-1 Sort with Swap(0, i)
- Sort with Swap(0, i)
- Sort with Swap(0, i)
- 浙大PAT-Sort with Swap(0, i)
- pat--Sort with Swap(0, i)
- 5-16 Sort with Swap(0, i)
- 10-排序6 Sort with Swap(0, i)
- 10-排序6 Sort with Swap(0, i) (25分)
- 10-排序6 Sort with Swap(0, i) (25分)
- 10-排序6 Sort with Swap(0, i)
- 10-排序6 Sort with Swap(0, i) (25分)
- 1067. Sort with Swap(0,*)
- 1067. Sort with Swap(0,*)
- 1067 Sort with Swap(0,*)
- 1067. Sort with Swap(0,*)
- 1067.Sort with Swap(0,*)
- pat1067 Sort with Swap(0,*)
- PAT1067 Sort with Swap(0,*)
- fetch_mldata('MNIST Original', data_home='./datasets')
- stl 仿函数(函数对象)
- sqlserver2008主从服务器配置
- 机械硬盘提示RAW,要如何找回文件
- RFID 电动二轮自行车的防盗系统—读头
- DS Homework 7-1 Sort with Swap(0, i)
- django2.0 ForeignKey参数变化
- Pycharm中配置pep8
- java环境安装以及中文eclipse分享
- CentOs 找不到ifconfig 命令的解决办法
- sqlserver xml.modify('replace value of .... with....') 函数改造
- 给初入职场的你
- plsql(一)
- 资源 | 盘点GitHub最著名的20个Python机器学习项目