Candles Counting


Problem Statement :


Tim is visiting his grandma for two days and is bored due to the lack of the electricity over there. That's why he starts to play with grandma's colorful candle collection.

He aligned the N candles from left to right. The ith candle from the left has the height Hi and the color Ci, an integer ranged from 1 to a given K, the number of colors.

Now he stares at the sequence of candles and wonders, how many strictly increasing ( in height ) colorful subsequences are there? A subsequence is considered as colorful if every of the K colors appears at least one times in the subsequence.

As the number of subsequences fulfilling the requirement can be large, print the result modulo 10^9+7.

Input Format

On the first line you will be given N and K, then N lines will follow. On the ith line you will be given two integers Hi and Ci.

Constraints
1 <= N <= 5.10^4
1 <= Ci <= K <= 7
1 <= Hi <= 5.10^4

Output Format

Print the number of strictly increasing colorful subsequences modulo 10^9+7.



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>

#define y0 sdkfaslhagaklsldk
#define y1 aasdfasdfasdf
#define yn askfhwqriuperikldjk
#define j1 assdgsdgasghsf
#define tm sdfjahlfasfh
#define lr asgasgash

#define eps 1e-11
//#define M_PI 3.141592653589793
#define bs 1000000007
#define bsize 128
#define right adsgasgadsg
#define free adsgasdg

using namespace std;

long n,k,h[1<<20],c[1<<20],t[1<<7][1<<17];
long nm,temp;
vector<pair<long, long> > v;

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

void add(long id,long i,long val)
{
 for (;i<=100000;i=(i|(i+1)))
  ad(t[id][i],val);
}

long sum(long id,long r)
{
 long res=0;
 for (;r>=0;r=(r&(r+1))-1)
  ad(res,t[id][r]);
 return res;
}


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

cin>>n>>k;

add(0,0,1);
for (int i=1;i<=n;i++)
{
 cin>>h[i]>>c[i];
 v.clear();
 for (int mask=0;mask<(1<<k);mask++)
 {
  nm=mask;
  nm|=(1<<(c[i]-1));
  temp=sum(mask,h[i]-1);
  v.push_back(make_pair(nm,temp));
 }
 for (int j=0;j<v.size();j++)
 {
  nm=v[j].first;
  temp=v[j].second;
  add(nm,h[i],temp);
 }
}
cout<<sum((1<<k)-1,100000)<<endl;

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








In Java :





import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;

public class C2 {
	static InputStream is;
	static PrintWriter out;
	static String INPUT = "";
	
	static void solve()
	{
		int n = ni(), K = ni();
		int[] h = new int[n];
		int[] c = new int[n];
		for(int i = 0;i < n;i++){
			h[i] = ni();
			c[i] = ni()-1;
		}
		int[][] fts = new int[1<<K][];
		for(int i = 0;i < 1<<K;i++){
			fts[i] = new int[50002];
		}
		addFenwick(fts[0], 0, 1);
		for(int i = 0;i < n;i++){
			for(int j = (1<<K)-1;j >= 0;j--){
				int sum = sumFenwick(fts[j], h[i]-1);
				addFenwick(fts[j|1<<c[i]], h[i], sum);
			}
		}
		out.println(sumFenwick(fts[(1<<K)-1], 50000));
	}
	
	static int mod = 1000000007;
	
	public static int sumFenwick(int[] ft, int i)
	{
		int sum = 0;
		for(i++;i > 0;i -= i&-i){
			sum += ft[i];
			if(sum >= mod)sum -= mod;
		}
		return sum;
	}
	
	public static void addFenwick(int[] ft, int i, int v)
	{
		if(v == 0 || i < 0)return;
		int n = ft.length;
		for(i++;i < n;i += i&-i){
			ft[i] += v;
			if(ft[i] >= mod)ft[i] -= mod;
		}
	}
	
	public static void main(String[] args) throws Exception
	{
		long S = System.currentTimeMillis();
		is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(
                INPUT.getBytes());
		out = new PrintWriter(System.out);
		
		solve();
		out.flush();
		long G = System.currentTimeMillis();
		tr(G-S+"ms");
	}
	
	private static boolean eof()
	{
		if(lenbuf == -1)return true;
		int lptr = ptrbuf;
		while(lptr < lenbuf)
                if(!isSpaceChar(inbuf[lptr++]))return false;
		
		try {
			is.mark(1000);
			while(true){
				int b = is.read();
				if(b == -1){
					is.reset();
					return true;
				}else if(!isSpaceChar(b)){
					is.reset();
					return false;
				}
			}
		} catch (IOException e) {
			return true;
		}
	}
	
	private static byte[] inbuf = new byte[1024];
	static int lenbuf = 0, ptrbuf = 0;
	
	private static int readByte()
	{
		if(lenbuf == -1)throw new InputMismatchException();
		if(ptrbuf >= lenbuf){
			ptrbuf = 0;
			try { lenbuf = is.read(inbuf); } catch (IOException e) 
                       { throw new InputMismatchException(); }
			if(lenbuf <= 0)return -1;
		}
		return inbuf[ptrbuf++];
	}
	
	private static boolean isSpaceChar(int c) { 
         return !(c >= 33 && c <= 126); }
	private static int skip() { 
        int b; while((b = readByte()) != -1 && isSpaceChar(b)); 
        return b; }
	
