牛客小白月赛15 C 表单 ( map 使用)
链接:https://ac.nowcoder.com/acm/contest/917/C
来源:牛客网
空间限制:C/C++ 262144K,其他语言524288K
64bit IO Format: %lld
题目描述
输入描述:
第一行两个整数n,Q
后n行每行一个字符串
后Q行每行代表一个操作:
一操作:1 s
二操作:2
输出描述: 对于每个二操作,进行回答。
输入
4 4
play
the
pubg
game
1 game
1 pubg
2
2
输出
2
0
说明:1≤n,Q≤5×105 对于所有输入的字符串长度<=40
思路 :就是一个裸的 C++ map 用法,每次判断新加入的字符串有没有出现过,对于当时不知道map的我手动模拟字符串匹配写了几十行(个人感觉手动模拟能过,但是超时了,自己菜了),map类似于python里面的字典,键值对是成对出现的,对于每一个键(key)都有一个值(value)与其对应,且键的值是唯一的,不可重复,引用头文件 #include <map> 定义一个map类 map<string,bool>name
C++ 中 map 提供的是一种键值对容器,里面的数据都是成对出现的,如下图:每一对中的第一个值称之为关键字(key),每个关键字只能在map中出现一次;第二个称之为该关键字的对应值。
代码:
1 #include <iostream> 2 #include <cstdio> 3 #include <map> 4 5 using namespace std; 6 int n, q, num, ans; 7 string s; 8 9 int main() 10 { 11 map<string,bool>a; 12 cin >> n >> q; 13 for(int i = 0; i < n; i ++ ) 14 { 15 cin >> s; 16 if(a[s]) ans ++ ; 17 a[s] = 1; 18 } 19 for(int i = 0; i < q; i ++ ) 20 { 21 scanf("%d",&num); 22 if(num == 1) 23 { 24 cin >> s; 25 if(a[s]) ans ++ ; 26 a[s] = 1; 27 } 28 else 29 { 30 cout << ans <<endl; 31 ans = 0; 32 } 33 } 34 return 0; 35 }