The variable res can be negative, so just add res = (res + mod)%mod before returning it.
In Python modulo is defined to be positive but in C/C++ you need to be careful with it.
Check your new submission: Submission #16394482 - AtCoder Beginner Contest 177
When all the elements of Array A are positive then where is the chance for res to go negative
When sum becomes more than mod, then value reduces, suppose prefix[n-2] = 10^9+5 and arr[n-1] = 2, in that case prefix[n-1] = 0 and prefix[n-1] - prefix[n-2] < 0. Did you understand it?
It’s always better to add res = (res+mod)%mod in the end.
I got 2 WA when I used C++. Then I implemented the same logic in python and got AC
I got AC in c++… hope this piece of code helps…
//
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long int ull;
const int mod = 1e9+7;
const int INF = INT_MAX;
#define endl “\n”
#define append push_back
#define roastedcoder ios_base::sync_with_stdio(false); cin.tie(NULL);
//__________________________________________________________________
int main() {
roastedcoder
ll n; cin>>n;
ll a[n], dp[n] = {0};
cin>>a[0];
dp[0] = a[0];
for(int i = 1; i<n; i++) {
cin>>a[i];
dp[i] = dp[i-1]+a[i];
}
ll res = 0;
for(int i = 0; i<n; i++) {
res += (((dp[n-1] - dp[i])%mod)*a[i])%mod;
}
cout<<res%mod<<endl;
}
//__________________________________________________________________
1 Like
My solution : “Submission #16321181 - AtCoder Beginner Contest 177”
I make other functions like modmul ,modadd , modsub so that my answer will never wrong bcz of modular arithmetic.
ll modmul(ll a, ll b) {
return ((a%mod) * (b%mod)) % mod;
}
ll modadd(ll a , ll b){
return((a%mod)+(b%mod)+mod)%mod;
}
ll modsub(ll a , ll b){
return((a%mod) - (b%mod) + mod)%mod;
}
1 Like
i have used #define int long long
Did using such function help you in preventing WA.
Yes , and code is clear too , but make your own functions