Problem: Harry Potter and Numbers
Have you ever read the fantasy novel Harry Potter?If not,it will be such a pity.Harry Potter is the most miserable, lonely boy you can imagine. He’s shunned by his relatives, the Dursley’s, that have raised him since he was an infant.Harry’s world gets turned upside down on his 11th birthday, however. A giant, Hagrid, informs Harry that he’s really a wizard, and will soon be attending Hogwarts School of Witchcraft and Wizardry. Harry also learns that, in the wizarding world, he’s a hero.
However,as with every magic story,there will be a villain.In this book,the villain is the Dark wizard Lord Voldemort,who aims to become immortal, conquer the wizard world, subjugate non-magical people, and destroy all those who stand in his way, especially Harry Potter.When he was an infant, the evil Lord Voldemort killed his parents and then tried to kill Harry too. What’s so amazing to everyone is that Harry survived, and allegedly destroyed Voldemort in the process.
One day,his cousin Dudley have a problem with his homework,which was to find how many numbers exists exactly k times in a sequences of n numbers.However, Dudley is so lazy that he didn’t want to do this hard problem.So he asks little poor Harry to do it for him. What’s worse ,if Harry cannot finish it quickly,Dudley will starve the poor Harry.As Harry haven’t learned any magic,he cannot do it using his magic power.So he turns to you for help.Can you help our hero Harry?
Input
There are multiply test cases(no more than 50).The first line of each test cases contains two numbers n,k(0<=n,k<=1e4) as described above.The second line of each test cases contains n numbers of range [-1e4,1e4].
Output
For each test cases,output a line contains the answer.
Sample Input
5 1
1 2 3 4 5
Sample Output
5
WA不停的原因T_T:
没有考虑到k==0时的情况而给数组初始值都赋了0噗……
而且还是在换个思路重新写了一份之后才AC,最后发现的……也是醉
错误代码:
#include <iostream>
#include <cstring>
using namespace std;
int a[30000];int main()
{//freopen("1.txt","r",stdin);int n,k;while(cin>>n>>k){memset(a,0,sizeof(a));for(int i=0;i<n;i++){int t;cin>>t;t+=1e4;a[t]++;}int cnt=0;//printf("AA%d\n",k);for(int i=0;i<=2e4;i++)if(a[i]==k) cnt++;cout<<cnt<<endl;}return 0;
}
AC代码:
#include <bits/stdc++.h>
using namespace std;int main()
{//freopen("1.txt","r",stdin);int n,k;while(cin>>n>>k){map<int,int> a;for(int i=0;i<n;i++){int t;cin>>t;if(a.count(t)) a[t]++;else a[t]=1;}int cnt=0;for(int i=-1e4;i<=1e4;i++)if(a.count(i)&&a[i]==k) cnt++;cout<<cnt<<endl;}return 0;
}