Pierre is recently obsessed with an online game. To encourage users to log in, this game will give users a continuous login reward. The mechanism of continuous login reward is as follows: If you have not logged in on a certain day, the reward of that day is 0, otherwise the reward is the previous day's plus 1.
On the other hand, Pierre is very fond of the number N. He wants to get exactly N points reward with the least possible interruption of continuous login.
Input
There are multiple test cases. The first line of input is an integer T indicates the number of test cases. For each test case:
There is one integer N (1 <= N <= 123456789).
Output
For each test case, output the days of continuous login, separated by a space.
This problem is special judged so any correct answer will be accepted.
Sample Input
4 20 19 6 9
Sample Output
4 4 3 4 2 3 2 3
Hint
20 = (1 + 2 + 3 + 4) + (1 + 2 + 3 + 4)
19 = (1 + 2 + 3) + (1 + 2 + 3 + 4) + (1 + 2)
6 = (1 + 2 + 3)
9 = (1 + 2) + (1 + 2 + 3)
Some problem has a simple, fast and correct solution.
题目说有一个在线游戏,连续登录的第i天可以得到i个积分.一个人想以最小的中断次数得到N分,最少中断几次,每次连续登陆几天,输出任意一种即可.
这道题刚看到完全不知所措,笔算后发现1-20的数全部都能由3个和来组成.
用dfs验证了1-500以内的数也都满足这个情况,下面是验证代码
#include<iostream>
#include<math.h>
using namespace std;
int sum[50005];
int Min;
int flag;
void dfs(int n,int deep)
{
if(deep>4) return;
if(n==0)
{
Min=min(Min,deep);
}
int k=sqrt(2*n)+5;
for(int i=k;i>=1;i--)
{
if(flag) return;
if(n-sum[i]>=0)
dfs(n-sum[i],deep+1);
}
}
int main()
{
for(int i=1;i<=50000;i++)
sum[i]=sum[i-1]+i;
for(int i=1;i<=500;i++)
{
Min=10;
dfs(i,0);
if(Min>3) flag=1;
}
if(!flag) cout<<"最多由3个数组成"<<endl;
else cout<<"可以由超过3个数组成"<<endl;
}
发现这个规律以后,这个问题可以得到解决了,分由一个和组成,两个和组成,三个和组成三种情况.第一种种情况直接判断,第二种情况枚举第一,第二个数,二分搜索第三个数,乍一看复杂度达到了O(n^2^logn),最坏的情况远远小于这个值,n大概在13000左右.
#include <iostream>
#include <cstdio>
using namespace std;
int sum[59000];
int t;
int main()
{
for(int i=1;i<=58888;i++)
sum[i]=sum[i-1]+i;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
int flag=1;
for(int i=1;i<=58888;i++)
{
if(sum[i]>n) break;
if(sum[i]==n)
{
cout<<i<<endl;
flag=0;
break;
}
}
if(flag)
{
for(int i=1;i<=58888;i++)
{
if(sum[i]>n) break;
int k=lower_bound(sum,sum+58000,n-sum[i])-sum;
if(sum[k]+sum[i]==n)
{
cout<<i<<" "<<k<<endl;
flag=0;
break;
}
}
if(!flag) continue;
for(int i=1;i<=58888;i++)
{
if(sum[i]>n) break;
for(int j=i+1;j<=58888;j++)
{
int k=lower_bound(sum,sum+58000,n-sum[i]-sum[j])-sum;
if(sum[i]+sum[j]>n) break;
if(sum[i]+sum[j]+sum[k]==n)
{
cout<<i<<" "<<j<<" "<<k<<endl;
flag=0;
break;
}
}
if(!flag) break;
}
}
}
return 0;
}