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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

HDU 4611 Balls Rearrangement 数学

發布時間:2025/3/20 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 HDU 4611 Balls Rearrangement 数学 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Balls Rearrangement

題目連接:

http://acm.hdu.edu.cn/showproblem.php?pid=4611

Description

  Bob has N balls and A boxes. He numbers the balls from 0 to N-1, and numbers the boxes from 0 to A-1. To find the balls easily, he puts the ball numbered x into the box numbered a if x = a mod A. Some day Bob buys B new boxes, and he wants to rearrange the balls from the old boxes to the new boxes. The new boxes are numbered from 0 to B-1. After the rearrangement, the ball numbered x should be in the box number b if x = b mod B.
  This work may be very boring, so he wants to know the cost before the rearrangement. If he moves a ball from the old box numbered a to the new box numbered b, the cost he considered would be |a-b|. The total cost is the sum of the cost to move every ball, and it is what Bob is interested in now.
  

Input

The first line of the input is an integer T, the number of test cases.(0<T<=50)
  Then T test case followed. The only line of each test case are three integers N, A and B.(1<=N<=1000000000, 1<=A,B<=100000).
  

Output

For each test case, output the total cost.

Sample Input

3
1000000000 1 1
8 2 4
11 5 3

Sample Output

0
8
16

Hint

題意

有n個數,給你a和b

T1[i]=i%a,T2[i]=i%b

求sigma(T1[i]-T2[i])

題解:

簡單思考一下,他們之間的差一開始都是0的,當遇到某個數是a的倍數的時候,他們之間每個數的差就會增加a,遇到某個數是b的倍數的時候,差就會減少b

根據這個去跑一個lcm周期的答案就好了

然后再暴力算最后一個n%lcm的答案就好了

代碼

#include<bits/stdc++.h> using namespace std;long long gcd(long long a,long long b) {if(b==0)return a;return gcd(b,a%b); } long long lcm(long long a,long long b) {return a*b/gcd(a,b); } vector<long long>p; void init() {p.clear(); } void solve() {init();long long n,a,b;cin>>n>>a>>b;long long c = lcm(a,b);for(long long i=1;i*a<=c;p.push_back(i*a),i++);for(long long i=1;i*b<=c;p.push_back(i*b),i++);p.push_back(0);sort(p.begin(),p.end());p.erase(unique(p.begin(),p.end()),p.end());long long ans = 0,now = 0;for(int i=1;i<p.size()-1;i++){if(p[i]%a==0)now-=a;if(p[i]%b==0)now+=b;ans+=abs(now)*(p[i+1]-p[i]);}long long k = n/c;long long Ans = 0;Ans = Ans + k*ans;k = n%c;int kkk = 0;for(int i=0;i<p.size()-1&&p[i+1]<k;i++){kkk = i+1;if(p[i]%a==0)now-=a;if(p[i]%b==0)now+=b;Ans+=abs(now)*(p[i+1]-p[i]);}if(p[kkk]%a==0)now-=a;if(p[kkk]%b==0)now+=b;Ans+=abs(now)*(k-p[kkk]);cout<<Ans<<endl; } int main() {int t;scanf("%d",&t);while(t--)solve();return 0; }

總結

以上是生活随笔為你收集整理的HDU 4611 Balls Rearrangement 数学的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。