问题描述
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;
}
}