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 1000000007

ll 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;

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值