本文主要是介绍N-Dimensional Grid ——线性逆元,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
You are given an n-dimensional grid in which the dimensions of the grid are a1?×?a2?×?…?×?an. Each cell in the grid is represented as an n-tuple (x1,?x2,?…,?xn) (1?≤?xi?≤?ai).
Two cells are considered to be adjacent if the Manhattan Distance between them is equal to 1. The Manhattan Distance between two cells X(x1,?x2,?…,?xn) and Y(y1,?y2,?…,?yn) is equal to: |x1?-?y1|?+?|x2?-?y2|?+?…?+?|xn?-?yn|.
Your task is to count how many pairs of cells are adjacents. Can you? Two pairs of cells are considered the same if they include the same cells, i.e the pair (c1,?c2)is the same as (c2,?c1).
Input
The first line contains an integer T (1?≤?T?≤?100) specifying the number of test cases.
The first line of each test case contains an integer n (1?≤?n?≤?105), in which n is the number of dimensions of the grid. Then a line follows containing n integers a1,?…,?an (1?≤?ai?≤?105), in which ai is the size of the ith dimension.
The sum of n overall test cases does not exceed 6?×?106.
Output
For each test case, print a single line containing the number of pairs of adjacent cells modulo 109?+?7.
Example
Input
1
3
1 2 3
Output
7
Note
The absolute value |x| of a real number x is the non-negative value of x without regard to its sign. Namely, |x| = x for a positive x, |x| = ?-?x for a negative x (in which case ?-?x is positive), and |0| = 0. For example, the absolute value of 3 is 3, and the absolute value of ?-?3 is also 3. The absolute value of a number may be thought of as its distance from zero.
在比赛的时候连题意都没看懂,
结束之后听旁边的人说的,a[i]是约束条件,就是说样例之中不能出现大于123的点,211这种。
之后就好办了,我们可以发现曼哈顿距离为1的时候,必然是有两个数是相同的,另一个数有(n-1)
种组合,所以结果是(a-1)b*c+a(b-1)c+a*b(c-1);
但是一个一个算太麻烦了,所以可以用逆元=a*b*c*(a-1)/a;
然而每一次都算一遍逆元的话会t,所以需要一个东西叫做线性逆元,就是说在p之内的所有逆元
都可以算出来,公式是a[i]=(mod-mod/i)*a[mod%i]%mod;
a[1]=1;
#include<bits/stdc++.h>using namespace std;#define ll long long#define mod 1000000007ll a[100005];ll ny[100005];void init(){ny[1]=1;for(int i=2;i<=100000;i++)ny[i]=((mod-(mod/i))*ny[mod%i])%mod;}int main(){int t;scanf("%d",&t);init();while(t--){int n;scanf("%d",&n);ll ans=1,sum=0;for(int i=1;i<=n;i++){scanf("%lld",&a[i]);ans=(ans*a[i])%mod;}for(int i=1;i<=n;i++){sum=(sum+(ans*(a[i]-1)%mod*ny[a[i]])%mod)%mod;}printf("%lld\n",sum);}return 0;}
这篇关于N-Dimensional Grid ——线性逆元的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!