zoukankan      html  css  js  c++  java
  • UVA 11572 Unique snowflakes (滑窗)

    用set,保存当前区间出现过的数字,如果下一个数字没有出现过,加入,否则删掉左端点,直到没有重复为止

    #include<bits/stdc++.h>
    using namespace std;
    const int maxn = 1e6+2;
    int A[maxn];
    
    int main()
    {
        int T; scanf("%d",&T);
        while(T--){
            int n; scanf("%d",&n);
            for(int i = 0; i < n; i++) scanf("%d",A+i);
            set<int> s;
            int L = 0, R = 0, ans = 0;
            while(R < n){
                while(R < n  && !s.count(A[R])) s.insert(A[R++]);
                ans = max(ans,R-L);
                s.erase(A[L++]);
            }
            printf("%d
    ",ans);
        }
        return 0;
    }

    数组版,pos[i]保存i最后一次出现的位置,最后到终点的时候也要算一次,所以令A[n] = A[n-1]。

    这个方法具有区间可加性。

    #include<bits/stdc++.h>
    using namespace std;
    const int maxn = 1e6+2;
    int A[maxn];
    int pos[maxn];
    
    int main()
    {
        int T; scanf("%d",&T);
        while(T--){
            int n; scanf("%d",&n);
            for(int i = 0; i < n; i++) scanf("%d",A+i);
            memset(pos,-1,sizeof(pos));
            int L = 0, ans = 0;
            A[n] = A[n-1];
            for(int i = 0; i <= n; i++){
                if(pos[A[i]] >= L){
                    ans = max(ans,i-L);
                    L = pos[A[i]]+1;
                }
                pos[A[i]] = i;
            }
            printf("%d
    ",ans);
        }
        return 0;
    }
  • 相关阅读:
    冲刺第十三天
    冲刺第十二天
    冲刺第十一天
    Android Studio三种运行方法
    第十三周学习进度
    冲刺第一阶段意见评论
    第十二周学习进度
    冲刺第十天
    大二暑假周总结(五)
    大二暑假周总结(四)
  • 原文地址:https://www.cnblogs.com/jerryRey/p/4694023.html
Copyright © 2011-2022 走看看