Pagini recente » Cod sursa (job #1453802) | Cod sursa (job #1453799)
#include<fstream>
#include<string>
#include<algorithm>
#include<vector>
#include<iostream>
using namespace std;
ifstream in("ratina.in");
ofstream out("ratina.out");
const int NMAX = 10005;
const int INF = 1 << 30;
vector<pair<string,int> > v;
int n,q,poz[NMAX],st,fn,lg_min;
string aux,pars;
struct Trie{
int left,right;
Trie *fii[30];
Trie(){
for(int i = 0 ; i < 26 ; ++i)
fii[i] = NULL;
}
};
Trie *trie = new Trie;
void read()
{
in>>n>>q;
getline(in,aux);
for(int i = 1 ; i <= n ; ++i){
getline(in,aux);
v.push_back(make_pair(aux,i));
}
}
bool cmp(pair<string,int> a,pair<string,int> b)
{
if(a.first == b.first)
return a.second < b.second;
return a.first < b.first;
}
void ins(Trie *t,int p,int pos){
if(p == aux.size())
return;
if(t->fii[aux[p] - 'a'] == NULL){
t->fii[aux[p]-'a'] = new Trie;
t->fii[aux[p] - 'a']->left = pos;
t->fii[aux[p]-'a']->right = pos;
}
else{
t->fii[aux[p] - 'a']->left = min(t->fii[aux[p]-'a']->left,pos);
t->fii[aux[p]-'a']->right = max(t->fii[aux[p] - 'a']->right,pos);
}
ins(t->fii[aux[p]-'a'],p + 1,pos);
}
int query(Trie *t,int p,int rez){
if(p >= lg_min)
return rez;
if(st < t->fii[aux[p]-'a']->left || fn > t->fii[aux[p] - 'a']->right)
return rez;
return query(t->fii[aux[p] - 'a'],p + 1,rez + 1);
}
void precalc()
{
sort(v.begin(),v.end(),cmp);
for(int i = 0 ; i < v.size() ; ++i){
poz[v[i].second] = i + 1;
aux = v[i].first;
ins(trie,0,i + 1);
}
}
int citire(int& i)
{
int rez = 0;
while(!isspace(pars[i]) && pars[i] != '?'){
rez = rez * 10 + (pars[i] - '0');
++i;
}
++i;
return rez;
}
int main()
{
read();
precalc();
for(int i = 1 ; i <= q ; ++i){
int lg,g;
st = INF;
fn = -1;
lg_min = INF;
int k = 0;
getline(in,pars);
pars[pars.size()] = '?';
lg = citire(k);
for(int j = 1 ; j <= lg ; ++j){
g = citire(k);
st = min(st,poz[g]);
fn = max(fn,poz[g]);
if(lg_min > v[poz[g]-1].first.size()){
lg_min = v[poz[g]-1].first.size();
}
aux = v[st-1].first;
}
out<<query(trie,0,0)<<"\n";
}
return 0;
}