洛谷1381 单词背诵

我也真是快废了……这个题调了半小时

双指针+map

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 map <string,int> mp;
 5 int n,m,a[100005],p1,p2,buf[1005],buf0[1005],ans=1e+9,cnt=0;
 6 string str;
 7 
 8 inline bool checker() {
 9     for(int i=1;i<=n;i++) 
10         if(buf[i]==0 && buf0[i]) 
11             return 0;
12     return 1;
13 }
14 
15 int main(){
16     ios::sync_with_stdio(false);
17     cin>>n;
18     for(int i=1;i<=n;i++) cin>>str, mp.insert(make_pair(str,i));
19     cin>>m;
20     for(int i=1;i<=m;i++) {
21         cin>>str;
22         if(mp.find(str)!=mp.end())
23             a[i]=mp.find(str)->second, buf[a[i]]++;
24     }
25     for(int i=1;i<=n;i++) cnt+=buf[i]!=0, buf0[i]=buf[i];
26     memset(buf,0,sizeof buf);
27     p1=1;p2=0;
28     while(p1<=m) {
29         while(!checker() && p2<=m) p2++, buf[a[p2]]++;
30         if(checker() && p1<=p2) 
31             ans=min(ans,p2-p1+1);
32         buf[a[p1]]--; p1++;
33     }
34     cout<<cnt<<endl<<(cnt==0?0:ans)<<endl;
35 }
原文地址:https://www.cnblogs.com/mollnn/p/8449899.html