题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1111
But an almost unknown archaeologist has obtained a copy of the code something during the 18th century. He was afraid that the code could get to the ``wrong people'' so he has encoded the numbers in a very special way. He took a random complex number B that was greater (in absolute value) than any of the encoded numbers. Then he counted the numbers as the digits of the system with basis B. That means the sequence of numbers an, an-1, ..., a1, a0 was encoded as the number X = a0 + a1B + a2B2 + ...+ anBn.
Your goal is to decrypt the secret code, i.e. to express a given number X in the number system to the base B. In other words, given the numbers X and Byou are to determine the ``digit'' a0 through an.
for all i in {0, 1, 2, ...n}: 0 <= ai < |B|
X = a0 + a1B + a2B2 + ...+ anBn
if n > 0 then an <> 0
n <= 100
If there are no numbers meeting these criteria, output the sentence "The code cannot be decrypted.". If there are more possibilities, print any of them.
把一个n次多项式f(x)=a[n]x^n+a[n-1]x^(n-1)+......+a[1]x+a[0]
改写成如下形式:
f(x)=a[n]x^n+a[n-1]x^(n-1))+......+a[1]x+a[0]
=(a[n]x^(n-1)+a[n-1]x^(n-2)+......+a[1])x+a[0]
=((a[n]x^(n-2)+a[n-1]x^(n-3)+......+a[2])x+a[1])x+a[0]
=...... =(......((a[n]x+a[n-1])x+a[n-2])x+......+a[1])x+a[0].
求多项式的值时,首先计算最内层括号内一次多项式的值,即 v[1]=a[n]x+a[n-1]然后由内向外逐层计算一次多项式的值,即 v[2]=v[1]x+a[n-2] v[3]=v[2]x+a[n-3] ...... v[n]=v[n-1]x+a[0]这样,求n次多项式f(x)的值就转化为求n个一次多项式的值。(注:中括号里的数表示下标)上述方法称为秦九韶算法。直到今天,这种算法仍是多项式求值比较先进的算法
复数的除法::令t=c*c+d*d,(a+bi)/(c+di)=(ac+bd)/t+(bc-ad)/ti
然后深搜枚举a0~an,每次减去ai之后除以b后,剩下的就又有一个常数,直到0为止。除法的时候,由于要保证整除(就是上面的ac+bd和bc-ad是t的倍数),可以减少很多时间
代码如下
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #include <stdio.h> 2 typedef __int64 LL; 3 LL xr, xi, br, bi, sq, ans[101]; 4 int flag, k; 5 //---------秦九韶算法---------- 6 void dfs(int step, LL real, LL com){ 7 LL tx, ty; 8 if (step > 100 || flag) return; 9 if (!real && !com){ 10 flag = 1; 11 k = step; 12 return; 13 } 14 //复数除法 --t=c*c+d*d, (a+bi)/(c+di)=(ac+bd)/t+(bc-ad)/ti---- 15 for (int i = 0; i*i < sq; i++){ 16 tx = (real - i)*br + com*bi; 17 ty = -(real - i)*bi + com*br; 18 ans[step] = i; 19 if (!(tx%sq) && !(ty%sq)) 20 dfs(step + 1, tx / sq, ty / sq); 21 if (flag) return; 22 } 23 } 24 int main(){ 25 int i, t; 26 scanf("%d", &t); 27 while (t--){ 28 flag = 0; 29 scanf("%I64d%I64d%I64d%I64d", &xr, &xi, &br, &bi); 30 sq = br*br + bi*bi; 31 dfs(0, xr, xi); 32 if (!flag) 33 printf("The code cannot be decrypted.\n"); 34 else{ 35 printf("%d", ans[k - 1]); 36 for (i = k - 2; i >= 0; i--) 37 printf(",%I64d", ans[i]); 38 printf("\n"); 39 } 40 } 41 return 0; 42 }