标签:limit div isp ref hash表 other for time signed
给定一个序列,请你求出该序列的一个连续的子序列,使原串中出现的所有元素皆在该子序列中出现过至少1次。
如2 8 8 8 1 1,所求子串就是2 8 8 8 1。
2 5 1 8 8 8 1 6 2 8 8 8 1 1
2 5
#include<iostream> #include<cstdio> #include<cmath> #include<cstring> #include<sstream> #include<algorithm> #include<queue> #include<deque> #include<iomanip> #include<vector> #include<cmath> #include<map> #include<stack> #include<set> #include<fstream> #include<memory> #include<list> #include<string> using namespace std; typedef long long LL; typedef unsigned long long ULL; #define MAXN 1000044 #define INF 1000000009 #define eps 0.00000001 /* 利用队列从前到后遍历数组元素 当前元素未在之前出现过,更新ans为队列元素个数 当前元素在之前出现过 如果当前队首元素在hash表中出现次数多于1次,pop */ int T, n, aim, a[MAXN],b[MAXN]; typedef struct Hashnode { int data; int cnt; struct Hashnode* next; }*List; typedef struct Hashtb { List* L; }*HashTable; HashTable Init() { HashTable H = (HashTable)malloc(sizeof(Hashtb)); H->L = (List*)malloc(sizeof(List)*MAXN); for (int i = 0; i < MAXN; i++) { H->L[i] = (List)malloc(sizeof(Hashnode)); H->L[i]->data = 0; H->L[i]->cnt = 0; H->L[i]->next = NULL; } return H; } int Hash(int x) { return x%MAXN; } void clear(HashTable H) { for (int i = 0; i < MAXN; i++) { H->L[i]->data = 0; H->L[i]->cnt = 0; H->L[i]->next = NULL; } } List find(int x, HashTable H) { List l = H->L[Hash(x)]; List p = l->next; while (p != NULL&&p->data != x) p = p->next; return p; } int cnt(int x, HashTable H) { List p = find(x, H); if (p == NULL) return -1; else { if (p->cnt > 1) { p->cnt--; return p->cnt + 1; } else return p->cnt; } } bool Insert(int x, HashTable H) { List l = H->L[Hash(x)]; List p = find(x, H); if (!p) { List tmp = (List)malloc(sizeof(Hashnode)); tmp->data = x; tmp->cnt = 1; tmp->next = l->next; l->next = tmp; return false; } else { p->cnt++; return true; } } int main() { scanf("%d", &T); HashTable H = Init(); while (T--) { clear(H); scanf("%d", &n); int ans = INF,tmp; queue<int> q; for (int i = 0; i < n; i++) { scanf("%d", &tmp); if (!Insert(tmp,H)) { q.push(tmp); ans = q.size(); } else { q.push(tmp); while (!q.empty()&&cnt(q.front(),H) > 1) { q.pop(); } ans = min(ans,(int)q.size()); } } printf("%d\n", ans); } return 0; }
子序列 NYOJ (尺取法+队列+hash) (尺取法+离散化)
标签:limit div isp ref hash表 other for time signed
原文地址:http://www.cnblogs.com/joeylee97/p/6891539.html