CodeForces 382 B.Number Busters(鸽巢定理)

Description
给出五个整数a,b,w,x,c,每秒c=c-1,如果b>=x,则b-=x,否则a=a-1,b=w-(x-b),问几秒后c<=a
Input
五个整数a,b,w,x,c(1<=a<=2e9,1<=w<=1000,0<=b < w,0 < x < w,1<=c<=2e9)
Output
输出c<=a所需时间
Sample Input
4 2 3 1 6
Sample Output
2
Solution
由于在运算过程中b始终介于[0,w)之间,由鸽巢定理经过一段时间后b的值会重复,进而出现循环,那么找出该循环后求出一个循环内a的减少量,那么中间的那些循环就可以O(1)的计算,之后不到一个循环暴力跑一遍即可
Code

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
#define INF 0x3f3f3f3f
#define maxn 1111
ll a,b,c,x,w;
int flag[maxn];
ll Solve()
{
    if(c<=a)return 0;
    memset(flag,-1,sizeof(flag));
    ll res=0,len;
    while(1)
    {
        res++,c--;
        if(b>=x)b-=x;
        else a--,b=w-(x-b);
        if(c<=a)return res;
        if(flag[b]!=-1)
        {
            len=res-flag[b];
            break;
        }
        flag[b]=res;
    }
    ll cnt=0;
    for(int i=1;i<=len;i++)
    {
        if(b>=x)b-=x;
        else cnt++,b=w-(x-b);
    }
    ll ans=(c-a-1)/(len-cnt);
    c-=ans*len,a-=ans*cnt,ans=ans*len+res;
    while(c>a)
    {
        ans++,c--;
        if(b>=x)b-=x;
        else a--,b=w-(x-b);
    }
    return ans;
}
int main()
{
    while(~scanf("%I64d%I64d%I64d%I64d%I64d",&a,&b,&w,&x,&c))
        printf("%I64d\n",Solve());
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值