Sorting a Three-Valued Sequence

IOI'96 - Day 2

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 three different 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.

本来打了贪心得进行模拟,后来改成了如下玄学贪心做法,十分简洁。欢迎Hack。

统计1,2,3的个数,可知放置1,2,3正确的位置,统计在各位置的数字1,2和3的个数,具体详见下。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std; const int MAXN=1000+5;
int ct[4],c[4][4];
int a[MAXN]; int main()
{
freopen("sort3.in","r",stdin);
freopen("sort3.out","w",stdout);
int n;
scanf("%d",&n);
for(int i=1;i<=n;++i)
scanf("%d",&a[i]),++ct[a[i]];
for(int i=1;i<=ct[1];++i)
++c[1][a[i]];
for(int i=ct[1]+1;i<=ct[1]+ct[2];++i)
++c[2][a[i]];
//统计个数
int ans=0;
ans+=c[1][2]+c[1][3];//把1换到正确位置的最少步数
c[2][3]+=max(0,c[2][1]-c[1][2]);//有多少3被交换到了二位置
ans+=c[2][3];//将2,3交换到正确位置
printf("%d\n",ans);
return 0;
}

最新文章

  1. MVC4做网站后台:栏目管理2、修改栏目
  2. Android热修复之微信Tinker使用初探
  3. 淘宝UWP桌面版已经发布
  4. JFreeChart 使用一 饼图之高级特性
  5. js事件冒泡和事件捕获
  6. zw版【转发&#183;台湾nvp系列Delphi例程】HALCON ObjToInteger1-4
  7. Redis系统管理相关指令简介
  8. mysql启动问题access denied for user &#39;root&#39;@&#39;localhost&#39;(using password:YES)
  9. Tmall发送码asp验证sing(自有码开发)
  10. poj 1870 Bee Breeding
  11. js实现滑动解锁功能(PC+Moblie)
  12. Source Insight设置总结
  13. scrot-0.8
  14. 这几天有django和python做了一个多用户博客系统(可选择模板)
  15. 根据HttpServletRequest获取用户真实IP地址
  16. Python_方法演示
  17. hello2 源码分析
  18. Python学习笔记-基础2
  19. androidstudio项目如何使用git版本回退
  20. hive表命名规范 源码规则

热门文章

  1. yii2 response响应配置
  2. 开学第一课Java考试
  3. JavaScript实现动态打字效果
  4. PAT 基础编程题目集 6-10 阶乘计算升级版 (20 分)
  5. 利用GRC进行安全研究和审计 – 将无线电信号转换为数据包(转)
  6. eXosip和osip详解
  7. Linux下文件的七种类型
  8. 137.在Django中操作session
  9. phpstorm格式化数组
  10. 解决webpack和gulp打包js时ES6转译ES5时Object.assign()方法没转译成功的问题