15行代码AC——Link/Cut Tree CodeForces - 614A(爆long long处理+快速幂讲解)
勵志用少的代碼做高效表達
Problem describe
Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure.
Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed to help if Rostislav solves a simple task (and if he doesn’t, then why would he need Splay trees anyway?)
Given integers l, r and k, you need to print all powers of number k within range from l to r inclusive. However, Rostislav doesn’t want to spent time doing this, as he got interested in playing a network game called Agar with Gleb. Help him!
Input
The first line of the input contains three space-separated integers l, r and k (1?≤?l?≤?r?≤?1018, 2?≤?k?≤?109).
Output
Print all powers of number k, that lie within range from l to r in the increasing order. If there are no such numbers, print “-1” (without the quotes).
題意分析
題意:輸入l,r,k,輸出所有在[l,r]區間內的k的冪次。
如:輸入1,10,2 輸出1 2 4 8
分析:求冪次不必多說,pow()、累乘、快速冪都可以。
但在求解過程中,會出現爆long long的情況, 如:k的n次冪=10^18, k=1000, 此時若繼續計算,就會出現10^21 的數。超過了long long的取值范圍,連unsigned long long都無法儲存。
解決辦法是:乘法變除法。
如:將式if(pow(k, i) <= r ) 改為:if(pow(k,i-1) <= r/k) 這樣就可以在long long的范圍內取值了。
下面列出兩種AC代碼, 代碼一為快速冪求法, 代碼二為樸素求法。
如果對快速冪不甚了解,請移步——>快速冪基本思想講解
代碼一(快速冪求法)
#include<iostream> #include<cmath> using namespace std; typedef long long ll; ll quick_power(ll a, ll q) {ll sum = 1;while(q) {if(q%2==1) sum *= a;a*=a;q /= 2;}return sum; } int main( ) {ll l, r, k; cin>>l>>r>>k;bool flag = true;for(ll i = 0; quick_power(k, i)<=r ; i++) {ll num = quick_power(k,i);if(num>=l) {cout <<(flag?"":" ")<< num;flag = false;}if(num > r/k) break;}if(flag) cout << -1; return 0; }代碼二(樸素求法)
#include<iostream> #include<cmath> using namespace std; typedef unsigned long long llu; int main( ) {llu l, r, k; cin>>l>>r>>k;llu t = 1, flag=0;while(t <= r) {if(t>=l) { cout << t << ' '; flag = 1; }if(t>r/k) break;t*=k; }if(!flag) cout << -1; return 0; }這世界就是,一些人總在晝夜不停的努力,而另外一些人,起床就發現世界已經變了。
總結
以上是生活随笔為你收集整理的15行代码AC——Link/Cut Tree CodeForces - 614A(爆long long处理+快速幂讲解)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 14行代码AC_Break the Ch
- 下一篇: Benelux Algorithm Pr