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

Get Node Value

This challenge is part of a tutorial track by MyCodeSchool Given a pointer to the head of a linked list and a specific position, determine the data value at that position. Count backwards from the tail node. The tail is at postion 0, its parent is at 1 and so on. Example head refers to 3 -> 2 -> 1 -> 0 -> NULL positionFromTail = 2 Each of the data values matches its distance from the t

View Solution →

Delete duplicate-value nodes from a sorted linked list

This challenge is part of a tutorial track by MyCodeSchool You are given the pointer to the head node of a sorted linked list, where the data in the nodes is in ascending order. Delete nodes and return a sorted list with each distinct value in the original list. The given head pointer may be null indicating that the list is empty. Example head refers to the first node in the list 1 -> 2 -

View Solution →

Cycle Detection

A linked list is said to contain a cycle if any node is visited more than once while traversing the list. Given a pointer to the head of a linked list, determine if it contains a cycle. If it does, return 1. Otherwise, return 0. Example head refers 1 -> 2 -> 3 -> NUL The numbers shown are the node numbers, not their data values. There is no cycle in this list so return 0. head refer

View Solution →

Find Merge Point of Two Lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the head nodes of 2 linked lists that merge together at some point, find the node where the two lists merge. The merge point is where both lists point to the same node, i.e. they reference the same memory location. It is guaranteed that the two head nodes will be different, and neither will be NULL. If the lists share

View Solution →

Inserting a Node Into a Sorted Doubly Linked List

Given a reference to the head of a doubly-linked list and an integer ,data , create a new DoublyLinkedListNode object having data value data and insert it at the proper location to maintain the sort. Example head refers to the list 1 <-> 2 <-> 4 - > NULL. data = 3 Return a reference to the new list: 1 <-> 2 <-> 4 - > NULL , Function Description Complete the sortedInsert function

View Solution →

Reverse a doubly linked list

This challenge is part of a tutorial track by MyCodeSchool Given the pointer to the head node of a doubly linked list, reverse the order of the nodes in place. That is, change the next and prev pointers of the nodes so that the direction of the list is reversed. Return a reference to the head node of the reversed list. Note: The head node might be NULL to indicate that the list is empty.

View Solution →