AtCoder - abc171_d

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值