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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章