Submission #1261816

#TimeUsernameProblemLanguageResultExecution timeMemory
1261816g4yuhgSelling RNA Strands (JOI16_selling_rna)C++20
100 / 100
426 ms719568 KiB
//Huyduocdithitp
#include <bits/stdc++.h>
typedef long long ll;
#define pii pair<ll, ll> 
#define MP make_pair
#define fi first
#define se second
#define TASK "mansion"
#define start if(fopen(TASK".in","r")){freopen(TASK".in","r",stdin);freopen(TASK".out","w",stdout);}
#define faster ios_base::sync_with_stdio(false);cin.tie(NULL);
#define N 200005
#define M 105
#define LOG 18
#define endl '\n'
using namespace std;
 
bool ghuy4g;

struct Node {
    ll child[26];
    ll cnt, exist;
} nodes[N * 20 + 5];
ll cur = 0, L[N * 20 + 5], R[N * 20 + 5];
ll new_node() {
	cur ++ ;
	memset(nodes[cur].child, -1, sizeof(nodes[cur].child));
	nodes[cur].cnt = nodes[cur].exist = 0;
	return cur;
} 

vector<ll> vt[N * 20 + 5];

void add(string s, ll id, ll type) { // 0 la add xuoi, 1 la add nguoc
	if (type == 1) reverse(s.begin(), s.end());
	ll pos = 0;
	for (auto f : s) {
		ll c = f - 'A';
		if (nodes[pos].child[c] == -1) {
			nodes[pos].child[c] = new_node();
		}
		pos = nodes[pos].child[c];
		//cout << f << " " << pos << " " << s << endl;
		if (type == 0) {
			if (L[pos] == 0) L[pos] = id;
			R[pos] = id;
		}
		else {
			vt[pos].push_back(id);
		}
	}
}

ll find(string s) {
	ll pos = 0;
	for (auto f : s) {
		ll c = f - 'A';
		if (nodes[pos].child[c] == -1) return 0;
		pos = nodes[pos].child[c]; 
	}
	return pos;
}

ll n, m;
string a[N];

bool klinh;

signed main(void) {
	faster;
	memset(nodes[0].child, -1, sizeof(nodes[0].child));
	cin >> n >> m;
	for (int i = 1; i <= n; i ++) {
		cin >> a[i];
		//cout << i << " | " << a[i] << endl;
	}
	sort(a + 1, a + 1 + n);
	for (int i = 1; i <= n; i ++) {
		add(a[i], i, 0);
		add(a[i], i, 1);
	}
	
	for (int i = 1; i <= m; i ++) {
		string u, v;
		cin >> u >> v;
		reverse(v.begin(), v.end());
		ll id1 = find(u), id2 = find(v);
		if (id1 == 0 || id2 == 0) {
			cout << 0 << endl;
			continue;
		}
		//cout << i << " " << u << " " << v << endl;
		ll l = L[id1], r = R[id1];
		//cout << l << " " << r << endl;
		ll it1 = lower_bound(vt[id2].begin(), vt[id2].end(), l) - vt[id2].begin();
		ll it2 = upper_bound(vt[id2].begin(), vt[id2].end(), r) - vt[id2].begin() - 1;
		cout << max(0LL, it2 - it1 + 1) << endl;
	}
	
	cerr << fabs(&klinh - &ghuy4g) / 1048576.0;
	
	return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...