Wet Shark and Two Subsequences


Problem Statement :


One day, Wet Shark was given an array X = {x1, x2, ..., xm}. As always, he started playing with its subsequences.

When you came to know about this habit, you presented him a task of finding all pairs of subsequences, (A,B), which satisfies all of the following constraints. We will represent a pair of subsequence as A = {xa1,xa2,...,xan} and B = {xb1,xb2,...,xbn}

 A and B must be of same length, i.e., |A| = |B|.
 Σ(xai + xbi) = r
 Σ(xai - xbi) = s
Please help Wet Shark determine how many possible subsequences A and B can exist. Because the number of choices may be big, output your answer modulo 10^9 + 7 =100000007.

Note:

Two segments are different if there's exists at least one index i such that element xi is present in exactly one of them.
Both subsequences can overlap each other.
Subsequences do not necessarily have to be distinct
Input Format

The first line consists of 3 space-separated integers m, r, s, where m denotes the length of the original array, X, and r and s are as defined above.
The next line contains m space-separated integers,  x1, x2,..., xm, representing the elements of X.

Constraints
1 <= m <= 100
0 <= r,s <=2000
1 <= xi <= 2000

Output Format

Output total number of pairs of subsequences, (A,B), satisfying the above conditions. As the number can be large, output it's modulo 10^9 + 7 =100000007.



Solution :



title-img


                            Solution in C :

In C++ :





/*
*/
 
//#pragma comment(linker, "/STACK:16777216")
#include <fstream>
#include <iostream>
#include <string>
#include <complex>
#include <math.h>
#include <set>
#include <vector>
#include <map>
#include <queue>
#include <stdio.h>
#include <stack>
#include <algorithm>
#include <list>
#include <ctime>
#include <memory.h>
#include <ctime> 
 
#define y0 sdkfaslhagaklsldk
#define y1 aasdfasdfasdf
#define yn askfhwqriuperikldjk
#define j1 assdgsdgasghsf
#define tm sdfjahlfasfh
#define lr asgasgash
 
#define eps 1e-9
//#define M_PI 3.141592653589793
#define bs 1000000007
#define bsize 256
#define right adsgasgadsg
#define free adsgasdg
#define MAG 10000

using namespace std;

long n,r,s,na,nb,q,dp[101][2525][101];
long long ans;

void add(long&a,long &b)
{
 a+=b;
 if (a>=bs)
  a-=bs;
}

int main(){
//freopen("evacuation.in","r",stdin);
//freopen("evacuation.out","w",stdout);
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
ios_base::sync_with_stdio(0);
//cin.tie(0);

cin>>n>>r>>s;
nb=(r-s)/2;

na=r-nb;
if (na>2000) return 1;

dp[0][0][0]=1;

for (int i=1;i<=n;i++)
{
     cin>>q;
     for (int j=0;j<=2000;j++)
     for (int l=0;l<=n;l++)
     {
      add(dp[i][j][l],dp[i-1][j][l]);
      if (j>=q&&l>0)
       add(dp[i][j][l],dp[i-1][j-q][l-1]);
     }
}
long long answ=0;

for (int p=1;p<=n;p++)
{
ans=dp[n][na][p];
if (s%2!=r%2||r<s)
 ans=0;else
ans*=dp[n][nb][p];
ans%=bs;
answ=answ+ans;
answ%=bs;}
cout<<answ<<endl;

cin.get();cin.get();
return 0;}








In Java :





import java.io.*;
import java.util.*;

public class Solution {
  private static InputReader in;
  private static PrintWriter out;
  public static int mod = 1000000007;

  public static void main(String[] args) throws IOException {
    in = new InputReader(System.in);
    out = new PrintWriter(System.out, true);
    
    int M = in.nextInt();
    int R = in.nextInt();
    int S = in.nextInt();
    if ((R+S) % 2 != 0 || S >= R) {
      out.println("0");
      out.close();
      System.exit(0);
    }
    
    int P = (R+S)/2, Q = (R-S)/2;
    
    long[][] nways = new long[M+1][P+1];
    nways[0][0] = 1;
    for (int i = 1; i <= M; i++) {
      int x = in.nextInt();
      for (int j = M; j >= 1; j--) {
        for (int k = P; k >= x; k--) {
          nways[j][k] += nways[j-1][k-x];
          if (nways[j][k] >= mod) nways[j][k] -= mod;
        }
      }
    }
    
    long total = 0;
    for (int i = 0; i <= M; i++) {
      total = (total + nways[i][P] * nways[i][Q]) % mod;
    }
    out.println(total);
    out.close();
    System.exit(0);
    
  }

  static class InputReader {
    public BufferedReader reader;
    public StringTokenizer tokenizer;

    public InputReader(InputStream stream) {
      reader = new BufferedReader(new InputStreamReader(stream), 32768);
      tokenizer = null;
    }

