7-16 Sort with Swap(0, i)

题目

题意:给出序列要求只能用0和未在正确顺序位置上的数交换,求最小交换次数

tip:贪心+模拟 

#include<iostream>
#include<algorithm>
using namespace std;
int main() {
	int n;
	cin>>n;
	int ans[n],place[n];
	int checked[n]= {0};
	int t;
	for(int i=0; i<n; ++i) {
		cin>>ans[i];
		if(!ans[i])
			t=i;
		if(ans[i]==i)//就在原位的标记一下
			checked[i]=1;
		place[ans[i]]=i;
	}
	int count=0;
	int j=1;
	while(1) {
		while(t) {//如果t不在零位,执行调换
			checked[t]=1;
			int f=t;
			t=place[t];
			count++;
		}
		//查看是否是已有序
		int i;
		for(i=j; i<n; ++i)
			if(!checked[i]) {
				t=i;
				place[0]=1;
				place[ans[i]]=0;
				count++;
				break;
			}
		j=i;
		if(i==n)
			break;
	}
	cout<<count;
	return 0;
}
发布了382 篇原创文章 · 获赞 17 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_40991687/article/details/104256803
今日推荐