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 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

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

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;
}

你可能感兴趣的:(单调栈)