HDU - 4611 A - Balls Rearrangement

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

题目说的很简单,就是放球的问题,归为数学问题就是让你求一下abs(i%a-i%a),当i<x是的所有的和,思想很容易想到a,b的最小公倍数为一个循环节,但当这两个数都很大的时候他们的最小公倍数也是很大的,所以需要考虑一下再继续优化,这是在纸上写一写数。你就会发现这些数有一些规律,在一些相邻的区间上差值是一样的,这时就考虑可不可以一个区间一个区间的去求值呢,但是自己还是很菜在打比赛的时候没能写出来的,鬼节原因还是自己比较狭隘,不够大气,还是不能从整体上上看待一个问题,只是一点点拼凑,但是做的题多了就会发现这种思想是不可取的,做题一定要从总体上把握题目,。。。。

赛后看了题解,发现博主只用了区区几行代码就把我比赛时没敲出来的代码写出来,很是钦佩,但一看代码就只有一个感觉,还是自己太菜!其实做法很简单,但是脑子里的思路一定要清晰

ac代码:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
long long gcd(long long a,long long b)
{
    return b?gcd(b,a%b):a;
}
long long lcm(long long a,long long b)
{
    return a/gcd(a,b)*b;
}
long long right(long long a,long long b,long long x)
{
    long long tmp,i,s;
	i=0;s=0;
	while(i<x)
	{
		tmp=min(a-i%a,b-i%b);
		if(tmp+i >= x)
			tmp=x-i;
		s+=abs(i%a-i%b)*tmp;
		i+=tmp;
	}
	return s;
}
int main()
{
    long long x,a,b,sum,h;
    cin>>h;
    while(h--)
    {
        cin>>x>>a>>b;
        if(a>b)
        {
            long long t=a;
            a=b;
            b=t;
        }
      sum=0;
      long long y=lcm(a,b);
      if(x<y)
      sum=right(a,b,x);
      else
      sum=x/y*right(a,b,y)+right(a,b,x%y);
      cout<<sum<<endl;
    }
    return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值