码迷,mamicode.com
首页 > 其他好文 > 详细

N-Dimensional Grid

时间:2018-07-29 18:51:37      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:pre   for   std   ted   NPU   end   each   Dimension   开始   

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.

题目大意

输入多个样例,每个样例为N维空间,统计N维空间中有多少对相邻点。

解题思路

从一维开始思考,每增加一维的变化,推导出公式。
每增加一维,相邻点的总数就变为前面的相邻点的对数乘以该维长度再加上每一维之间新产生的,即前面的点数乘以当前维的长度-1。

代码

#include <bits/stdc++.h>
using namespace std;
int a[100005];
int main()
{
    int t;
    cin >> t;
    while(t--)
    {
        int x;
        cin >> x;
        for(int i = 0; i < x; i++)
            scanf("%d", &a[i]);
       unsigned long long point = a[0];  //总点数
       unsigned long long ans = a[0] - 1;
        for(int i = 1; i < x; i++)
        {
            
            ans = ans * a[i] + point * (a[i] - 1);
            point *= a[i];
            ans %= 1000000007;
            point %= 1000000007;
        }
        cout << ans << endl;
    }
    return 0;
}

总结

忘了要取模。

N-Dimensional Grid

标签:pre   for   std   ted   NPU   end   each   Dimension   开始   

原文地址:https://www.cnblogs.com/wanghn-blog/p/9386119.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!