Educational Codeforces Round 89 (Rated for Div. 2)~~E. Two Arrays

You are given two arrays a1,a2,…,an and b1,b2,…,bm. Array b is sorted in ascending order (bi<bi+1 for each i from 1 to m−1).
You have to divide the array a into m consecutive subarrays so that, for each i from 1 to m, the minimum on the i-th subarray is equal to bi. Note that each element belongs to exactly one subarray, and they are formed in such a way: the first several elements of a compose the first subarray, the next several elements of a compose the second subarray, and so on.
For example, if a=[12,10,20,20,25,30] and b=[10,20,30] then there are two good partitions of array a : [12,10,20],[20,25],[30] ; [12,10][20,20,25],[30] You have to calculate the number of ways to divide the array a. Since the number can be pretty large print it modulo 998244353.

Input

The first line contains two integers n and m (1≤n,m≤2⋅105) — the length of arrays a and b respectively.
The second line contains n integers a1,a2,…,an (1≤ai≤109) — the array a.
The third line contains m integers b1,b2,…,bm (1≤bi≤109;bi<bi+1) — the array b.

Output

In only line print one integer — the number of ways to divide the array a modulo 998244353.

Examples
Input

6 3
12 10 20 20 25 30
10 20 30

Output

2

Input

4 2
1 3 3 7
3 7

Output

0

Input

8 2
1 2 2 2 2 2 2 2
1 2

Output

7

思路:將數組a分成m段,第i段最小值等於bi,在數組a中最後一個值爲bi的元素必屬於第i段(若數組a、b中的最小元素不相等,輸出0),並且數組b是單調遞增的,所以反向遍歷最小值,可以找到每段的標誌元素,然後dp算出結果。

#include<bits/stdc++.h>

using namespace std;

typedef long long LL;
const int mod = 998244353;
const int maxn = 1e6 + 1;
const int inf = 0x3f3f3f3f;
const double Pi = acos(-1.0);
const LL INF = 0x3f3f3f3f3f3f3f3f;

template<class T, class F> inline void mem(T a,F b, int c) {for(int i=0;i<=c;++i)a[i]=b;}
template<class T> inline void read(T &x,T xk=10) { // xk 爲進制
	char ch = getchar(); T f = 1, t = 0.1;
	for(x=0; ch>'9'||ch<'0'; ch=getchar()) if(ch=='-')f=-1;
	for(;ch<='9'&&ch>='0';ch=getchar())x=x*xk+ch-'0';if(ch=='.') 
	for(ch=getchar();ch<='9'&&ch>='0';ch=getchar(),t*=0.1)x+=t*(ch-'0');x*=f;
}

int main() {
    int n, m; read(n), read(m);
    vector<int> a(n), b(m);
    for(int i = 0; i < n; ++ i) read(a[i]);
    for(int i = 0; i < m; ++ i) read(b[i]);
    for(int i = n-1; i > 0; -- i) a[i-1] = min(a[i-1], a[i]);
    if (a[0] != b[0]) {
        printf("0\n");
        return 0;
    }
    map<int,int> p;
    for(int i = 0; i < m; ++ i)  p[b[i]] = i;
    vector<LL> dp(m);
    dp[0] = 1;
    for(int r: a) {
        if (!p.count(r)) continue;
        r = p[r];
        if (r == 0) continue;
        dp[r] = (dp[r] + dp[r-1]) % mod;
    }
    printf("%lld\n", dp.back());
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章