You are given an array A initially comprising of N non-negative integers A[1], A[2], A[3]..... A[N]. An array B can be generated from array A in the following manner :
for(i=1;i<=N;i++)
{
B[i]=1;
for(j=1;j<=N;j++)
{
if(i!=j)
{
B[i]=B[i]*A[j];
}
}
}
You will now be given Q queries, each query being either of the two types :
Type 1 : 0 ID V : Set A[ID] = V
Type 2: 1 ID: Generate the array B from the current array A and print the value of B[ID] modulo 10^9 + 7.
You must do as directed in each query.
NOTE: Both array A and array B are 1-indexed.
Example:
Input: n = 5, a = {1, 2, 3, 4, 5}, q = 3, queries = {{1, 3}, {0, 2, 4}, {1, 4}}
Output:
40 60
Approach:
C++
#include <bits/stdc++.h>using namespace std;#define mod 1000000007long long mpow(long long a, long long b){if (b == 0)return 1;if (b == 1)return a % mod;long long x = mpow(a, b / 2) % mod;long long y = (x * x) % mod;if (b % 2 == 1){long long res = (a % mod * y) % mod;return res;}return y;}void atoB(long long n, vector<long long> a, long long q,vector<vector<long long>> queries){long long p = 1, zc = 0;for (int i = 0; i < n; i++){if (a[i] != 0)p = (p * a[i]) % mod;elsezc++;}for (int i = 0; i < q; i++){long long type = queries[i][0];if (type == 1){long long id = queries[i][1];id--;if (a[id] == 0 and zc == 1)cout << p << "\n";if (a[id] == 0 and zc > 1)cout << 0 << "\n";if (a[id] != 0 and zc > 0)cout << 0 << "\n";if (a[id] != 0 and zc == 0){long long res = (p * mpow(a[id], mod - 2)) % mod;cout << res << "\n";}}else{long long id = queries[i][1];long long x = queries[i][2];id--;if (a[id] == 0 and x != 0){a[id] = x;p = (p * x) % mod;zc--;}if (a[id] != 0 and x == 0){p = (p * mpow(a[id], mod - 2)) % mod;zc++;a[id] = 0;}if (a[id] != 0 and x != 0){p = (p * x) % mod;p = (p * mpow(a[id], mod - 2)) % mod;a[id] = x;}}}}int main(){long long n = 5;vector<long long> a = {1, 2, 3, 4, 5};long long q = 3;vector<vector<long long>> queries = {{1, 3},{0, 2, 4},{1, 4}};atoB(n, a, q, queries);return 0;}
No comments:
Post a Comment