You are given an array a consisting of n elements, and q queries. There are two types of queries, as follow:
“1 p v” – An update query asks to change the value at position p in array a to v.
“2” – A query asks to print the minimum number of required operations to convert array a to a zero array.
A zero array is defined as an array which all its elements are zeros. There is only one allowed operation to convert an array to a zero array. At each operation, you can choose a value x and subtract it from all non-zero elements in the array, such that no element will be negative after the operation.
Input
The first line contains an integer T (1 ≤ T ≤ 100), in which T is the number of test cases.
The first line of each test case consists of two integers n and q (1 ≤ n, q ≤ 105), in which n is the size of the array a, and q is the number of queries.
Then a line follows containing n elements a1, a2, …, an (0 ≤ ai ≤ 109), giving the array a.
Then q lines follow, each line containing a query in the format described in the problem statement. It is guaranteed that the following constraints hold for the first type of queries: 1 ≤ p ≤ n, 0 ≤ v ≤ 109.
The sum of n and q overall test cases does not exceed 106 for each.
Output
For each query of the second type, print the minimum number of required operations to convert array a to a zero array. The queries must be answered in the order given in the input.
Example
Input
1
5 5
3 2 1 5 4
1 2 3
2
1 3 2
1 4 1
2
Output
4
4
题记:1pv是将第p个位置的值改为v,2是查询最少的操作数使得所有数都变为0,从原序列中选一个非0的数,然后用非0的数去减它,所有数不能为负数(就是找有多少个不一样的数)。
#include<bits/stdc++.h>
using namespace std;
int a[100001];
map<int,int>mp;
int main()
{
int t,n,m,x,y,k;
scanf("%d",&t);
while(t--)
{
mp.clear();
int ans=0;
scanf("%d%d",&n,&m);
for(int i=1; i<=n; i++)
{
scanf("%d",&a[i]);
if(a[i]&&!mp[a[i]])ans++;
mp[a[i]]++;
}
while(m--)
{
scanf("%d",&k);
if(k==1)
{
scanf("%d%d",&x,&y);
if(a[x]&&mp[a[x]]==1)ans--;
mp[a[x]]--;
if(y&&!mp[y])ans++;
mp[y]++;
a[x]=y;
}
else printf("%d\n",ans);
}
}
return 0;
}
这题输入用cin会超时,用scanf不会…如果要用cin的话要加上
cin.tie(0);
cout.tie(0);
ios::sync_with_stdio(false);
下面是学校师兄给出的答案
#include <bits/stdc++.h>
using namespace std;
#define N 100010
unordered_map <int, int> mp;
int t, n, q;
int arr[N];
int main()
{
cin.tie(0);
cout.tie(0);
ios::sync_with_stdio(false);
cin >> t;
while (t--)
{
cin >> n >> q;
mp.clear();
for (int i = 1; i <= n; ++i)
{
cin >> arr[i];
mp[arr[i]]++;
}
int op, p, v;
while (q--)
{
cin >> op;
if (op == 1)
{
cin >> p >> v;
if (mp[arr[p]] == 1)
{
mp.erase(arr[p]);
}
else
{
mp[arr[p]]--;
}
mp[v]++;
arr[p] = v;
}
else
{
mp[0]++;
cout << mp.size() - 1 << endl;
}
}
}
return 0;
}