PAT A1067 Sort with Swap(0, i)(***贪心)

问题链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805403651522560

题意:

    给出0,1,...,N-1的一个序列,要求通过两两交换的方式将其变为递增序列,但是规定每次只能用0与其他数进行交换。求最小交换次数。

Note:

1 记录不在应有位置上的数字个数时要除去0.

2 在while循环中k是从进入循环开始递增的,不用每次从头开始判断。

法一不记录数字,因为数字是0~N-1固定的。只散列记录数字位置,这样就无需遍历查找位置。

法二因为在循环中需要对数字位置进行多次查找,所以一些测试点会超时。 

法一:

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
int pos[100010];
int main(){
	int n, num, ans = 0;//ans记录交换次数 
	cin >> n;
	
	int x = 0;
	for(int i = 0; i < n; i++){
		cin >> num;
		pos[num] = i;//num所处的位置为i 
		if(num != i && num != 0)//记录除0以外不在应有位置上的数字个数 
		    x++;
	}
	
	int k = 1; //k存放除0以外当前不在本位上的最小的数 
	while(x > 0){
        //如果0在本位上,则寻找一个当前不在本位上的数与0交换
		if(pos[0] == 0){
			while(k < n){
				if(pos[k] != k){
					swap(pos[0], pos[k]);//将k与0交换位置
					ans++;
					break;
				}
				k++;
			}
		}
		//如果0不在本位,则将0所在位置的数的当前所处位置,与0的位置交换 
        while(pos[0] != 0){
        	swap(pos[0], pos[pos[0]]);
        	ans++;
        	x--;
		}
	}
	cout << ans;
	return 0;
} 

法二:

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
int temp[100010];
int main(){
	int n, num = 0;//num记录交换次数 
	cin >> n;
	
	int x = 0;
	for(int i = 0; i < n; i++){
		cin >> temp[i];
		if(temp[i] != i && temp[i] != 0)//记录除0以外不在应有位置上的数字个数 
		    x++;
	}
	
	while(x > 0){

		if(temp[0] == 0){
			for(int i = 1; i < n; i++)//找不在应在位置上的数字 
			    if(temp[i] != i){
			    	swap(temp[0], temp[i]);
			    	num++;
			    	break;
				}	
		}
        while(temp[0] != 0){
        	int i;//找0的位置k
	    	for(i = 1; i < n; i++)
			    if(temp[i] == 0)
			        break;	
			int j;
			for(j = 0; j < n; j++)
				if(temp[j] == i)
					break;
			swap(temp[i], temp[j]);
			num++;
			x--;   		
		}
	}
	
	cout << num;
	
	return 0;
} 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值