HDU - 5122 K.Bro Sorting(贪心)
2015-10-28 23:46
204 查看
题目大意:给你N个数字,要求你将这N个数字进行排序,有一种排序操作,挑选一个数,往右移动,直到碰到大于该数的数
问最少要操作几次
解题思路:从右往左扫,只有最高位都到位置了,才能移动最低位,不然中途就会被卡掉
用pos表明扫到那个位置了,用Max代表该位置应该要放什么数
讨论一下
1.如果val[pos] < Max,表示本来该位置应该是Max的,可是该数却比Max小,这就要将所有[val[pos] + 1, Max] 的所有数进行移动了,接着更新Max = val[pos ] - 1,表示下一个位置就要放Max了
2.如果val[pos] > Max,这就不用管了,因为我们前面已经计算在内了,所以直接跳过
3.如果val[pos] == Max,表示符合,Max–
问最少要操作几次
解题思路:从右往左扫,只有最高位都到位置了,才能移动最低位,不然中途就会被卡掉
用pos表明扫到那个位置了,用Max代表该位置应该要放什么数
讨论一下
1.如果val[pos] < Max,表示本来该位置应该是Max的,可是该数却比Max小,这就要将所有[val[pos] + 1, Max] 的所有数进行移动了,接着更新Max = val[pos ] - 1,表示下一个位置就要放Max了
2.如果val[pos] > Max,这就不用管了,因为我们前面已经计算在内了,所以直接跳过
3.如果val[pos] == Max,表示符合,Max–
#include <cstdio> #include <cstring> const int N = 1000010; int val ; int n, cas = 1; void init() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &val[i]); } void solve() { int pos = n, Max = n, ans = 0; while (pos) { if (val[pos] < Max ) { ans += Max - val[pos]; Max = val[pos] - 1; } if (val[pos] == Max) Max--; pos--; } printf("Case #%d: %d\n", cas++, ans); } int main() { int test; scanf("%d", &test); while (test--) { init(); solve(); } return 0; }
相关文章推荐
- Spring官网改版后下载
- 教你简单玩转WebService -JAX-WS
- 传统的分布式应用集成技术(网摘)
- [LeetCode] Single Number III
- Java的向下转型和向上转型专题
- sift 初步学习
- Oracle练习题(1~19)
- 野指针(悬挂指针)
- Lintcode 两个链表的交叉
- 野指针(悬挂指针)
- unity抛物线,平均速度下的运动轨迹
- uc手机浏览器使用animation的一个坑
- Lowest Common Ancestor of a Binary Search Tree
- 线程的生命周期
- codeforces 591A. Wizards' Duel 解题报告
- UIDevice的 UiSelector的讲解
- Xargs用法详解
- ip
- Java NIO (一)
- 好久没打开博客了