1. 程式人生 > >【PAT甲級】1067. Sort with Swap(0,*) (25)

【PAT甲級】1067. Sort with Swap(0,*) (25)

注:第二個for迴圈中,始終從0開始查詢會使測試用例1、2超時,因此作一個小優化,即記住上次開始查詢的位置start,下次從此處開始進行查詢。

#include <stdio.h>
void swap(int *a, int *pos, int x, int y) {
    int tmp = a[x];
    a[x] = a[y];
    pos[a[y]] = x;
    a[y] = tmp;
    pos[tmp] = y;
}
int main(int argc, char *argv[]) {
    int n;
    scanf("%d", &n);
    int
*a = new int[n]; int *pos = new int[n]; for (int i = 0; i < n; i++) { scanf("%d", &a[i]); pos[a[i]] = i; } int count = 0; bool flag = true; int start = 0; while (flag) { while (pos[0] != 0) { swap(a, pos, pos[0], pos[pos[0]]); count++; } for
(int i = start; i < n; i++) { if (a[i] != i) { swap(a, pos, 0, i); start = i; count++; break; } else if (i == n - 1) { flag = false; } } } printf("%d\n", count); return
0; }