题目描叙:
You’re given an array aa. You should repeat the following operation kk times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0.
Input
The first line contains integers nn and kk (1≤n,k≤105)(1≤n,k≤105), the length of the array and the number of operations you should perform.
The second line contains nn space-separated integers a1,a2,…,ana1,a2,…,an (1≤ai≤109)(1≤ai≤109), the elements of the array.
Output
Print the minimum non-zero element before each operation in a new line.
Examples
inputCopy
3 5
1 2 3
outputCopy
1
1
1
0
0
inputCopy
4 2
10 3 5 3
outputCopy
3
2
Note
In the first sample:
In the first step: the array is [1,2,3][1,2,3], so the minimum non-zero element is 1.
In the second step: the array is [0,1,2][0,1,2], so the minimum non-zero element is 1.
In the third step: the array is [0,0,1][0,0,1], so the minimum non-zero element is 1.
In the fourth and fifth step: the array is [0,0,0][0,0,0], so we printed 0.
In the second sample:
In the first step: the array is [10,3,5,3][10,3,5,3], so the minimum non-zero element is 3.
In the second step: the array is [7,0,2,0][7,0,2,0], so the minimum non-zero element is 2.
分析:
本题数据较多,如果不用SORT排序的话,会时间超限。本题切忌输出一个最小的然后减去一个最小的。可以用sum变量来保存在这一次的输出中应该减去多少。
#include"stdio.h"
#include"string.h"
#include"algorithm"
using namespace std;
long long a[100001];
int main()
{
long long n,k;
long long sum;
long long i,j;
while(~scanf("%lld%lld",&n,&k))
{
for(i=0;i<n;i++)
scanf("%lld",&a[i]);
sum=0;//第一次的时候不减
sort(a,a+n);
for(i=0;k--;i++)//循环k次
{ if(i<n)//如果下标在制定范围里,就也许不是输出0
{if(a[i]-sum!=0)//sum保存要减去的数。当前数减去sum表示经过前i次后的值
{printf("%lld\n",a[i]-sum);
sum+=(a[i]-sum);//sum实时更新,注意是加a[i]-sum的值。
}
else
{
k++;//未能输出,表示这个数和上一个数相同,所以需要多一次循环
continue;
}
}
else
printf("%lld\n",0);
}
}
}