51nod 1127 最短的包含字符串(尺取法)

http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1127

可以用一个映射,把从头到当前位置的出现了多少个不同的字符计算出来,不断向区间末尾推进,如果包含了A-Z就可以更新最短长度,然后把开头的字符减1,表示向前推进一位.

这样就能在nlogn的时间内出解. 用map或者一个一维数组来映射都可以.

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cmath>
 4 #include <vector>
 5 #include <cstring>
 6 #include <string>
 7 #include <algorithm>
 8 #include <string>
 9 #include <set>
10 #include <functional>
11 #include <numeric>
12 #include <sstream>
13 #include <stack>
14 #include <map>
15 #include <queue>
16 #pragma comment(linker, "/STACK:102400000,102400000")
17 #define CL(arr, val)    memset(arr, val, sizeof(arr))
18 
19 #define ll long long
20 #define inf 0x7f7f7f7f
21 #define lc l,m,rt<<1
22 #define rc m + 1,r,rt<<1|1
23 #define pi acos(-1.0)
24 
25 #define L(x)    (x) << 1
26 #define R(x)    (x) << 1 | 1
27 #define MID(l, r)   (l + r) >> 1
28 #define Min(x, y)   (x) < (y) ? (x) : (y)
29 #define Max(x, y)   (x) < (y) ? (y) : (x)
30 #define E(x)        (1 << (x))
31 #define iabs(x)     (x) < 0 ? -(x) : (x)
32 #define OUT(x)  printf("%I64d\n", x)
33 #define lowbit(x)   (x)&(-x)
34 #define Read()  freopen("a.txt", "r", stdin)
35 #define Write() freopen("b.txt", "w", stdout);
36 #define maxn 1000000000
37 #define N 510
38 #define mod 1000000000
39 using namespace std;
40 char str[100010];
41 int main()
42 {
43     //Read();
44     scanf("%s",str);
45     int l=strlen(str);
46     map<char,int>m;
47     int s=0,t=0,num=0,res=inf;
48     while(1)
49     {
50         while(t<l&&num<26)
51         {
52             if(m[str[t++]]++==0) num++;
53             //printf("%d\n",num);
54         }
55         if(num<26) break;
56         res=min(res,t-s);
57         if(--m[str[s++]]==0) num--;
58     }
59     if(res==inf) printf("No Solution\n");
60     else printf("%d\n",res);
61     return 0;
62 }
posted @ 2015-06-27 10:31  NowAndForever  阅读(419)  评论(2编辑  收藏  举报