标签:
拼了老命用一种贪心的思想把它A了,但是代码写的太烂了,而且时间复杂度为 n ^ 2,我就不多说了,太烂了
之后上网找了一个规律,时间复杂度为 nlogn,而且思路很明确,又写了一遍
代码:(贪心)
/* ID: 18906421 LANG: C++ PROG: sort3 */ #include<cstdio> #include<cstring> #include<vector> #include<algorithm> using namespace std; const int maxn = 1005; int n; int arr[maxn]; int sorted[maxn]; int vis[4] = {0}; int s[3]; int find_pos(int u,int v,int num){ int re_pos; for(int i = 0; i < num; i++){ if(arr[i] == v){ if(i >= s[u]) return i; else re_pos = i; } } return re_pos; } int main(){ int n,cnt = 0,pos; freopen("sort3.in","r",stdin); freopen("sort3.out","w",stdout); scanf("%d",&n); for(int i = 0; i < n; i ++){ scanf("%d",&arr[i]); sorted[i] = arr[i]; vis[arr[i]]++; } s[1] = -1; s[2] = -1; sort(sorted,sorted + n); for(int i = 0; i < n; i++) if(sorted[i] == 1 && s[1] < 0) s[1] = i; else if(sorted[i] == 2 && s[2] < 0) s[2] = i; //printf("%d %d\n",s[1],s[2]); for(int i = n - 1; i >= 0; i--){ //printf("%d %d %d\n",vis[1],vis[2],vis[3]); if(arr[i] == 1){ if(vis[3]){ pos = find_pos(1,3,i); //printf("%d %d\n",i,pos); arr[pos] = 1; cnt ++; vis[3] --; } else if(vis[2]){ pos = find_pos(1,2,i); //printf("%d %d\n",i,pos); arr[pos] = 1; cnt ++; vis[2] --; } else vis[1] --; } else if(arr[i] == 2){ if(vis[3]){ pos = find_pos(2,3,i); //printf("%d %d\n",i,pos); arr[pos] = 2; cnt ++; vis[3] --; } else vis[2] --; } else vis[3] --; } printf("%d\n",cnt); return 0; }思路:
/* ID: 18906421 LANG: C++ PROG: sort3 */ #include<cstdio> #include<cstring> #include<vector> #include<algorithm> using namespace std; const int maxn = 1005; int n,ans; int arr[maxn]; int sorted[maxn]; int vis[4][4] = {0}; int main(){ freopen("sort3.in","r",stdin); freopen("sort3.out","w",stdout); int n; scanf("%d",&n); for(int i = 0; i < n; i++){ scanf("%d",&arr[i]); sorted[i] = arr[i]; } sort(sorted,sorted + n); for(int i = 0; i < n; i++){ if(arr[i] != sorted[i]) vis[sorted[i]][arr[i]] ++; } int v1 = min(vis[1][2],vis[2][1]); vis[1][2] -= v1; vis[2][1] -= v1; int v2 = min(vis[1][3],vis[3][1]); vis[1][3] -= v2; vis[3][1] -= v2; int v3 = min(vis[2][3],vis[3][2]); vis[2][3] -= v3; vis[3][2] -= v3; ans = v1 + v2 + v3; ans += (vis[1][2] + vis[2][1] + vis[1][3] + vis[3][1] + vis[2][3] + vis[3][2]) / 3 * 2; printf("%d\n",ans); return 0; }
【USACO】Sorting a Three-Valued Sequence(思路)
标签:
原文地址:http://blog.csdn.net/u013451221/article/details/45064935