题目链接:http://codeforces.com/contest/8/problem/A
题意:给了一个文本串,然后现在有两个模式串,问这两个模式串能否正向和反向匹配。
解法:kmp粘粘粘。

//CF 8A

#include <bits/stdc++.h>
using namespace std;

const int maxn = 1e5+7;
char s[maxn], s1[maxn], s2[maxn];
int fail[maxn];
vector <int> p1, p2;
int flag1 = 0, flag2 = 0;

int main()
{
    scanf("%s", s+1);
    scanf("%s", s1+1);
    scanf("%s", s2+1);
    int len, len1, len2, j;
    len1 = strlen(s1+1);
    j = 0;
    for(int i = 2; i <= len1; i++){
        while(j>0&&s1[j+1]!=s1[i]) j = fail[j];
        if(s1[j+1] == s1[i]) j++; fail[i] = j;
    }
    len = strlen(s+1);
    j = 0;
    for(int i = 1; i <= len; i++){
        while(j>0&&s1[j+1]!=s[i]) j=fail[j];
        if(s1[j+1]==s[i]) j++;
        if(j==len1){p1.push_back(i), j = fail[j];}
    }
    //
    memset(fail, 0, sizeof(fail));
    len2 = strlen(s2+1);
    j = 0;
    for(int i = 2; i <= len2; i++){
        while(j>0&&s2[j+1]!=s2[i]) j = fail[j];
        if(s2[j+1] == s2[i]) j++; fail[i] = j;
    }
    len = strlen(s+1);
    j = 0;
    for(int i = 1; i <= len; i++){
        while(j > 0 && s2[j+1] != s[i]) j = fail[j];
        if(s2[j+1] == s[i]) j++;
        if(j==len2){p2.push_back(i), j = fail[j];}
    }
    sort(p1.begin(), p1.end());
    sort(p2.begin(), p2.end());
    //
// for(int i = 0; i < p1.size(); i++){
// printf("%d ", p1[i]);
// }
// printf("\n");
// for(int i = 0; i < p2.size(); i++){
// printf("%d ", p2[i]);
// }
// printf("\n");

    if(p1.size()!=0&&p2.size()!=0)
        if(p1[0]+strlen(s2+1)<=p2[(int)p2.size()-1]) flag1 = 1;


    p1.clear();
    p2.clear();
    len = strlen(s+1);
    reverse(s+1,s+len+1);

    memset(fail, 0, sizeof(fail));
    len1 = strlen(s1+1);
    j = 0;
    for(int i = 2; i <= len1; i++){
        while(j>0&&s1[j+1]!=s1[i]) j = fail[j];
        if(s1[j+1] == s1[i]) j++; fail[i] = j;
    }
    len = strlen(s+1);
    j = 0;
    for(int i = 1; i <= len; i++){
        while(j>0&&s1[j+1]!=s[i]) j=fail[j];
        if(s1[j+1]==s[i]) j++;
        if(j==len1){p1.push_back(i), j = fail[j];}
    }
    //
    memset(fail, 0, sizeof(fail));
    len2 = strlen(s2+1);
    j = 0;
    for(int i = 2; i <= len2; i++){
        while(j>0&&s2[j+1]!=s2[i]) j = fail[j];
        if(s2[j+1] == s2[i]) j++; fail[i] = j;
    }
    len = strlen(s+1);
    j = 0;
    for(int i = 1; i <= len; i++){
        while(j > 0 && s2[j+1] != s[i]) j = fail[j];
        if(s2[j+1] == s[i]) j++;
        if(j==len2){p2.push_back(i), j = fail[j];}
    }
    sort(p1.begin(), p1.end());
    sort(p2.begin(), p2.end());
    if(p1.size()!=0&&p2.size()!=0)
        if(p1[0]+strlen(s2+1)<=p2[p2.size()-1]) flag2 = 1;

    if(flag1&&flag2) return puts("both"), 0;
    if(flag1) return puts("forward"), 0;
    if(flag2) return puts("backward"), 0;
    return puts("fantasy"), 0;
}