【POJ - 3320 】Jessica's Reading Problem (尺取,哈希)
題干:
Jessica's a very lovely girl wooed by lots of boys. Recently she has a problem. The final exam is coming, yet she has spent little time on it. If she wants to pass it, she has to master all ideas included in a very thick text book. The author of that text book, like other authors, is extremely fussy about the ideas, thus some ideas are covered more than once. Jessica think if she managed to read each idea at least once, she can pass the exam. She decides to read only one contiguous part of the book which contains all ideas covered by the entire book. And of course, the sub-book should be as thin as possible.
A very hard-working boy had manually indexed for her each page of Jessica's text-book with what idea each page is about and thus made a big progress for his courtship. Here you come in to save your skin: given the index, help Jessica decide which contiguous part she should read. For convenience, each idea has been coded with an ID, which is a non-negative integer.
Input
The first line of input is an integer?P?(1 ≤?P?≤ 1000000), which is the number of pages of Jessica's text-book. The second line contains?P?non-negative integers describing what idea each page is about. The first integer is what the first page is about, the second integer is what the second page is about, and so on. You may assume all integers that appear can fit well in the signed 32-bit integer type.
Output
Output one line: the number of pages of the shortest contiguous part of the book which contains all ideals covered in the book.
Sample Input
5 1 8 8 8 1Sample Output
2題目大意:
? ? 有一本書有n個章節,但是有的章節是在講相同的內容,現在每個內容用數字代替,問你最少需要讀多少章節才可以把所有的內容都學到手?
解題報告:
? ? 一看就是尺取嘛,,然后cur==cnt之后,別忘看看l還可不可以往右移動就好了。
AC代碼:
#include<cstdio> #include<map> #include<iostream> #include<cstring> #define ll long long #define pb push_back #define pm make_pair #define fi first #define se second using namespace std; const int MAX = 2e6 + 5; int a[MAX]; int cnt,cur,ans; map<int , int> mp; int main() {int n;while(~scanf("%d",&n)) {cnt = cur = 0;ans = 0x3f3f3f3f;mp.clear();for(int i = 1; i<=n; i++) {scanf("%d",a+i);if(mp.find(a[i]) == mp.end()) mp[a[i]]=1,cnt++; } int l = 1,r = 1;mp.clear();while(r <= n) {if(mp[a[r]] == 0) cur++;mp[a[r]]++;if(cur >= cnt) {while(cur > cnt) {mp[a[l]]--;if(mp[a[l]] == 0) cur--;l++;}while(mp[a[l]] >= 2) {mp[a[l]]--;l++; } ans = min(ans,r-l+1); }r++;}printf("%d\n",ans);} return 0 ;} /* 4 3 3 2 1 4 2 3 2 1 */總結:
1.和這題一樣【HDU - 5672】String(尺取法),都是要注意一種樣例:
4
3 3 2 1
和:
4
3 2 3 1
。如果找到cur==cnt就更新答案了,那就錯了,因為左邊說不定還是可以縮減的。但是我給的這兩個樣例是兩種類型的!!
如果僅僅針對第一個樣例可以這樣? ? ? ? while(a[l] == a[l+1]) l++;?? ?
但是對第二個又過不了,因為這幾個3不一定連續!!
?
2.這題數據量1e6,用map的話是516msAC的,有點慢,這題可以用hash數組
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的【POJ - 3320 】Jessica's Reading Problem (尺取,哈希)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【CodeForces - 589F】G
- 下一篇: 2017中信银行信用卡有效期 揭开银行那