七个字:从后往前先换大
就是从后往前扫,1的时候 从最大的可能中先替换3,然后替换2。
这个规律就是观察出的,比较好理解。
因为“从后往前先换大”的时候,把最大的放在的最后,这样可能就节省了下次的排序。
具体代码如下:
/*
ID: awsd1231
PROG: sort3
LANG: C++
*/
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int n, a[1010];
int main () {
freopen("sort3.in", "r", stdin);
freopen("sort3.out", "w", stdout);
scanf("%d", &n);
int c1(0);
for (int i = 0; i != n; ++i) {
scanf("%d", &a[i]);
if(a[i] == 1) ++c1;
}
int cnt(0);
for (int m = 1; m != 3; ++m) {
for (int i = n - 1; i != -1; --i) {
bool c3 = false;
if (a[i] == m) {
int t = i;
if (m == 1) t = c1;
for (int j = 0; j != t; ++j) {
if (a[j] == 3) {
int t = a[i];
a[i] = a[j];
a[j] = t;
++cnt;
c3 = true;
break;
}
}
if (!c3 && m != 2) {
for (int j = 0; j != i; ++j) {
if (a[j] == 2) {
int t = a[i];
a[i] = a[j];
a[j] = t;
++cnt;
break;
}
}
}
}
}
}
cout << cnt << endl;
return 0;
}
时间: 2025-01-09 08:55:12