AtCoder Beginner Contest 171 D - Replacing
阿新 • • 發佈:2020-07-15
Time Limit: 2 sec / Memory Limit: 1024 MB
Score :400400points
Problem Statement
You have a sequenceAAcomposed ofNNpositive integers:A1,A2,⋯,ANA1,A2,⋯,AN.
You will now successively do the followingQQoperations:
- In theii-th operation, you replace every element whose value isBiBiwithCiCi.
For each ii(1≤i≤Q)(1≤i≤Q), findSiSi: the sum of all elements inAAjust after theii-th operation.
Constraints
- All values in input are integers.
- 1≤N,Q,Ai,Bi,Ci≤1051≤N,Q,Ai,Bi,Ci≤105
- Bi≠CiBi≠Ci
Input
Input is given from Standard Input in the following format:
NN A1A1 A2A2 ⋯⋯ ANANQQ B1B1 C1C1 B2B2 C2C2 ⋮⋮ BQBQ CQCQ
Output
PrintQQintegersSiSito Standard Output in the following format:
S1S1 S2S2 ⋮⋮ SQSQ
Note thatSiSimay not fit into a3232-bit integer.
Sample Input 1Copy
Copy4 1 2 3 4 3 1 2 3 4 2 4
Sample Output 1Copy
Copy11 12 16
Initially, the sequenceAAis1,2,3,41,2,3,4 .
After each operation, it becomes the following:
- 2,2,3,42,2,3,4
- 2,2,4,42,2,4,4
- 4,4,4,44,4,4,4
Sample Input 2Copy
Copy4 1 1 1 1 3 1 2 2 1 3 5
Sample Output 2Copy
Copy8 4 4
Note that the sequenceAAmay not contain an element whose value isBiBi.
Sample Input 3Copy
Copy2 1 2 3 1 100 2 100 100 1000
Sample Output 3Copy
Copy102 200 2000
題意:輸入一個n,然後輸入n個數字,再輸入一個Q,接下來Q行每行輸入一個B和C,然後將陣列中所有的B換成C,然後把新陣列的和輸出
題解:開一個數組b,用來儲存陣列元素中出現的次數,我們在輸入陣列的元素的時候,先用sum把每個元素加起來,然後陣列b中a【i】元素出現的次數++(這樣能讓我們在後面O(1)的時間算出新陣列的總和)
每次B,C輸入的時候其實直接用公式sum=sum-(C-B)*b[B];求出sum,然後將陣列b更新一下。
程式碼如下:
#include<cstdio> #include<iostream> #define maxn 100005 #define ll long long using namespace std; ll n,q,a[maxn],sum; int tm[maxn]; int main(void) { while(~scanf("%lld",&n)) { sum=0; for(int i=0;i<n;++i) { scanf("%lld",&a[i]); sum+=a[i];//求和 tm[a[i]]++;//a[i]出現的次數自增 } scanf("%lld",&q); ll b,c; for(int i=0;i<q;++i) { scanf("%lld %lld",&b,&c); sum+=(c-b)*tm[b]; tm[c]+=tm[b];//更新tm[c] tm[b]=0;//更新tm[b] printf("%lld\n",sum); } } return 0; }