[hdu 4611]Balls Rearrangement 数论

Balls Rearrangement

Time Limit: 9000/3000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others)
Total Submission(s): 2376    Accepted Submission(s): 864


Problem 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
 

Source
 


这一题我的思路是利用类似中国余数定理的取模表的原理,每次都填充下一个对角线的内容,而对于大于lcm(a,b)的部分直接重复计算即可。


#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <vector>
#define INF 999999999.9
#define PI acos(-1.0)
using namespace std;
struct lines{
	long long be,en;
	long long x,num,tot;
}l[200005];

long long gcd(long long x,long long y)
{
	if (y==0) return x;
	return gcd(y,x%y);
}
long long lcm(long long x,long long y)
{
	return x/gcd(x,y)*y;
}
int main()
{
	int T_T; 
	long long q,n,m,cir,ans,tim;
	scanf("%d",&T_T);
	while (T_T--)
	{
		scanf("%I64d%I64d%I64d",&q,&n,&m); 
		if (n>m) swap(n,m);
		memset(l,0,sizeof(l));
		for (long long i=1;i<=m;i++)
			{
			l[i].x=min(i,n);
			l[i].tot=(m-i)*l[i].x;
			}
		for (long long i=m+1;i<=m+n-1;i++)
		{
			l[i].x=min(m+n-i,m);
			l[i].tot=(i-m)*l[i].x;
		}
		long long cur=1,fu=m;
		while (1)
			{
				l[fu].be=cur;
				cur+=l[fu].x;
				l[fu].en=cur-1;
				fu=fu-min(n,m);
				if (fu==0) break;
				if (fu<0) fu+=m+n;
			}
		cir=ans=0;
		tim=q/lcm(n,m);
		q%=lcm(n,m);
		for (long long i=1;i<=n+m-1;i++)
		{
			
			if (l[i].en)
			cir+=l[i].tot;
			if (l[i].en)
			if (q>l[i].en) ans+=l[i].tot;
			if (q)
			if (q<=l[i].en&&q>=l[i].be) ans+=l[i].tot/l[i].x*(q-l[i].be+1);
		}
		ans+=tim*cir;
		printf("%I64d\n",ans);
	}
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值