当前位置: 代码迷 >> 综合 >> PAT1067 Sort with Swap(0,*) (25)(贪心)
  详细解决方案

PAT1067 Sort with Swap(0,*) (25)(贪心)

热度:25   发布时间:2024-01-16 13:20:29.0

题意:

给出0~N-1的序列,要求每次只能通过0和其他数交换,最后将所有数排序

思路:

这题还是比较容易想到的,分成两种情况讨论:

  • 0不在0位置,如果0在i位置,那么在i位置的应该是i,所以将i对应的位置与0交换即可
  • 0在第0位且还没排好序,选择还没匹配位置的第一个数与0交换

这题有两个样例卡时间,所以对第二种情况进行优化,不用每次从0开始遍历,从上一次的位置之前的数已经匹配完成,所以从该位置开始遍历即可。

#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 100050;int main() {int n, cnt = 0, ans = 0,index=1;int num[maxn];scanf("%d", &n);int temp;for (int i = 0; i < n; i++) {scanf("%d", &temp);num[temp] = i;if (temp != i) cnt++;}cnt--;while (cnt > 0) {if (num[0] == 0) {while(index<n){if (num[index] != index) {swap(num[index], num[0]);ans++;index++;break;}index++;}}while (num[0] != 0) {swap(num[num[0]], num[0]);ans++;cnt--;}}printf("%d\n", ans);return 0;
}

  相关解决方案