第四届吉林省大学生程序设计大赛个人解题报告 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,所以算法得以正确执行。

下面贴出我的代码:

#include using namespace std; const int MAXN = 105; int main(){ int n,i,j,k,a[MAXN],b[MAXN]; while(scanf("%d",&n)!=EOF) { for(i = 0 ; i < n; i ++) cin >> a[i]; for(i = 0 ; i < n; i ++) cin >> b[i]; int count = 0; for(i = n-1 ;i >=0 ; i--) { for(j = i ; j != -1 && a[i] < b[j] ; j --); for(int t = j ; t < i ;t ++) b[t] = b[t+1]; count += i - j; } cout << count <

你可能感兴趣的:(ACM/ICPC,比赛题解)