1004_History_repeat_itself

来源:互联网 发布:凸轮机构设计软件 编辑:程序博客网 时间:2024/05/30 02:52

题目:

hdu_4342_History_repeat_itself

官方题解:

1)To solve the N-th non-square number:
There is a number K:  K^2<N+K<(K+1)^2
Thus : K^2+1<= N+K <= (K+1)^2-1
So: (K-1/2)^2+3/4=K^2-K+1 <= n <= K^2 +K = (K+1/2)^2 -1/4
That is to say: K-1/2 < (N)^1/2 <= K+1/2
the N-th non-square number is : N+K (K is the nearest integer from N^1/2);


And for many team, you can just use circular statement, it's simple and fast.


2)To get the sum:
for any i , there exists a integer K : K^2<=i<(K+1)^2;
to find the K:
the first (1^2) i : 1
the next  (2^2) i : 2
...
the next  (K^2) i : K
...
If Sum(K^2) <= N <= Sum( (K+1)^2), R=N-Sum(K^2);
add them up : 1^2*1 + 2^2*2 + ... + K^2*K + R*(K+1) ;
use the knowlege of college math,
Then You Got It! 
M=N^(1/2)-1, drop the number after the decimal point.
the Ans=(M*(M+1)*(2*M+1))/3 +(M+1)*M/2+ (M+1)*(N-(M+1)*(M+1)+1);




3)
I think this problem is simple, hope that most of you can solve it.


个人理解:

解题的关键在于找到离第M个非平方数最近且小于它的平方数。本人最初的想法是预处理出2^31以内的平方数,再用二分查找去找第M个非平方数。但是题解给出的方法显然要跟好些。

标程:

#include <iostream>#include <cmath>using namespace std;typedef __int64 LL;int main(){ //   freopen("data.in", "r", stdin); //   freopen("data.out", "w", stdout);    LL n,m,ans,total;    cin>>total;    while (total--)    {        cin>>n;        n+=sqrt(n)+0.5;        m=sqrt(n)-1;        ans=(m*(m+1)*(2*m+1))/3 +(m+1)*m/2+ (m+1)*(n-(m+1)*(m+1)+1);        cout<<n<<" "<<ans<<endl;    }    return 0;}