Problem Statement
You have a sequence A composed of N positive integers: 1,2,⋯,A1,A2,⋯,AN.
You will now successively do the following Q operations:
- In the i-th operation, you replace every element whose value is Bi withCi.
For each i (1≤i≤Q), find Si: the sum of all elements in A just after the i-th operation.
Constraints
- All values in input are integers.
- 1≤N,Q,Ai,Bi,Ci≤105
- Bi!=Ci
Input
Input is given from Standard Input in the following format:
N 1A1 2A2 ⋯⋯ AN Q B1 C1 B2 C2 ⋮⋮ BQ CQ
Output
Print Q integers Si to Standard Output in the following format:
S1 S2 ⋮⋮ SQ
Note that Si may not fit into a 3232-bit integer.
Sample 1
Input | Output |
---|---|
4 1 2 3 4 3 1 2 3 4 2 4 | 11 12 16 |
Initially, the sequence A is 1,2,3,41,2,3,4.
After each operation, it becomes the following:
- 2,2,3,4
- 2,2,4,4
- 4,4,4,4
Sample 2
Input | Output |
---|---|
4 1 1 1 1 3 1 2 2 1 3 5 | 8 4 4 |
Note that the sequenceA may not contain an element whose value is Bi.
Sample 3
Inputcopy | Outputcopy |
---|---|
2 1 2 3 1 100 2 100 100 1000 | 102 200 2000 |
题目分析&解题思路:
每次输入a,b把数组当中所有的a全部换成b,那么对于所有数的和来说就是加上(b-a)*a的个数,然后再更新b的个数和a的个数就行
代码:
#include<bits/stdc++.h>
#define _for(a,b) for(int i=a;i<=b;i++)
#define for_(a,b) for(int i=a;i>=b;i--)
#define pii pair<int,int>
#define use int T;cin>>T;while(T--)
using namespace std;
const int N =1e5+6;
int ar[N];
int cnt[N];
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);cout.tie(0);
int n;
cin>>n;
long long sum=0;
_for(1,n)
{
cin>>ar[i];
cnt[ar[i]]++;
sum+=ar[i];
}
int q;cin>>q;
while(q--)
{
int a,b;cin>>a>>b;
if(cnt[a]!=0)
{
sum+=(b-a)*cnt[a];
cnt[b]+=cnt[a];
cnt[a]=0;
}
cout<<sum<<endl;
}
return 0;
}