CodeForces - 227C:Flying Saucer Segments(快速幂)

Discription
An expedition group flew from planet ACM-1 to Earth in order to study the bipedal species (its representatives don’t even have antennas on their heads!).

The flying saucer, on which the brave pioneers set off, consists of three sections. These sections are connected by a chain: the 1-st section is adjacent only to the 2-nd one, the 2-nd one — to the 1-st and the 3-rd ones, the 3-rd one — only to the 2-nd one. The transitions are possible only between the adjacent sections.

The spacecraft team consists of n aliens. Each of them is given a rank — an integer from 1 to n. The ranks of all astronauts are distinct. The rules established on the Saucer, state that an alien may move from section a to section b only if it is senior in rank to all aliens who are in the segments a and b (besides, the segments a and b are of course required to be adjacent). Any alien requires exactly 1 minute to make a move. Besides, safety regulations require that no more than one alien moved at the same minute along the ship.

Alien A is senior in rank to alien B, if the number indicating rank A, is more than the corresponding number for B.

At the moment the whole saucer team is in the 3-rd segment. They all need to move to the 1-st segment. One member of the crew, the alien with the identification number CFR-140, decided to calculate the minimum time (in minutes) they will need to perform this task.

Help CFR-140, figure out the minimum time (in minutes) that all the astronauts will need to move from the 3-rd segment to the 1-st one. Since this number can be rather large, count it modulo m.

Input
The first line contains two space-separated integers: n and m (1 ≤ n, m ≤ 109) — the number of aliens on the saucer and the number, modulo which you should print the answer, correspondingly.

Output
Print a single number — the answer to the problem modulo m.

Examples
Input
1 10
Output
2
Input
3 8
Output
2
在这里插入图片描述
题目大意
要将n个数从3移动到1,每次只能走一步,且等级高的先移动,问需要多少部所有的人才能全部从3走到1,结果需要模m

思路
根据样例,可以找到规律,步数和就是2*3^(n-1)的前缀和,由于数据量过大,需要用快速幂求解,而求前缀和即求等比数列前n项和再模m就可以。注意要特判模之后为负数的情况,要再加一个m

AC代码

#include<bits/stdc++.h>
using namespace std;
long long n,m;
int qmi(long long m, long long k, long long p)
{
    long long res = 1, t = m;
    while (k)
    {
        if (k&1) res = res * t % p;
        t = t * t % p;
        k >>= 1;
    }
    return res;
}
int main()
{
    cin>>n>>m;
    long long ans;
    ans=qmi(3,n,m);
    long long sum=(ans-1)%m;
    if(sum>=0)
    cout<<sum<<endl;
    else
        cout<<sum+m<<endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值