138 – Street Numbers//暴力or解方程

來源:互聯網
上載者:User

先bs下自己吧。這道題可以先打表,在提交。

剛開始寫的二分有點問題,我先找到的是n,然後再找m。其實是先找到m,然後再找n。

另一種解法是解方程,解佩爾方程。

不管是暴力還是解方程都要先找出運算式。由題意可得n*(n+1)/2=x*(x+1)/2-n*(n+1)+n;化簡可得n*n/2=x*x+x。然後將其變形為標準的佩爾方程,然後再用遞推求解。

下面是二分的代碼:

#include<iostream>#include<cstdio>using namespace std;const int n=~(unsigned int)0/2;int main(){    int t=0;    for(long long i=6;i<n&&t<=10;i++)    {        long long min=1;        long long max=i+1;        long long mid;        while(min<=max)        {            mid=(min+max)/2;            if(mid*mid*2==i*(i+1))            {                printf("%10lld%10lld\n",mid,i);                t++;                break;            }            else if(mid*mid*2>i*(i+1)) max=mid-1;            else min=mid+1;        }    }    return 0;}

結果需要3分鐘左右才能求出10組解。囧.....

下面是解方程的代碼:

#include<iostream>#include<cstdio>using namespace std;int main(){    int x3,y3;    for(int x1=1,y1=1,x2=1,y2=1,t=0;t<10;t++)    {        x3=(2*x1+1)*(2*x2+1)+8*y1*y2;        y3=(2*x1+1)*y2+y1*(2*x2+1);        printf("%10d%10d\n",y3,(x3-1)/2);        x2=(x3-1)/2;        y2=y3;    }    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.