洛谷 P2312 解方程(数学||秦九昭)

题目链接:https://www.luogu.com.cn/problem/P2312

秦九昭算法模板。

秦九昭算法:https://baike.baidu.com/item/%E7%A7%A6%E4%B9%9D%E9%9F%B6%E7%AE%97%E6%B3%95/449196?fr=aladdin

将多项式

 化成

 

 

 

 

 

求多项式的值时,首先计算最内层括号内一次多项式的值,即
$v_1=a_n*x+a_{n-1}$
然后由内向外逐层计算一次多项式的值,即
 
 
这样,求n次多项式f(x)的值就转化为求n个一次多项式的值。
结论:对于一个n次多项式,至多做n次乘法和n次加法。

关于这道题:

首先用字符串读入,然后mod一个大质数,使它保存下来。然后枚举每一个数,如果带入经过秦九昭算法处理过的式子中,这个式子为0,那么就记录下来。

AC代码:

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 using namespace std;
 5 typedef long long ll;
 6 const int mod=998244353;
 7 ll n,m,cnt;
 8 ll a[110];
 9 ll ans[105];
10 string str;
11 bool judge(ll x){
12     ll v=(a[n]*x+a[n-1])%mod;
13     for(int i=n-2;i>=0;i--) v=(v*x+a[i])%mod;
14     if(v==0) return 1;
15     return 0;
16 }
17 int main(){
18     scanf("%lld%lld",&n,&m);
19     for(int i=0;i<=n;i++){
20         cin>>str;
21         int len=str.length();
22         if(str[0]=='-') for(int j=1;j<len;j++) a[i]=(a[i]*10+(str[j]-'0'))%mod; 
23         else{
24             for(int j=0;j<len;j++) a[i]=(a[i]*10+(str[j]-'0'))%mod;
25             a[i]=-a[i];
26         }
27     }
28     for(int i=1;i<=m;i++) if(judge(i)) ans[++cnt]=i;
29     printf("%lld
",cnt);
30     for(int i=1;i<=cnt;i++) printf("%lld
",ans[i]);
31     return 0;
32 }
AC代码
原文地址:https://www.cnblogs.com/New-ljx/p/13910750.html