【题目】http://codeforces.com/gym/101853/problem/A
【题意】给出一串数,两种操作,把一个位置的数改变,询问这串数中有多少个不是0的数。
【思路】map存数,另外存答案;map存数,set再存一遍去0;map每次查询数一遍不是0的(TLE)
【代码】
1:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int M=1e5+100;
const int inf=1e9+10;
int a[M];
map<int,int>book;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n,q;
int ans=0;
scanf("%d%d",&n,&q);
for(int i=1; i<=n; i++)
{
scanf("%d",&a[i]);
if(book[a[i]]==0&&a[i]!=0)
ans++;
book[a[i]]++;
}
for(int i=1; i<=q; i++)
{
int tt;
scanf("%d",&tt);
if(tt==2)
{
printf("%d\n",ans);
}
if(tt==1)
{
int p,v;
scanf("%d%d",&p,&v);
book[a[p]]--;
if(book[a[p]]==0&&a[p]!=0)
ans--;
a[p]=v;
if(book[a[p]]==0&&a[p]!=0)
ans++;
book[a[p]]++;
}
}
book.clear();
}
}
2:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int M=1e5+100;
const int inf=1e9+10;
ll a[M];
map<ll,int>book;
int main()
{
int t;
cin>>t;
while(t--)
{
int n,q;
set<ll> s;
scanf("%d%d",&n,&q);
for(int i=1; i<=n; i++)
{
scanf("%I64d",&a[i]);
if(a[i] != 0) s.insert(a[i]);
book[a[i]]++;
}
for(int i=0; i<q; i++)
{
int tt;
scanf("%d",&tt);
if(tt==2)
{
printf("%d\n",s.size());
}
else
{
int p;
ll v;
scanf("%d%I64d",&p,&v);
book[a[p]]--;
if(book[a[p]] == 0 && a[p] != 0) s.erase(a[p]);
a[p]=v;
book[a[p]]++;
if(v != 0) s.insert(v);
}
}
book.clear();
}
return 0;
}
TLE:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int M=1e5+100;
const int inf=1e9+10;
int a[M];
map<int,int>book;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n,q;
scanf("%d%d",&n,&q);
for(int i=1; i<=n; i++)
{
scanf("%d",&a[i]);
book[a[i]]++;
}
for(int i=1; i<=q; i++)
{
int tt;
scanf("%d",&tt);
if(tt==2)
{
int cnt=0;
map<int, int>::iterator iter;
for(iter = book.begin(); iter != book.end(); iter++)
{
if(iter->second!=0&&iter->first!=0)
cnt++;
}
printf("%d\n",cnt);
}
if(tt==1)
{
int p,v;
scanf("%d%d",&p,&v);
book[a[p]]--;
a[p]=v;
book[a[p]]++;
}
}
book.clear();
}
}