Friends and Cookies(思维)
Abood's birthday has come, and his n friends are aligned in a single line from 1 to n, waiting for their cookies, Abood has x cookies to give to his friends.
Here is an example to understand how Abood gives away the cookies. Suppose Abood has 4 friends and x cookies, then Abood will do the following:
- Give a cookie to the 1st friend.
- Give a cookie to the 2nd friend.
- Give a cookie to the 3rd friend.
- Give a cookie to the 4th friend.
- Give a cookie to the 3rd friend.
- Give a cookie to the 2nd friend.
- Give a cookie to the 1st friend.
- Give a cookie to the 2nd friend.
- And so on until all the x cookies are given away.
Your task is to find how many cookies each friend will get. Can you?
The first line contains an integer T (1 ≤ T ≤ 100) specifying the number of test cases.
Each test case consists of a single line containing two integers x and n (1 ≤ x ≤ 1018, 1 ≤ n ≤ 1000), in which x is the number of cookies Abood has, and n is the number of his friends.
For each test case, print a single line containing n space-separated integers a1, ..., an, in which ai represents how many cookies the ith friend got.
1
5 3
2 2 1
解题思路:我将蛋糕的分配方式模拟一下
- - - - - - -
- - - - - -
- - - - - -
- - - - - -
- - - - - -
- - -
我们可以看到的是:第一行每一个人都有,然后开始的奇数个前N-1个有,偶数个后N-1有,最后一行再判断是第奇数个还是偶数个就可以得出结果。
注意的是:没跑完第一行的情况需要特判一下,跑完第一行但是m<n也需要特判一下。
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 #define LL long long int 5 using namespace std; 6 int main() 7 { 8 int t; 9 LL i,j,a[10010],m,n,x,y; 10 scanf("%d",&t); 11 while(t--) 12 { 13 memset(a,0,sizeof(a)); 14 scanf("%lld%lld",&m,&n); 15 if(n==1)///特判一下当n为1的时候 16 { 17 printf("%lld\n",m); 18 } 19 else if(m<n) 20 { 21 for(i=0;i<m;i++) 22 { 23 a[i]=1; 24 } 25 for(i=0;i<n;i++)///只有前m个人有蛋糕,后面的人没有了蛋糕 26 { 27 if(i==n-1) 28 { 29 printf("%lld\n",a[i]); 30 } 31 else 32 { 33 printf("%lld ",a[i]); 34 } 35 } 36 37 } 38 else 39 { 40 for(i=0;i<n;i++)///第一行的分配 41 { 42 a[i]=1; 43 } 44 m=m-n;///分配完第一行之后剩下的蛋糕数量 45 x=m/(n-1);///x表示剩下的行数 46 y=m%(n-1);///y表示最后一行余下的蛋糕份数 47 for(i=1;i<n-1;i++) 48 { 49 a[i]=a[i]+x;///除了第一个人和最后一个人其他的人再得到x份蛋糕 50 } 51 ///下面是对第一个人和最后一个人以及最后一行的蛋糕分配 52 if(x%2==0)///行数为偶数 53 { 54 a[0]=a[0]+x/2; 55 a[n-1]=a[n-1]+x/2; 56 for(i=n-2;i>=n-2-y+1;i--) 57 { 58 a[i]++; 59 } 60 } 61 else///行数为奇数 62 { 63 a[0]=a[0]+x/2+1; 64 a[n-1]=a[n-1]+x/2; 65 for(i=1;i<=y;i++) 66 { 67 a[i]=a[i]+1; 68 } 69 } 70 } 71 for(i=0;i<n;i++)///输出 72 { 73 if(i==n-1) 74 { 75 printf("%lld\n",a[i]); 76 } 77 else 78 { 79 printf("%lld ",a[i]); 80 } 81 } 82 } 83 return 0; 84 }