	private static double nd() { 
        return Double.parseDouble(ns()); }
	private static char nc() { return (char)skip(); }
	
	private static String ns()
	{
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while(!(isSpaceChar(b)))
                { // when nextLine, (isSpaceChar(b) && b != ' ')
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}
	
	private static char[] ns(int n)
	{
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while(p < n && !(isSpaceChar(b))){
			buf[p++] = (char)b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}
	
	private static char[][] nm(int n, int m)
	{
		char[][] map = new char[n][];
		for(int i = 0;i < n;i++)map[i] = ns(m);
		return map;
	}
	
	private static int[] na(int n)
	{
		int[] a = new int[n];
		for(int i = 0;i < n;i++)a[i] = ni();
		return a;
	}
	
	private static int ni()
	{
		int num = 0, b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}
		
		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}
	
	private static long nl()
	{
		long num = 0;
		int b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}
		
		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}
	
	private static void tr(Object... o) 
        { if(INPUT.length() != 0)
         System.out.println(Arrays.deepToString(o)); }
}








In C :






#include <stdio.h>
#include <stdlib.h>
#define MOD 1000000007
void get_num(int j,int shift,int *zero,int *one);
void init( int n );
void range_increment( int i, int j, int val, int *tree );
int query( int i, int *tree );
int dp[128][150000];
int H[50000],C[50000],N;
int mask[8]={0,0b1,0b11,0b111,0b1111,0b11111,0b111111,0b1111111};

int main(){
  int N,K,i,j,x,y,max=-1;
  for(i=0;i<128;i++)
    for(j=0;j<150000;j++)
      dp[i][j]=0;
  scanf("%d%d",&N,&K);
  for(i=0;i<N;i++){
    scanf("%d%d",H+i,C+i);
    if(max==-1 || H[i]>max)
      max=H[i];
  }
  init(max);
  for(i=0;i<N;i++){
    if(H[i]!=1)
      for(j=0;j<(1<<(K-1));j++){
        get_num(j,C[i]-1,&x,&y);
        range_increment(H[i],max,query(H[i]-1,&dp[y][0]),&dp[y][0]);
        if(!j)
          range_increment(H[i],max,1,&dp[y][0]);
        else
          range_increment(H[i],max,query(H[i]-1,&dp[x][0]),&dp[y][0]);
      }
    else
      range_increment(H[i],max,1,&dp[1<<(C[i]-1)][0]);
  }
  printf("%d",query(max,&dp[(1<<K)-1][0]));
  return 0;
}
void get_num(int j,int shift,int *zero,int *one){
  int x,y;
  x=((j<<1)&(~mask[shift+1]));
  y=(j&mask[shift]);
  *zero=(x|y);
  *one=((*zero)|(1<<shift));
  return;
}
void init( int n ){
  N = 1;
  while( N < n ) N *= 2;
}
void range_increment( int i, int j, int val, int *tree ){
  for( i += N, j += N; i <= j; i = ( i + 1 ) / 2, j = ( j - 1 ) / 2 )
  {
    if( i % 2 == 1 ) tree[i] = (tree[i] +val)%MOD;
    if( j % 2 == 0 ) tree[j] = (tree[j] +val)%MOD;
  }
}
int query( int i, int *tree ){
  int ans = 0,j;
  for( j = i + N; j; j /= 2 ) ans = (ans+tree[j])%MOD;
  return ans;
}
                        








View More Similar Problems

Is This a Binary Search Tree?

For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements: The data value of every node in a node's left subtree is less than the data value of that node. The data value of every node in a node's right subtree is greater than the data value of that node. Given the root node of a binary tree, can you determine if it's also a

View Solution →

Square-Ten Tree

The square-ten tree decomposition of an array is defined as follows: The lowest () level of the square-ten tree consists of single array elements in their natural order. The level (starting from ) of the square-ten tree consists of subsequent array subsegments of length in their natural order. Thus, the level contains subsegments of length , the level contains subsegments of length , the

View Solution →

Balanced Forest

Greg has a tree of nodes containing integer data. He wants to insert a node with some non-zero integer value somewhere into the tree. His goal is to be able to cut two edges and have the values of each of the three new trees sum to the same amount. This is called a balanced forest. Being frugal, the data value he inserts should be minimal. Determine the minimal amount that a new node can have to a

View Solution →

Jenny's Subtrees

Jenny loves experimenting with trees. Her favorite tree has n nodes connected by n - 1 edges, and each edge is ` unit in length. She wants to cut a subtree (i.e., a connected part of the original tree) of radius r from this tree by performing the following two steps: 1. Choose a node, x , from the tree. 2. Cut a subtree consisting of all nodes which are not further than r units from node x .

View Solution →

Tree Coordinates

We consider metric space to be a pair, , where is a set and such that the following conditions hold: where is the distance between points and . Let's define the product of two metric spaces, , to be such that: , where , . So, it follows logically that is also a metric space. We then define squared metric space, , to be the product of a metric space multiplied with itself: . For

View Solution →

Array Pairs

Consider an array of n integers, A = [ a1, a2, . . . . an] . Find and print the total number of (i , j) pairs such that ai * aj <= max(ai, ai+1, . . . aj) where i < j. Input Format The first line contains an integer, n , denoting the number of elements in the array. The second line consists of n space-separated integers describing the respective values of a1, a2 , . . . an .

View Solution →