[ZZOJ#31]类欧几里得
[ZZOJ#31]類歐幾里得
試題描述
這是一道模板題。
給出 \(a, b, c, n\),請(qǐng)你求出 \(\sum_{x=0}^n{\lfloor \frac{a \cdot x + b}{c} \rfloor}\)
輸入
一行四個(gè)正整數(shù) \(a, b, c, n\)。
輸出
一個(gè)整數(shù)表示答案。
輸入示例1
10 7 3 3輸出示例1
28輸入示例2
36976101 240442820 735275034 66441189輸出示例2
110998229606855數(shù)據(jù)規(guī)模及約定
對(duì)于 \(50\%\) 的數(shù)據(jù),有 \(n \le 10^7\)
對(duì)于 \(100\%\) 的數(shù)據(jù),保證 \(a, b, c, n \le 10^9\),答案不會(huì)超過(guò) \(9223372036854775807\)(int64 最大值)。
題解
以前出出來(lái)的,發(fā)現(xiàn)忘記寫博客了,來(lái)補(bǔ)個(gè)坑。
類歐模板。講解隨便就能百度到。
主要思路就是數(shù)形結(jié)合,將此題轉(zhuǎn)化成“求直線下方整點(diǎn)個(gè)數(shù)”。對(duì)于 \(c \ge a\) 或 \(b \ge a\) 的情況,將整數(shù)部分 \(\lfloor \frac{c}{a} \rfloor\) 和 \(\lfloor \frac{b}{a} \rfloor\) 先算出來(lái),再考慮補(bǔ)上沒記上的部分,于是將問(wèn)題變成了 \(b, c < a\) 的情況。對(duì)于這個(gè)情況,就是求一個(gè)直角梯形內(nèi)部整點(diǎn)個(gè)數(shù)(這個(gè)直角梯形 \(y\) 軸上結(jié)局和斜率都小于 \(1\) 的性質(zhì)保證后面的子問(wèn)題規(guī)模會(huì)縮小),我們考慮不按 \(x\) 坐標(biāo)枚舉,變成按 \(y\) 坐標(biāo)枚舉,推一推式子發(fā)現(xiàn)能轉(zhuǎn)化成子問(wèn)題。
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <cctype> #include <algorithm> using namespace std; #define rep(i, s, t) for(int i = (s); i <= (t); i++) #define dwn(i, s, t) for(int i = (s); i >= (t); i--)int read() {int x = 0, f = 1; char c = getchar();while(!isdigit(c)){ if(c == '-') f = -1; c = getchar(); }while(isdigit(c)){ x = x * 10 + c - '0'; c = getchar(); }return x * f; }#define LL long longLL solve(LL a, LL b, LL c, LL n) {if(!n) return b / c;if(n < 0) return 0;if(a >= c || b >= c) return b / c * (n + 1) + a / c * n * (n + 1) / 2 + solve(a % c, b % c, c, n);LL m = (a * n + b) / c;return n * m + m - solve(c, a - b + c - 1, a, m - 1); }int main() {int a = read(), b = read(), c = read(), n = read();printf("%lld\n", solve(a, b, c, n));return 0; }轉(zhuǎn)載于:https://www.cnblogs.com/xiao-ju-ruo-xjr/p/8005645.html
總結(jié)
以上是生活随笔為你收集整理的[ZZOJ#31]类欧几里得的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: linux用户权限
- 下一篇: Java程序员的知识树