uva 11572 Unique Snowflakes

本文介绍了解决UVA11572问题的方法,通过使用滑动窗口结合哈希表来寻找序列中最大连续且各元素不重复的子序列长度。文章详细解释了算法流程,并提供了实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目大意:求给定序列的最大连续的各个数字不同的序列长度。


解题:此题不是难题,就是使用一个hash表来查找在前面是否存在一个数与当前的相等,如果相等就将左边的边界设为相等的数的pos+1,再将当前的数加入hash表中,唯一注意的点就是在hash查找的时候注意判断左边的下界就行了。


//
//  main.cpp
//  uva 11572 - Unique Snowflakes
//
//  Created by XD on 15/8/13.
//  Copyright (c) 2015年 XD. All rights reserved.
//

//窗口滑动 + hash查找
#include <iostream>
#include <string>
#include <queue>
#include <stack>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include<vector>
#include <string.h>
#include <string>
#include <algorithm>
#include <set>
#include <map>
#include <cstdio>
using namespace std ;

int n ;
int lowerbound ;
const int hashsize = 1000003 ;
int st[hashsize]  ;

int head[hashsize]  ; int mnext[hashsize] ;

int max(int x , int y)
{
    return  x > y ? x :y  ;
}
void init()
{
    memset(head, 0, sizeof(head)) ;
    memset(mnext, 0, sizeof(int ) * (n + 5)) ;
}
int HASH(int pos)
{
    return st[pos] % hashsize ;
}
int insert_into_table(int pos)
{
    int flag = 1 ;
    int  h = HASH(pos) ;
    int  u  = head[h] ;
    while (u!=0) {
        
        if(u >= lowerbound && st[u] == st[pos])
        {
            lowerbound = u + 1 ;
//            mnext[pos] = head[h] ;
//            head[h] = pos ;
            flag = 0 ;
            break ;
        }
        u = mnext[u] ;
    }
    
    mnext[pos] = head[h] ;
    head[h] = pos ;
    return flag;
}


int main() {
    int casenum ;
    int d ;
    scanf("%d",&casenum) ;
    while (casenum--) {
        int ans = 0 ;
        int t = 0  ;
        lowerbound = 1 ;
        init() ;
        scanf("%d" ,&n) ;
        for (int i =1 ; i <=n ; i++) {
            scanf("%d" ,&d) ;
            st[i] = d  ;
           if(insert_into_table(i))
           {
               t++ ;
           }
           else{
               t =  i -lowerbound + 1 ;
           }
           ans = max(ans ,t) ;
        }
        printf("%d\n",ans) ;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值