Funky Numbers (CodeForces
阿新 • • 發佈:2019-01-22
In the first sample number .
In the second sample number 512 can not be represented as a sum of two triangular numbers.
題意:給你一個數n,是否有滿足的A、B的值。
思路:如果用兩個for迴圈遍歷一定會超時,我們可以遍歷A,然後用二分去尋找B,這樣會很大程度上減少耗時。
程式碼參考:
#include <iostream> #include<stdio.h> #include<string.h> #include<stdlib.h> #include<algorithm> #include<math.h> #define ll long long using namespace std; int main() { ll n; while(~scanf("%lld",&n)) { ll i,A,B,p=0; for(i=1;i<sqrt(2*n);i++) { A=i*(i+1)/2; ll l=i,r=sqrt(2*n),m=(l+r)/2; while(l<=r) { B=m*(m+1)/2; if(A+B<n) { l=m+1; m=(l+r)/2; } else if(A+B>n) { r=m-1; m=(l+r)/2; } else { p=1; break; } } if(p==1) break; } if(p==1) printf("YES\n"); else printf("NO\n"); } return 0; }