题目描述:
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:
9题目分析:
题目有两个特点:一是每次只能和0进行交换;二是这N个数是连续的,即最终第m个位置上是数字m.
我的做法是,首先找到0所在的位置,然后去找应该在这个位置的数字,交换他们,直到0到了位置0.
接下来检查是否所有数字都到了自己的位置,如果没有,则将0与第一个不在位置的数字交换,然后执行上面的步骤。直到所有数字归位。
代码逻辑没有问题,但是时间复杂度高了一些,有一些测试用例会超时。
C++代码如下:
#include <stdio.h>
#include <vector>
using namespace std;
int N,count=0;
vector<int> v;
void swap(int index){
if(index == 0)
return;
int i;
for(i=0;i<N;i++){
if(v[i] == index){
int tmp=v[i];
v[i] = 0;
v[index] = tmp;
count++;
swap(i);
break;
}
}
}
int main(){
scanf("%d",&N);
int i,index;
for(i=0;i<N;i++){
int tmp;
scanf("%d",&tmp);
if(tmp == 0)
index = i;
v.push_back(tmp);
}
swap(index);
int flag=0;
index=0;
while(flag==0){
flag=1;
for(i=index;i<N;i++){
if(v[i] != i){
flag=0;
v[0] = v[i];
v[i] = 0;
count++;
index=i;
swap(index);
break;
}
}
}
printf("%d\n",count);
return 0;
}
看了网上的解法,自己修改了一下,不再超时。该做法比较巧妙,不是用数组去存值,而是去存每个数字的位置。
C语言代码如下:
#include <stdio.h>
int N;
int v[100001];
int findNotOk(int begin){
int i;
for(i=begin;i<N;i++){
if(v[i]!=i)
return i;
}
return 0;
}
int main(){
scanf("%d",&N);
int i;
for(i=0;i<N;i++){
int tmp;
scanf("%d",&tmp);
v[tmp] = i;
}
int count=0;
int index=1;
index = findNotOk(index);
while(index!=0){
if(v[0]==0){
v[0]=v[index];
v[index]=0;
count++;
}
while(v[0]!=0){
int tmp = v[0];
v[0] = v[tmp];
v[tmp] = tmp;
count++;
}
index = findNotOk(index);
}
printf("%d\n",count);
return 0;
}