Codeforces 1256B. Minimize the Permutation 貪心 STL

題意:給出一個排列,可以且僅可以對排列中某個位置相鄰元素進行一次操作,該操作交換兩元素位置,求出在進行操作後可以得到的最小字典序的排列
思路:水題,算是對STL的應用,主要是太久沒有碰代碼了,手癢的不行。因爲不管怎麼交換隻要最小的元素在最前面就行,首先1肯定是在首位,這樣原來1位置之前的所有元素都需要交換一次,記錄下當前已交換的元素位置,找出後面還沒交換過的最小的元素,將其儘量放到前面,直到所有元素都已交換或者最小元素排在最後算法結束

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxn = 4e5+10;
const int mod = 1e9+7;
const int inf = 0x3f3f3f3f;
int q, n, a[maxn];
int main()
{
	cin >> q;
	while (q--) {
		cin >> n;
		int pos = 0;
		vector<int> a(n);
		for (int i = 0; i < n; i++) {
			cin >> a[i];
		}
		while (pos < n) {
			int p = min_element(a.begin()+pos, a.end())-a.begin();
			int t = a[p];
			a.erase(a.begin()+p);
			a.insert(a.begin()+pos, t);
			if (pos == p) pos = p+1;
			else pos = p;
		}
		for (int i = 0; i < n; i++)
			printf("%d ", a[i]);
		cout << "\n";
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章