PAT甲级1067
Posted wx630c98f24f6b8
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT甲级1067相关的知识,希望对你有一定的参考价值。
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 1
Sample Output:
9
/*
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
bool checksort(vector<int> a,int n,int &swapindex)
for (int i = 0; i < n; i++)
if (a[i] != i)
swapindex = i;
return false;
return true;
int main()
int N;
scanf("%d", &N);
//int *a = new int[N];
//int *b = new int[N];
int temp;
int start;
vector<int> a, b;
for (int i = 0; i < N; i++)
b.push_back(0);
for (int i = 0; i < N; i++)
scanf("%d", &temp);
if (!temp)
start = i;
a.push_back(temp); b[temp] = i;
int swapindex = 0,count=0;
while (!checksort(a, N,swapindex))
if (!start)
int temp = a[swapindex];
swap(a[swapindex], a[start]);
b[0] = swapindex;
b[temp] = start;
count++;
start = swapindex;
while (start)
for (int i = 0; i < N; i++)
if (a[i] == start)
swapindex = i;
break;
swap(a[swapindex], a[start]);
count++;
start = swapindex;
while (start)
swap(a[b[start]], a[start]);
int temp = b[start];
b[start] = start;
b[0] = temp;
start = temp;
count++;
printf("%d", count);
return 0;
我的超时版本*/
#include <cstdio>
#include <vector>
using namespace std;
int main()
int n, num, cnt = 0, ans = 0, index = 1;
scanf("%d", &n);
vector<int> v(n);
for (int i = 0; i < n; i++)
scanf("%d", &num);
v[num] = i;//记录索引即可
if (num != i && num != 0) cnt++;//记录索引与值不一致的个数
while (cnt > 0)
if (v[0] == 0)
while (index < n)
if (v[index] != index) //记录上次处理时,第一次记录索引与值不一致时的索引
swap(v[index], v[0]);//因为每次处理时都会使之一致,那么从这里开始往后
//进行遍历即可,不要从头开始遍历
ans++;
break;
index++;
while (v[0] != 0)
swap(v[v[0]], v[0]);
ans++;
cnt--;
printf("%d", ans);
return 0;
/*跟这位大神的思想一致,但对复杂度的处理不够好 ╮(╯▽╰)╭*/
以上是关于PAT甲级1067的主要内容,如果未能解决你的问题,请参考以下文章
PAT甲级——A1067 Sort with Swap(0, i)