1,数据存储:
List<int[]>f:{[ploy1],[ploy2],[ploy3],…}
where[ployi]denotes[系数,x1的指数,x2的指数,x3的指数,…]
2,快速幂 qmi()
由于Math.pow()返回的是Double,转成Long会导致精度丢失
e.g.a13=a(1101)2=a1+a4+a8
private long qmi(long a, long k) {
long res = 1; // 结果初始化为1
while (k > 0) { // 当指数 k 还未变为 0
if ((k & 1) == 1) // 如果 k 的最低位是 1
res = (res * a) % MOD; // 乘上当前 a,并取模
a = (a * a) % MOD; // a 自乘,即 a^2、a^4、a^8...
k >>= 1; // 右移 k,相当于去掉最低位
}
return res;
}
import java.util.*;
class Poly {
List<long[]> f;
static final int MOD = (int) 1e9 + 7;
static int n;
Poly() {
f = new ArrayList<>();
}
Poly(int x) {
this();
long[] a = new long[n + 1];
a[0] = x;
f.add(a);
}
Poly(String str) {
this();
int ind = Integer.parseInt(str.substring(1));
long[] a = new long[n + 1];
a[0] = 1;
a[ind] = 1;
f.add(a);
}
Poly multiply(Poly w) {
Poly res = new Poly();
for (long[] x : f) {
for (long[] y : w.f) {
long[] t = new long[n + 1];
t[0] = (x[0] * y[0]) % MOD;
for (int i = 1; i <= n; i++) t[i] = x[i] + y[i];
res.f.add(t);
}
}
return res;
}
Poly add(Poly w) {
Poly res = new Poly();
res.f.addAll(f);
res.f.addAll(w.f);
return res;
}
Poly diff(int ind) {
Poly res = new Poly();
for (long[] vec : f) {
long[] newVec = vec.clone();
newVec[0] = (newVec[0] * newVec[ind]) % MOD;
newVec[ind]--;
res.f.add(newVec);
}
return res;
}
long eval(List<Integer> v) {
long sum = 0;
for (long[] vec : f) {
long res = vec[0];
if (res == 0) continue;
for (int i = 1; i <= n; i++) {
res = (res * qmi(v.get(i - 1), vec[i])) % MOD;
}
sum = (sum + res) % MOD;
}
return (sum + MOD) % MOD;
}
long qmi(long a, long k)
{
long res = 1;
while(k > 0)
{
if((k & 1) == 1)
{
res = (res * a) % MOD;
}
a = (a * a) % MOD;
k = k >> 1;
}
return res;
}
}
public class Main {
static Stack<Poly> val = new Stack<>();
static int n, m;
public static void calc(String str) {
Poly a = val.pop();
Poly b = val.pop();
if (str.equals("*")) val.push(b.multiply(a));
else if (str.equals("+")) val.push(b.add(a));
else {
for (long[] x : a.f) x[0] = -x[0];
val.push(b.add(a));
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
sc.nextLine();
Poly.n = n;
String formula = sc.nextLine();
String[] tokens = formula.split(" ");
for (String token : tokens) {
if (token.startsWith("x")) {
val.push(new Poly(token));
} else if (token.equals("*") || token.equals("+") || token.equals("-")) {
calc(token);
} else {
val.push(new Poly(Integer.parseInt(token)));
}
}
Poly ff = val.pop();
while (m-- > 0) {
int ind = sc.nextInt();
List<Integer> t = new ArrayList<>();
for (int i = 0; i < n; i++) {
t.add(sc.nextInt());
}
Poly tt = ff.diff(ind);
System.out.println(tt.eval(t));
}
}
}