原题链接:
题目内容:
In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.
Every soldier has a rank — some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.
To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.
At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.
You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1 ≤ i ≤ n, 1 ≤ ai ≤ k).
output
Print a single integer — the number of golden coins needed to raise all the soldiers to the maximal rank.
输入1
4 4
1 2 2 3
输出1
4
输入2
4 3
1 1 1 1
输出2
5
思路
大致的意思就是第一个输入n,代表士兵数量;第二个输入k,代表最高等级;每次训练可以升级不同等级的士兵各一个。要使得所有士兵都到达k级,需要多少次训练。
所以我们可以将士兵每次从小到大排列,只要第一位士兵也到了k级就可以了。
具体实现过程中,需要多开一个数组,在每次训练过程中,来记录此等级的士兵是否已经升级过了。
具体代码如下:
#include<iostream>
#include<algorithm>
using namespace std;
const int N=105;
int a[N],b[N];
//a数组储存士兵等级,b数组储存当前等级士兵是否升级过
int main(){
int n,k;
scanf("%d %d",&n,&k);
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
}
int num=0;
while(a[0]!=k){
num++;
for(int i=0;i<n;i++){
if(b[a[i]]!=1&&a[i]<k){
b[a[i]]=1; //当此等级士兵被升级过后,b数组为1
a[i]++;
}
}
for(int i=1;i<=k;i++){
b[i]=0; //清零所有的b数组
}
sort(a,a+n);
}
printf("%d",num);
return 0;
}