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

Insert a Node at the Tail of a Linked List

You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty. Input Format: You have to complete the SinglyLink

View Solution →

Insert a Node at the head of a Linked List

Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node should point to head and the data value should be replaced with a given value. Return a reference to the new head of the list. The head pointer given may be null meaning that the initial list is empty. Function Description: Complete the function insertNodeAtHead in the editor below

View Solution →

Insert a node at a specific position in a linked list

Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is e

View Solution →

Delete a Node

Delete the node at a given position in a linked list and return a reference to the head node. The head is at position 0. The list may be empty after you delete the node. In that case, return a null value. Example: list=0->1->2->3 position=2 After removing the node at position 2, list'= 0->1->-3. Function Description: Complete the deleteNode function in the editor below. deleteNo

View Solution →

Print in Reverse

Given a pointer to the head of a singly-linked list, print each data value from the reversed list. If the given list is empty, do not print anything. Example head* refers to the linked list with data values 1->2->3->Null Print the following: 3 2 1 Function Description: Complete the reversePrint function in the editor below. reversePrint has the following parameters: Sing

View Solution →

Reverse a linked list

Given the pointer to the head node of a linked list, change the next pointers of the nodes so that their order is reversed. The head pointer given may be null meaning that the initial list is empty. Example: head references the list 1->2->3->Null. Manipulate the next pointers of each node in place and return head, now referencing the head of the list 3->2->1->Null. Function Descriptio

View Solution →