Title: http://poj.org/problem?id=3320
Test instructions: Given an array of n elements, find the shortest interval so that the element type within the interval equals the element type of the entire array.
Analysis: The beginning of the violent enumeration interval x, and then find the smallest y, so that the interval [x, y] satisfies the condition, X shifted to the X ', now Y ' certainly not on the left of Y. Both map and hash can be used.
Map Code:
#include <iostream> #include <set> #include <map> #include <cstdio> #include <algorithm> using namespace Std;const int MAXN = 1e6+6;int A[maxn],t[maxn];int Main () {map <int, int > Mp;int n,i,j,ncase;while (S CANF ("%d", &n)!=eof) {for (i=1;i<=n;i++) {scanf ("%d", &a[i]); t[i-1]=a[i];} Mp.clear (); sort (t,t+n); int Kind=unique (t,t+n)-t;int ans=n;int r=1;for (int l=1; l<=n; l++) {while (R<=n && mp.size () <kind) {if (Mp.find (A[r]) ==mp.end ()) Mp.insert (Make_pair (a[r],1)); else++ Mp[a[r]]; r++;} if (Mp.size () <kind) break;if (R-l<ans) ans=r-l;if (mp[a[l]]==1) mp.erase (Mp.find (a[l])); else--mp[a[l]];} printf ("%d\n", ans);} return 0;}
Hash code:
#include <iostream> #include <cstdio> #include <cstring>using namespace std; #define ABS (x) (x>0?x: -x) const int MAXN = 1e6+7;int a[maxn],n;struct node{int value,num;int next;}; int Table[maxn],cnt;node List[maxn];int Findkind () {Cnt=0;memset (table,-1,sizeof (Table)); int ret=0,hash,fd;for (int i =0;i<n;i++) {hash=abs (A[i])%maxn;fd=0;hash=table[hash];while (hash!=-1) {if (List[hash].value==a[i]) {Fd=1;break ;} Hash=list[hash].next;} if (FD) Continue;hash=abs (a[i])%MAXN; List[cnt].value=a[i]; List[cnt].next=table[hash]; table[hash]=cnt++;ret++;} return ret;} int Insert (int v) {int hash=abs (v)%maxn;hash=table[hash];while (hash!=-1) {if (LIST[HASH].VALUE==V) return List[hash]. Num++;hash=list[hash].next;} Hash=abs (v)%maxn; List[cnt].value=v; List[cnt].num=1; List[cnt].next=table[hash]; Table[hash]=cnt++;return 0;} int Delete (int v) {int hash=abs (v)%maxn;hash=table[hash];while (hash!=-1) {if (LIST[HASH].VALUE==V) return List[hash]. Num--;hash=list[hash].next;} return 0;} int main () {int i,j;int ncase;scanf ("%d"), &ncase), while (ncase--) {scanf ("%d", &n), for (i=0;i<n;i++) scanf ("%d", &a[i]); int kind=findkind (); memset (table,-1,sizeof (Table)); cnt=0;int r=0,ans=n,sz=0;for (int l=0; l<n; l++) {while (r<n && sz<kind) {if (! Insert (A[r])) sz++; r++;} if (sz<kind) break;if (R-l<ans) ans=r-l;if (Delete (a[l]) ==1) sz--;} printf ("%d\n", ans);} return 0;}
POJ 3320 Jessica ' s Reading problem (ruler extraction +map/hash)