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

Fibonacci Numbers Tree

Shashank loves trees and math. He has a rooted tree, T , consisting of N nodes uniquely labeled with integers in the inclusive range [1 , N ]. The node labeled as 1 is the root node of tree , and each node in is associated with some positive integer value (all values are initially ). Let's define Fk as the Kth Fibonacci number. Shashank wants to perform 22 types of operations over his tree, T

View Solution →

Pair Sums

Given an array, we define its value to be the value obtained by following these instructions: Write down all pairs of numbers from this array. Compute the product of each pair. Find the sum of all the products. For example, for a given array, for a given array [7,2 ,-1 ,2 ] Note that ( 7 , 2 ) is listed twice, one for each occurrence of 2. Given an array of integers, find the largest v

View Solution →

Lazy White Falcon

White Falcon just solved the data structure problem below using heavy-light decomposition. Can you help her find a new solution that doesn't require implementing any fancy techniques? There are 2 types of query operations that can be performed on a tree: 1 u x: Assign x as the value of node u. 2 u v: Print the sum of the node values in the unique path from node u to node v. Given a tree wi

View Solution →

Ticket to Ride

Simon received the board game Ticket to Ride as a birthday present. After playing it with his friends, he decides to come up with a strategy for the game. There are n cities on the map and n - 1 road plans. Each road plan consists of the following: Two cities which can be directly connected by a road. The length of the proposed road. The entire road plan is designed in such a way that if o

View Solution →

Heavy Light White Falcon

Our lazy white falcon finally decided to learn heavy-light decomposition. Her teacher gave an assignment for her to practice this new technique. Please help her by solving this problem. You are given a tree with N nodes and each node's value is initially 0. The problem asks you to operate the following two types of queries: "1 u x" assign x to the value of the node . "2 u v" print the maxim

View Solution →

Number Game on a Tree

Andy and Lily love playing games with numbers and trees. Today they have a tree consisting of n nodes and n -1 edges. Each edge i has an integer weight, wi. Before the game starts, Andy chooses an unordered pair of distinct nodes, ( u , v ), and uses all the edge weights present on the unique path from node u to node v to construct a list of numbers. For example, in the diagram below, Andy

View Solution →