【尺取法】POJ 3320:Jessica‘s Reading Problem

    科技2022-07-13  129

    一、题目内容

    POJ 3320 原题地址

    二、题意解释

    一本书有 P 页,每页都有个知识点a[i],知识点可能重复,求包含所有知识点的最少的页数。

    三、代码及注释

    #include<cstdio> #include<algorithm> #include<set> #include<map> using namespace std; int p; int a[1000005]; void solve() { set<int> all;//set中不包含重复元素,这里获得所有知识点 for(int i=0; i<p; i++) { all.insert(a[i]); } int n=all.size(); int s=0,t=0,num=0;//s为尺取法起始位置,t为终止位置,num记录已经加入的不重复知识点数量 int res=p; map<int,int> count; for(;;) { while(t<p&&num<n) { if(count[a[t]]==0) //如果当前知识点还没在map中 { count[a[t]]++; t++; num++;//知识点数量+1 } else { count[a[t]]++; t++; } } if(num<n) break; res=min(res,t-s); --count[a[s]]; if(count[a[s]]==0) //如果此时知识点数量为0,那么该知识点退出map,知识点总数量-1 { num--; } s++;//起始位置后移一位 } printf("%d\n",res); } int main() { scanf("%d",&p); for(int i=0; i<p; i++) { scanf("%d",&a[i]); } solve(); return 0; }
    Processed: 0.011, SQL: 8