hdoj 5478 Can you find it 【找恒等式 + 快速幂】

来源:互联网 发布:网络嗅探器 安卓 编辑:程序博客网 时间:2024/05/01 13:18



Can you find it

Time Limit: 8000/5000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 504    Accepted Submission(s): 230


Problem Description
Given a prime number C(1C2×105), and three integers k1, b1, k2 (1k1,k2,b1109). Please find all pairs (a, b) which satisfied the equation ak1n+b1 + bk2nk2+1 = 0 (mod C)(n = 1, 2, 3, ...).
 

Input
There are multiple test cases (no more than 30). For each test, a single line contains four integers C, k1, b1, k2.
 

Output
First, please output "Case #k: ", k is the number of test case. See sample output for more detail.
Please output all pairs (a, b) in lexicographical order. (1a,b<C). If there is not a pair (a, b), please output -1.
 

Sample Input
23 1 1 2
 

Sample Output
Case #1:1 22
 



题意:让你找出所有满足


ak1n+b1 + bk2nk2+1 = 0 (mod C)(n = 1, 2, 3, ...).  的整数对(a, b),其中1 <= a, b < C。 

若存在,则按字典序输出,否则输出-1。




由于等式对所有的n >= 1均满足,我们可以先考虑特殊的情况。

n 为 1时,有a ^ (k1+b1) + b = 0 (mod C);等式1

n 为 2时,有a ^ (2*k1+b1) + b ^ (k2 + 1) = 0 (mod C);等式2

...

我们让等式1两边同乘a ^ k1,得到a ^ (2*k1 + b1) + b * a ^ k1 = 0 (mod C)。

与等式2结合,可以得到a ^ k1 = b ^ k2,这样我们只需枚举所有满足该等式的(a, b)就ok了。

显然 C ^ C的复杂度是不可取的的,由于a ^ (k1 + b1) + b = 0 (mod C),我们只需枚举a的值,根据a的值求出b,判断a ^ k1 和 b ^ k2就可以了。


AC代码:


#include <cstdio>#include <cstring>#include <algorithm>#define LL long longusing namespace std;LL pow_mod(LL a, LL n, LL m){    LL ans = 1;    while(n)    {        if(n & 1)            ans = ans * a % m;        a = a * a % m;        n >>= 1;    }    return ans;}int main(){    int k = 1;    LL c, k1, b1, k2;    while(scanf("%lld%lld%lld%lld", &c, &k1, &b1, &k2) != EOF)    {        printf("Case #%d:\n", k++);        bool flag = false;        for(int i = 1; i < c; i++)        {            int j = c - pow_mod(i, k1+b1, c);            if(pow_mod(i, k1, c) == pow_mod(j, k2, c))            {                flag = true;                printf("%d %d\n", i, j);            }        }        if(!flag)            printf("-1\n");    }    return 0;}


0 0
原创粉丝点击