USACO 2.1 Sorting a Three-Valued Sequence

来源:互联网 发布:网络彩票恢复最新消息 编辑:程序博客网 时间:2024/05/21 15:00

题目:

Sorting is one of the most frequently performed computational tasks. Consider the special sorting problem in which the records to be sorted have at most threedifferent key values. This happens for instance when we sort medalists of a competition according to medal value, that is, gold medalists come first, followed by silver, and bronze medalists come last.

In this task the possible key values are the integers 1, 2 and 3. The required sorting order is non-decreasing. However, sorting has to be accomplished by a sequence of exchange operations. An exchange operation, defined by two position numbers p and q, exchanges the elements in positions p and q.

You are given a sequence of key values. Write a program that computes the minimal number of exchange operations that are necessary to make the sequence sorted.

PROGRAM NAME: sort3

INPUT FORMAT

Line 1:N (1 <= N <= 1000), the number of records to be sortedLines 2-N+1:A single integer from the set {1, 2, 3}


题目大意就是给定一串只有1,2,3组成的数字序列,要将其进行升序排列,问最少需要进行几次数字交换?

题目描述的过程是交换,而非插入,一开始做这道题的时候我一直想着像扑克牌一样碰到1抽出来插到前面,遇到3抽出来插到后面,后来发现并不能这样做。
这道题最简单的方法就是运用贪心的策略。因为给定了序列后,它排序后的结果是定的,所以我们只要将错位的元素进行交换,比如占了1位子的3尽量和序列末尾开始的1进行交换,占了1位子的2就和靠中间的1进行交换。这样交换的代价和可以最小。
具体实现时就是在输入时统计1的个数n1和2的个数n2,然后从1到n1之间,如果有2,就和从n1+1->n之间找到的第一个1交换;如果有3,就和从n->n1+1之间找到的第一个1交换,这样1就全都归位了。然后只要遍历一下n1+1~n2之间有多少个3,就把计数次数加上3的个数。最后得到答案。

代码如下:
/*ID: gjj50201LANG: C++TASK: sort3*/#include<stdio.h>#include<iostream>#include<string>#include<stdlib.h>#include<algorithm>using namespace std;int a[1001];int main(){freopen("sort3.in","r",stdin);freopen("sort3.out","w",stdout);int n,n1 = 0,n2 = 0,ans = 0,j;cin>>n;for(int i=1; i<=n; i++){cin>>a[i];if(a[i] == 1) n1++;else if(a[i] == 2) n2++;}for(int i=1;i<=n1;i++){if(a[i] == 2){//cout<<i<<endl;for(j=n1+1;j<=n;j++)if(a[j] == 1)break;swap(a[i],a[j]);ans++;}else if(a[i]==3){for(j=n;j>=n1+1;j--)if(a[j] == 1)break;swap(a[i],a[j]);ans++;}}// for(int i=1;i<=n;i++)// cout<<a[i]<<" ";// cout<<endl;for(int i=n1+1; i<=n1+n2; i++)if(a[i] == 3)ans ++;cout<<ans<<endl;return 0;}




2 0
原创粉丝点击