【練習04】 字典樹 1002 Flying to the Mars

來源:互聯網
上載者:User

題目大意:

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;}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.