DOJ - 1002 Least Subsequence

问题描述

Giving a set of keywords like (key1,key2,…,keym)(key1,key2,…,keym) and a paragraph like (word1,word2,…,wordn)(word1,word2,…,wordn), please find the least subsequence of the paragraph which includes all keywords (ignoring the order). The least subsequence means that its number of words is the least.
输入格式

There are several test cases and each case takes up three lines.

The first line contains two integers nn and mm, representing the number of words in the paragraph and the number of keywords respectively.

The second line contains mm keywords, separated by spaces.

The third line contains nn words, separated by spaces.

The input is terminated by EOF.

Note: The lengths of both keywords and words are less than 100. Any two keywords are different.
输出格式

For each test case X, if the least subsequence exists, then print out a string like “Case X: XX”, otherwise, just print out “Case X: -1”. X is the test case number starting from I and XX is the length of the least subsequence.
样例输入

5 2
hello world
hell everyone this is good
10 3
sun apple tree
what is the sun tell apple tree sun call apple

样例输出

Case 1: -1
Case 2: 3

数据范围和提示

1≤n≤105,l≤m≤100

分析:O(N)可以推出所有以i为结尾的符合条件的子串的最短长度。

#include <cstdio>
#include <iostream>
#include <cstring>
#include <unordered_map>
using namespace std;
string a;
int n,m,NUM,b[100005],now[100005],F[100005],New[100005];
int main()
{
    cin.sync_with_stdio(false);
    while(cin>>n>>m)
    {
        unordered_map <string,int> f;
        memset(now,0,sizeof(now));
        memset(F,0,sizeof(F));
        memset(New,0,sizeof(New));
        memset(b,0,sizeof(b));
        int tot = 0;
        for(int i = 1;i <= m;i++) 
        {
            cin>>a;
            f[a] = ++tot;
        }
        for(int i = 1;i <= n;i++)
        {
            cin>>a;
            if(f.count(a)) F[i] = New[f[a]],b[i] = f[a],New[f[a]] = i;
        }
        int i = n,pre = 0,num = 0;
        for(;i;i--)
        {
            if(b[i] == 0) continue;
            if(now[b[i]] == 0) now[b[i]] = 1,num++,pre = pre == 0 ? i:pre;
            if(num == m) break;
        }
        if(num != m)
        {
            cout<<"Case "<<++NUM<<": "<<-1<<endl;
            continue;
        }
        int l = i;
        int ans = pre - l + 1;
        for(i = pre-1;i;i--)
        {
            if(b[i] == 0) continue;
            if(F[pre] == 0) break;
            if(F[pre] < l) l = F[pre];
            pre = i;
            ans = min(ans,i - l + 1); 
        }
        cout<<"Case "<<++NUM<<": "<<ans<<endl;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值