HDU 2446 Shell Pyramid Binary Search

Source: Internet
Author: User

This morning, I finally got rid of the last question D. My second point is an AK.
I still have the copyright to answer this question ~~ More and more interesting!
Let's talk about how to do it.
I heard that I tried to push the formula myself. It feels good.
First, we can see that

A1 = 1, a2 = 3, a3 = 6. Obviously an = (1 + n) * n/2;
How can we find the Sn ??? Sn = Σ an = (1/2) Σ (n * n + n) = 0.5 * (Σ n * n + Σ n );
In this way, it is converted into the sum of consecutive natural numbers and the sum of consecutive natural numbers.
Continuous natural numbers and (1 + n) * n/2
Sum of squares: n (n + 1) (2n + 1)/2
Sum of cubes: [n (n + 1)/2] ^ 2
Bringing the formula into the ultimate simplification ------> Sn = n (n + 1) (n + 2)/6; a beautiful formula was born

Next we can use binary to search for the answer.
I think my code is still very beautiful ~ Despite vulnerabilities

#include<iostream>#define MAXLayer 1111111using namespace std;__int64 layerSum[MAXLayer];__int64 getSum( __int64 m ){ __int64 sum; sum=m*(m+1)/2;    if( sum%3==0 ){      sum/=3;sum*=(m+2);       }       else sum*=(m+2)/3;    return sum;}int BinarySeachLayer( __int64 &num ){ __int64 l=1,r=3810776,m; __int64 sum; while( m=(l+r)/2,l<r ) {    sum=getSum(m);    if( sum>=num ) r=m;    else l=m+1;  }  num-=getSum(m-1);  return (int)m;}int BinarySeachRow( __int64 &num ){ __int64 l=1,r=3810776,m; __int64 sum; while( m=(l+r)/2,l<r ) {    sum=(1+m)*m/2;    if( sum>=num ) r=m;    else l=m+1;  }  num-=(m-1)*m/2;  return (int)m;}int main(){ __int64 N;int T; scanf( "%d",&T ); while( T-- ) {   scanf("%I64d",&N);    int Layer=BinarySeachLayer( N );    int Row=BinarySeachRow( N );    int Column=N;    printf( "%d %d %d\n",Layer,Row,Column );  }  return 0;}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.