尺取

POJ 3061:
For each the case the program has to print the result on separate line of the output file.if no answer, print 0.

Sample Input

2
10 15
5 1 3 5 10 7 4 9 2 8
5 11
1 2 3 4 5

Sample Output

2
3

题意:
2为样例数;
举第一组样例:
10为有十个数,15为 求和为15的最少的连续的数的个数

该题为尺取模板题,通过例题理解尺取:


#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
const int N = 55;
int main()
{
    int a[100100],i,t,t1,ge,sum,n,m,ans;
    scanf("%d",&t1);
    while(t1--)
    {
        scanf("%d%d",&n,&m);
        memset(a,0,sizeof(a));
        for( i=0; i<=n-1; i++)
            scanf("%d",&a[i]);
        i=0;
        t=0;
        ge=0;
        sum=0;
        ans=0x3f3f3f3f;
        while(i<=n)
        {
            if(sum<m)
            {
                sum+=a[i++];
                ge++;
            }
            else if(sum>=m)
            {
                sum-=a[t++];
                ge--;
            }
            if(sum>=m)
                ans=min(ans,ge);

        }
        if(ans!=0x3f3f3f3f)
        printf("%d\n",ans);
        else
            printf("0\n");
    }


}

 

给出一个字符串,求该字符串的一个子串s,s包含A-Z中的全部字母,并且s是所有符合条件的子串中最短的,输出s的长度。
如果给出的字符串中并不包括A-Z中的全部字母,则输出No Solution。
Input第1行,1个字符串。字符串的长度 <= 100000。Output输出包含A-Z的最短子串s的长度。如果没有符合条件的子串,则输出No Solution。
Sample Input
BVCABCDEFFGHIJKLMMNOPQRSTUVWXZYZZ
Sample Output
28

#include <iostream>
#include <string.h>
#include <stdio.h>
#include<map>
using namespace std;
map<int,int>mp;
map<int,int>::iterator it;
int f()
{
    int ge=0;
    for(it=mp.begin(); it!=mp.end(); it++)
    {
        if(it->second!=0)
            ge++;
    }
    if(ge==26)
        return 1;
    return 0;
}
int main()
{
    int i,ge=0;
    char a[100010];
    scanf("%s",a);
    int b=strlen(a);
    i=0;
    int t=0;
    int ans=0x3f3f3f3f;
    while(i<=b)
    {
        int t1=f();
        if(t1==0)
        {
            mp[a[i]-'A']++;
            i++;
            ge++;
        }
        if(t1==1)
        {
            ans=min(ans,ge);
        }
        if(t1==1)
        {
            mp[a[t++]-'A']--;
            ge--;
        }
    }
    if(ans!=0x3f3f3f3f)
        printf("%d\n",ans);
    else
        printf("No Solution\n");


}

  






posted @ 2018-08-15 18:14  我的秘密小屋  阅读(273)  评论(0编辑  收藏  举报