J 建設道路

題目描述

牛牛國有 nnn 個城市,編號爲 1−n1-n1−n,第 iii 個城市有一個價值 aia_iai​,牛國的國王牛闊落特別喜歡在牛牛國旅遊,並且他不想每次旅遊的時候都計算一遍走哪條路最短,於是他決定在任意兩個城市之間建立一條雙向道路,在第 iii 座城市和第 jjj 座城市之間建立雙向道路的代價是 (ai−aj)2(a_i-a_j)^2(ai​−aj​)2,牛闊落希望你能算出這項工程的花費。由於答案太大,你只需要輸出答案模 1e9+71e9+71e9+7 的餘數

輸入描述:

第一行一個整數 nnn,表示城市的數量。

第二行 nnn 以空格分隔的整數 a1,a2,…,ana1,a2,…,ana1,a2,…,an,表示第i座城市的價值。

輸出描述:

輸出一行一個數字,表示工程的花費模 1e9+71e9+71e9+7 的餘數

示例1

輸入

3
1 2 3

輸出

6

說明

城市1到城市2的道路價值是(2 - 1)^ 2 = 1

城市2到城市3的道路價值是(3 - 2)^ 2 = 1
城市1到城市3的道路價值是(3 - 1)^ 2 = 4
總的花費 = 1 + 1 + 4 = 6

備註:

1≤n≤5e51\leq n\leq 5e51≤n≤5e5
1≤ai≤1e91\leq a_i\leq 1e91≤ai​≤1e9
建議使用 scanf 讀入

注意負數取模,這點被坑了。。

#include <iostream>
#include <cmath>
#include <cstring>
#include <queue>
#include <algorithm>
#include <map>
using namespace std;

typedef long long ll;
const int maxn = 5e5 + 10;
const int mod = 1e9 + 7;
int n;
ll a[maxn];
ll sum[maxn];

int main() {
	cin >> n;
	for(int i = 1; i <= n; i++)
		cin >> a[i];
	for(int i = n; i >= 1; i--) {
		sum[i] = sum[i + 1] + a[i];	
		sum[i] %= mod;
	}
	ll ans = 0;
	for(int i = 1; i <= n; i++) {
		ans += (a[i] * (n - 1) % mod ) * a[i] % mod;
		ans %= mod;
	
		ll tem = 2 * sum[i + 1] % mod * a[i] % mod;
		tem %= mod;
		ans -= tem;
		ans += mod;
		ans %= mod; //長記性了!一直wa,最後才發現是負數取模的問題
	}
	cout << ans;
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章