HDU 4287 map的用法

来源:互联网 发布:java用两个栈实现队列 编辑:程序博客网 时间:2024/06/06 22:23

原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=4287

Intelligent IME

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4834    Accepted Submission(s): 2255


Problem Description
  We all use cell phone today. And we must be familiar with the intelligent English input method on the cell phone. To be specific, the number buttons may correspond to some English letters respectively, as shown below:
  2 : a, b, c    3 : d, e, f    4 : g, h, i    5 : j, k, l    6 : m, n, o    
  7 : p, q, r, s  8 : t, u, v    9 : w, x, y, z
  When we want to input the word “wing”, we press the button 9, 4, 6, 4, then the input method will choose from an embedded dictionary, all words matching the input number sequence, such as “wing”, “whoi”, “zhog”. Here comes our question, given a dictionary, how many words in it match some input number sequences?
 

Input
  First is an integer T, indicating the number of test cases. Then T block follows, each of which is formatted like this:
  Two integer N (1 <= N <= 5000), M (1 <= M <= 5000), indicating the number of input number sequences and the number of words in the dictionary, respectively. Then comes N lines, each line contains a number sequence, consisting of no more than 6 digits. Then comes M lines, each line contains a letter string, consisting of no more than 6 lower letters. It is guaranteed that there are neither duplicated number sequences nor duplicated words.
 

Output
  For each input block, output N integers, indicating how many words in the dictionary match the corresponding number sequence, each integer per line.
 

Sample Input
13 5466444874goinnightmightgn
 

Sample Output
320
题解:此题一般的想法都是,对于一个数字,然后遍历所有字符串,输出符合单词的总数,但是此时复杂度很高,会超时的。所以我们应该在输入每一个字符串的时候,就对该字符串进行处理,避免后面每一个数字都要遍历所有。巧妙就在于将字符串转换为数字,直接比较数字,而不是比较字符串。

代码:

#include<cstdio>  #include<map>  #include<cstring>  using namespace std;map<char, int> mp;int num[1000000 + 100];//num[i]=j表输入的N个数中有一个是i,且这个i数对应了j个单词(计数)  int inputNum[5000 + 100];  char inputWord[5000 + 100][10]; int main(){mp.clear();mp['a'] = 2;mp['b'] = 2;mp['c'] = 2;mp['d'] = 3;mp['e'] = 3;mp['f'] = 3;mp['g'] = 4;mp['h'] = 4;mp['i'] = 4;mp['j'] = 5;mp['k'] = 5;mp['l'] = 5;mp['m'] = 6;mp['n'] = 6;mp['o'] = 6;mp['p'] = 7;mp['q'] = 7;mp['r'] = 7;mp['s'] = 7;mp['t'] = 8;mp['u'] = 8;mp['v'] = 8;mp['w'] = 9;mp['x'] = 9;mp['y'] = 9;mp['z'] = 9;int t;while (scanf("%d", &t) == 1 && t){while (t--){memset(num, 0, sizeof(num));//初始化所有数字的次数  int n, m;scanf("%d%d", &n, &m);for (int i = 0; i<n; i++)scanf("%d", &inputNum[i]);//存每个数字  for (int i = 0; i<m; i++){scanf(" %s", inputWord[i]);//读每个单词  int len = strlen(inputWord[i]);int value = 0;for (int j = 0; j<len; j++){//将每个单词转化为对应的值value = value * 10 + mp[inputWord[i][j]];}num[value]++;//该值计数加一  }for (int i = 0; i<n; i++)printf("%d\n", num[inputNum[i]]);}}return 0;}


0 0