日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

15行代码AC——Link/Cut Tree CodeForces - 614A(爆long long处理+快速幂讲解)

發(fā)布時間:2024/2/28 编程问答 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 15行代码AC——Link/Cut Tree CodeForces - 614A(爆long long处理+快速幂讲解) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

勵志用少的代碼做高效表達


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]區(qū)間內(nèi)的k的冪次。
如:輸入1,10,2 輸出1 2 4 8

分析:求冪次不必多說,pow()累乘快速冪都可以。
但在求解過程中,會出現(xiàn)爆long long的情況, 如:k的n次冪=10^18, k=1000, 此時若繼續(xù)計算,就會出現(xiàn)10^21 的數(shù)。超過了long long的取值范圍,連unsigned long long都無法儲存。

解決辦法是:乘法變除法。

如:將式if(pow(k, i) <= r ) 改為:if(pow(k,i-1) <= r/k) 這樣就可以在long long的范圍內(nèi)取值了。

下面列出兩種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; }

這世界就是,一些人總在晝夜不停的努力,而另外一些人,起床就發(fā)現(xiàn)世界已經(jīng)變了。

總結(jié)

以上是生活随笔為你收集整理的15行代码AC——Link/Cut Tree CodeForces - 614A(爆long long处理+快速幂讲解)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。