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

来源:互联网 发布:阐释者淘宝 编辑:程序博客网 时间:2024/05/21 17:02

注:第二个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;}
0 0
原创粉丝点击