Time Limit: 2 sec / Memory Limit: 1024 MB
Score : 400400 points
Problem Statement
You have a sequence AA composed of NN positive integers: A_{1}, A_{2}, \cdots, A_{N}A1,A2,⋯,AN.
You will now successively do the following QQ operations:
- In the ii-th operation, you replace every element whose value is B_{i}Bi with C_{i}Ci.
For each ii (1 \leq i \leq Q)(1≤i≤Q), find S_{i}Si: the sum of all elements in AA just after the ii-th operation.
Constraints
- All values in input are integers.
- 1 \leq N, Q, A_{i}, B_{i}, C_{i} \leq 10^{5}1≤N,Q,Ai,Bi,Ci≤105
- B_{i} \neq C_{i}Bi=Ci
Input
Input is given from Standard Input in the following format:
NN A_{1}A1 A_{2}A2 \cdots⋯ A_{N}AN QQ B_{1}B1 C_{1}C1 B_{2}B2 C_{2}C2 \vdots⋮ B_{Q}BQ C_{Q}CQ
Output
Print QQ integers S_{i}Si to Standard Output in the following format:
S_{1}S1 S_{2}S2 \vdots⋮ S_{Q}SQ
Note that S_{i}Si may not fit into a 3232-bit integer.
Sample Input 1 Copy
4 1 2 3 4 3 1 2 3 4 2 4
Sample Output 1 Copy
11 12 16
Initially, the sequence AA is 1,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 2 Copy
4 1 1 1 1 3 1 2 2 1 3 5
Sample Output 2 Copy
8 4 4
Note that the sequence AA may not contain an element whose value is B_{i}Bi.
Sample Input 3 Copy
2 1 2 3 1 100 2 100 100 1000
Sample Output 3 Copy
102 200 2000
这题如果采用循环一个个去找的话,会出现超时;
采用桶排序就很方便
#include<iostream>
using namespace std;
#include<algorithm>
int main()
{
int n,q,a[100020]={0},m;
long long sum=0;
int i,j,B,C;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&m);
a[m]++;
sum=sum+m;
}
scanf("%d",&q);
while(q--)
{
scanf("%d %d",&B,&C);
sum=sum+(C-B)*a[B];
a[C]=a[C]+a[B];
a[B]=0;
printf("%lld",sum);
if(q!=0)
printf("\n");
}
return 0;
}