散列:
将元素通过一个函数转换为整数,使得该整数可以尽量唯一地代表这个元素。
1.字符串统计
给出N个字符串(由恰好三个大写字母组成),再给出M个查询字符串,问每个查询字符串在N个字符串中出现的次数.
思路:用字符串通过散列转换为数字作为下标进行计数,数组中记录每个字符串出现的次数,再将查询字符串转换为数字,匹配下标,输出数组中所记录的个数.
代码如下:
1 | #include<stdio.h> |
2.String Subtraction
Given two strings S1 and S2, S = S1 - S2 is defined to be the remaining string after taking all the characters in S2 from S1. Your task is simply to calculate S1 - S2for any given strings. However, it might not be that simple to do it fast.
输入信息:
Each input file contains one test case. Each case consists of two lines which gives S1 and S2, respectively. The string lengths of both strings are no more than 104. It is guaranteed that all the characters are visible ASCII codes and white space, and a new line character signals the end of a string.
输出信息:
For each test case, print S1 - S2 in one line.
样例输入:
1 | They are students. |
样例输出:
1 | Thy r stdnts. |
思路:运用哈希函数,将s2中出现的字符标志设置为true,在s1中遍历,将为false的字符输出。
注意:
1.多层循环嵌套会导致运行超时
2.注意字符串的范围,会导致RE60%
代码如下:
1 | #include <stdio.h> |
3.Be Unique
Being unique is so important to people on Mars that even their lottery is designed in a unique way. The rule of winning is simple: one bets on a number chosen from [1,10000 ]. The first one who bets on a unique number wins. For example, if there are 7 people betting on { 5 31 5 88 67 88 17 }, then the second one who bets on 31 wins.
输入信息:
Each input file contains one test case. Each case contains a line which begins with a positive integer N (<=105) and then followed by N bets. The numbers are separated by a space.
输出信息:
For each test case, print the winning number in a line. If there is no winner, print “None” instead.
样例输入:
1 | 7 5 31 5 88 67 88 17 |
样例输出:
1 | 31 |
代码如下:
1 | #include <stdio.h> |
4.分组统计
先输入一组数,然后输入其分组,按照分组统计出现次数并输出,参见样例。
输入信息:
输入第一行表示样例数m,对于每个样例,第一行为数的个数n,接下来两行分别有n个数,第一行有n个数,第二行的n个数分别对应上一行每个数的分组,n不超过100。
输出信息:
输出m行,格式参见样例,按从小到大排。
样例输入:
1 | 1 |
样例输出:
1 | 1={2=0,3=2,8=1} |
注意:哈希数组要选的大一些,否则会WA50%。
代码如下:
1 | #include <stdio.h> |