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

Components in a graph

There are 2 * N nodes in an undirected graph, and a number of edges connecting some nodes. In each edge, the first value will be between 1 and N, inclusive. The second node will be between N + 1 and , 2 * N inclusive. Given a list of edges, determine the size of the smallest and largest connected components that have or more nodes. A node can have any number of connections. The highest node valu

View Solution →

Kundu and Tree

Kundu is true tree lover. Tree is a connected graph having N vertices and N-1 edges. Today when he got a tree, he colored each edge with one of either red(r) or black(b) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex a to b, vertex b to c and vertex c to a . Note that

View Solution →

Super Maximum Cost Queries

Victoria has a tree, T , consisting of N nodes numbered from 1 to N. Each edge from node Ui to Vi in tree T has an integer weight, Wi. Let's define the cost, C, of a path from some node X to some other node Y as the maximum weight ( W ) for any edge in the unique path from node X to Y node . Victoria wants your help processing Q queries on tree T, where each query contains 2 integers, L and

View Solution →

Contacts

We're going to make our own Contacts application! The application must perform two types of operations: 1 . add name, where name is a string denoting a contact name. This must store name as a new contact in the application. find partial, where partial is a string denoting a partial name to search the application for. It must count the number of contacts starting partial with and print the co

View Solution →

No Prefix Set

There is a given list of strings where each string contains only lowercase letters from a - j, inclusive. The set of strings is said to be a GOOD SET if no string is a prefix of another string. In this case, print GOOD SET. Otherwise, print BAD SET on the first line followed by the string being checked. Note If two strings are identical, they are prefixes of each other. Function Descriptio

View Solution →

Cube Summation

You are given a 3-D Matrix in which each block contains 0 initially. The first block is defined by the coordinate (1,1,1) and the last block is defined by the coordinate (N,N,N). There are two types of queries. UPDATE x y z W updates the value of block (x,y,z) to W. QUERY x1 y1 z1 x2 y2 z2 calculates the sum of the value of blocks whose x coordinate is between x1 and x2 (inclusive), y coor

View Solution →