第四届吉林省大学生程序设计大赛个人解题报告 Problem F: Coin Game

                          Problem F: Coin Game

Gordon and Lee, fond of collecting coins, are playing a coin game.  
At first, Gordon puts N piles of his coins, decreasing-order in heights, in a rowThen Lee also puts N piles of his coins, randomly, in another row. The game rules areas follows: Every time Lee can swap any two adjacent piles of his coins. Lee, ifsuccessfully making each pile of his coins NOT higher than the correspondent pile ofGordon’s in the given time, can win all the coins away. Lee, a smart coder, is planningto write a program to calculate the minimum swaps he needs to win the game.

Input
Each test case starts with a line containing an integers N  (1<=N<=100) which is the number of piles. The next two lines each contain N integers, namely the heights of each pile of coins of Gordon’s and Lee’s, respectively. You can assume there is always a feasible solution for Lee to win the game.

Output
Print the minimum swaps Lee needs to win the game.

Sample Input
3
3 2 1 
2 2 1
3
3 2 1
1 2 3
4
6 5 3 1
1 3 5 5

Sample Output
0
3
5

 

       这道题是一道贪心的题,给两个含有N个元素的序列A[1...N] B[1...N],其中序列A是非递增序列,而B是随机序列。你的任务是,对与B序列,使用最少的交换次数W,使得两个序列满足 Ai >= Bi ( i = 1...N )。

       初看这道题,我想到了逐一比较Ai和Bi,当Ai < Bi 时,在临近位置处交换过来一个Bk,使得Ai >= Bk,那么共需要交换fabs(k-i)次。但后来发现,这样交换不是次数最少的,因为每次换完之后,有可能影响了下一次交换,导致做了一次无用功,这也就是我当时在比赛的时候无法解决的问题。

      后来想想,其实只要从序列的尾端向前端逐一比较,就可以解决这个问题,因为序列A是非递增的,所以对于任意一个Ai (i>1) ,必有A(i-1) >= Ai ,所以,每一次交换Bk之后,后面的交换将不再涉及区间[i,N]的元素,因为B在这个区间内的任意元素Bt <= At ( t∈[i,N] ),而 At <= A(t-1) 则所有的 Bt <= A(t-1) <= A(t-2) .... <=A1 ,所以,在后面的交换中,不可能再使用Bt,所以算法得以正确执行。

下面贴出我的代码:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值