CodeForces 91A Newspaper Headline

题目链接:CodeForces - 91A  Newspaper Headline

官方题解:

In this problem letters from s1 should be taken greedily: take the left letter from the right of the last used letter, if there is no necessary letter from the right of the right used letter the the search should be started from the beginning of string s1 and the answer should be increased by one. But the brute solution get TL and have complexity O(Ans * |s1|).
This solution can be optimized using the following way. For every position in s1 let's precalculate positions of the closest letters from the right of it from the alphabet. It can be done by moving from the right to the left ins s1 and remembering the last position of every type of symbol. This solution have complexity O(|s1| * K + |s2|), where K is a size of alphabet.

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<cmath>
#define CLR(a,b) memset((a),(b),sizeof((a)))
using namespace std;

const int N = 10005;
const int M = 1e6+5;

char s1[N], s2[M];
int d[N][26];
bool vis[26];

int main () {
    scanf("%s %s", s1, s2);
    int i, j;
    CLR(d, -1);
    CLR(vis, 0);
    int len1 = strlen(s1);
    int len2 = strlen(s2);
    for(i = 0; i < len1; ++i) {
        vis[ s1[i]-'a' ] = 1;
        for(j = 0; j <= i; ++j) {
            if(d[j][ s1[i]-'a' ] == -1)
                d[j][ s1[i]-'a' ] = i;
        }
    }
    for(j = 0; j < len2; ++j) {
        if(vis[ s2[j]-'a' ] == 0) {
            printf("-1\n"); return 0;
        }
    }
    int ans = 0;
    for(j = 0; j < len2; ) {
        i = 0;
        while(i < len1 && j < len2 && d[i][ s2[j]-'a' ] != -1) {
            i = d[i][ s2[j]-'a' ] + 1;
            j++;
        }
        ans++;
    }
    printf("%d\n", ans);
    return 0;
}
posted @ 2017-04-05 20:59  GraceSkyer  阅读(623)  评论(0编辑  收藏  举报

~~~~~~ACM大牛语录,激励一下~~~~~~

为了世界的和平,为了女生的安全,我拼命做题,做题,做题!

用最短的时间,刷最多的题!

给我一滴泪,我就看到了你全部的海洋!

seize the hour, seize the day.

人生难免有无奈,幸福走远了,或是感叹幸福来迟了.其实我一直相信,无论手中的幸福是多么微不足道的感觉,我会把握住那每一分,每一秒,当幸福依旧像那百鸟般飞逝,终究无法掌握时,我会感谢它,曾经降临过!

A自己的题,让别人郁闷去吧

WA肠中过,AC心中留 TLE耳边过,AC特别牛

天然的悲苦和伤逝,过去有过,以后还会有

^*^一步一步往上爬^*^

AC就像练级,比赛就像PK. 练级不如PK好玩

其实,世上本没有ACM,AC的人多了,也便有了!

AC无止尽~ Seek you forever~

找呀找呀找水题,找到一个AC一个呀!

AC是检验程序的唯一标准。

真的猛士,敢于直面惨淡的人生,敢于正视淋漓的鲜血……