【练习04】 字典树 1002 Flying to the Mars

来源:互联网 发布:淘宝app修改评价 编辑:程序博客网 时间:2024/06/05 11:27

题目大意:

8888年,地球被PPF王国统治了。由于人口增长,PPF需要为新生儿找寻更多的陆地。最后,PPF决定攻击通知Mars火星的Kscinow。问题来了,怎样让士兵到火星上去呢?PPF召集士兵征询建议。最后决定从哈利波特那里买些魔法扫帚,让士兵们飞上去~现在那些士兵正在学习使用魔法扫帚。我们假设每个战士都有一个等级表示他的级别。高等级的战士可以指导低等级的,但是反过来不可以。一个战士最多有一名指导者,也可以没有指导者。类似的,一个战士最多可以指导一名学习者,也可以不指导任何人。指导者和学习者可以共用同一把扫帚。所有的战士必须在飞往火星之前准备好。扫把很贵,怎样才能使所需要的扫把数量最少?

例如,有五个战士a,b,c,d,e,他们级别是2,4,5,6,4;

方法一:

c teach b,bteach a,所以a,b,c可以使用一把扫帚;

d teach e,所以d,d可以使用一把扫帚;

这样就需要2把;

方法二:

d teach a,所以a,d用一把;

c teach b,所以b,c用一把;

e自用一把;

这样就需要3把;

。。。

最后在所有可能的方法中,我们发现最少要2把;

输入:多组测试用例

第一行:正整数N(0-3000)表示战士个数;

接下来N行,每行一个非负整数,表示战士级别;(不超过30位)

输出:每组测试用例,输出最少需要的扫把数;

===========由题可知===========

1、相同的数最多有几个。

2、如果战士级别不超过18位,那就可以用__int64或者long long来解决了,但是题目中要求30位,只能用字符串解决;

3、不到3000个士兵,也就是最多3000个士兵级别

算法思路:map。

这题关键是要对相同level的最大值进行统计,其他人有用trie的,用val数组保存相同“单词”(字符串)出现的频率,trie的作用无非就是克服了(30 digits)的限制,感觉并没有起什么太大的作用,之所以采用map也是因为能够用字符串作为键值。

不过有人直接用int进行排序统计也过了,可见数据是很水的,30digits就是用来吓人的。

提示:

1.用map和trie做的时候需要去掉前导0;

2.map如果用find函数的话会超时。

 

//模板开始#include <string>   #include <vector>   #include <algorithm>   #include <iostream>   #include <sstream>   #include <fstream>   #include <map>   #include <set>   #include <cstdio>   #include <cmath>   #include <cstdlib>   #include <ctime>#include <iomanip>#include <string.h>#include <queue>#define SZ(x) (int(x.size()))using namespace std;int toInt(string s){istringstream sin(s); int t; sin>>t; return t;}template<class T> string toString(T x){ostringstream sout; sout<<x; return sout.str();}typedef long long int64;int64 toInt64(string s){istringstream sin(s); int64 t; sin>>t;return t;}template<class T> T gcd(T a, T b){ if(a<0) return gcd(-a, b);if(b<0) return gcd(a, -b);return (b == 0)? a : gcd(b, a % b);}//模板结束(通用部分)#define ifs cinmap<string, int> m;map<string, int>::iterator it;//【练习04】 字典树 1001 Hat’s Wordsint main(){//ifstream ifs("shuju.txt", ios::in);int n;while(ifs>>n){ifs.ignore(35, '\n');m.clear();for(int i = 0; i < n; i++){string a;getline(ifs, a, '\n');int k = 0;while(a[k++] == '0');a = a.substr(k - 1, a.length() - (k - 1));m[a]++;}int max;for(it = m.begin(), max = it->second; it != m.end(); it++){if(max < it->second){max = it->second;}}cout<<max<<endl;}return 0;}


 

原创粉丝点击