    public String next() {
      while (tokenizer == null || !tokenizer.hasMoreTokens()) {
        try {
          tokenizer = new StringTokenizer(reader.readLine());
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      }
      return tokenizer.nextToken();
    }

    public int nextInt() {
      return Integer.parseInt(next());
    }
  }


}








In C :





#include <stdio.h>
#include <stdlib.h>
#define MOD 1000000007
int a[100];
long long dp1[101][100][2001];

int main(){
  int m,r,s,A,B,i,j,k;
  long long ans=0;
  scanf("%d%d%d",&m,&r,&s);
  for(i=0;i<m;i++)
    scanf("%d",a+i);
  if((r+s)%2 || r<s){
    printf("0");
    return 0;
  }
  A=(r+s)/2;
  B=(r-s)/2;
  for(i=0;i<=m;i++)
    for(j=0;j<m;j++)
      for(k=0;k<=A;k++)
        if(!i)
          if(!k)
            dp1[i][j][k]=1;
          else
            dp1[i][j][k]=0;
        else if(!j){
          if(i>1)
            dp1[i][j][k]=0;
          else if(k==a[j])
            dp1[i][j][k]=1;
          else
            dp1[i][j][k]=0;
        }
        else if(i>j+1)
          dp1[i][j][k]=0;
        else{
          dp1[i][j][k]=dp1[i][j-1][k];
          if(k-a[j]>=0)
            dp1[i][j][k]=(dp1[i][j][k]+dp1[i-1][j-1][k-a[j]])%MOD;
        }
  for(i=1;i<=m;i++)
    ans=(ans+dp1[i][m-1][A]*dp1[i][m-1][B]%MOD)%MOD;
  printf("%lld",ans);
  return 0;
}








In Python3 :





def solve():
    mod = 10**9+7
    m,r,s = map(int,input().rstrip().split(' '))
    if m == 0 or r<=s: return 0
    arr = list(map(int,input().rstrip().split(' ')))
    if (r-s) % 2 != 0: return 0
    sumb = (r-s)//2
    suma = r - sumb
    
    def get_ways(num):
        dp = [[0]*(num+1) for _ in range(m+1)]
        dp[0][0] = 1
        for c in arr:
            for i in range(len(dp[0])-1,c-1,-1):
                for j in range(len(dp)-2,-1,-1):
                    if dp[j][i-c]>0:
                        #print(j,i,c)
                        dp[j+1][i]+=dp[j][i-c]
        #print(dp)
        for j in range(len(dp)):
            if dp[j][num] > 0:
                #print(j,dp[j][num])
                yield (j,dp[j][num]) #num coins, count
                
    a = list(get_ways(suma))
    #print('---',suma,sumb)
    b = list(get_ways(sumb))
    res = 0
    for i in a:
        for j in b:
            if i[0]==j[0]: #same length
                res += i[1]*j[1]
    return res % mod       
    
print(solve())
                        








View More Similar Problems

Array-DS

An array is a type of data structure that stores elements of the same type in a contiguous block of memory. In an array, A, of size N, each memory location has some unique index, i (where 0<=i<N), that can be referenced as A[i] or Ai. Reverse an array of integers. Note: If you've already solved our C++ domain's Arrays Introduction challenge, you may want to skip this. Example: A=[1,2,3

View Solution →

2D Array-DS

Given a 6*6 2D Array, arr: 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 An hourglass in A is a subset of values with indices falling in this pattern in arr's graphical representation: a b c d e f g There are 16 hourglasses in arr. An hourglass sum is the sum of an hourglass' values. Calculate the hourglass sum for every hourglass in arr, then print t

View Solution →

Dynamic Array

Create a list, seqList, of n empty sequences, where each sequence is indexed from 0 to n-1. The elements within each of the n sequences also use 0-indexing. Create an integer, lastAnswer, and initialize it to 0. There are 2 types of queries that can be performed on the list of sequences: 1. Query: 1 x y a. Find the sequence, seq, at index ((x xor lastAnswer)%n) in seqList.

View Solution →

Left Rotation

A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. Given an integer, d, rotate the array that many steps left and return the result. Example: d=2 arr=[1,2,3,4,5] After 2 rotations, arr'=[3,4,5,1,2]. Function Description: Complete the rotateLeft function in the editor below. rotateLeft has the following parameters: 1. int d

View Solution →

Sparse Arrays

There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results. Example: strings=['ab', 'ab', 'abc'] queries=['ab', 'abc', 'bc'] There are instances of 'ab', 1 of 'abc' and 0 of 'bc'. For each query, add an element to the return array, results=[2,1,0]. Fun

View Solution →

Array Manipulation

Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array. Example: n=10 queries=[[1,5,3], [4,8,7], [6,9,1]] Queries are interpreted as follows: a b k 1 5 3 4 8 7 6 9 1 Add the valu

View Solution →