Requirement


Problem Statement :


There are n variables and m requirements. Requirements are represented as (x <= y), meaning that the xth variable must be less than or equal to the yth variable.

Your task is to assign non-negative numbers smaller than 10 to each variable and then calculate the number of different assignments satisfying all requirements. Two assignments are different if and only if at least one variable is assigned to a different number in both assignments. Print your answer modulo  10^3 + 7.

Input Format

The first line contains 2 space-separated integers, n and m, respectively. Each of the m subsequent lines contains 2 space-seperated integers describing the respective x and y values for an (x <= y) requirement.

Constraints

0 < n < 14
0 < m < 200
0 < = x,y < n
Output Format

Print your answer modulo 10^3+7.



Solution :



title-img


                            Solution in C :

In C++ :





#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <cstring>
#include <sstream>
#include <vector>
#include <map>
#include <set>
#include <functional>
#include <numeric>
#include <utility>

using namespace std;

#define Rep(i,n) for(int i = 0; i < n; ++i)
#define Rep2(i, f, t) for(int i = (f); i <= (t); ++i)
#define tr(C,it) for(__typeof__((C).begin()) it = (C).begin();
#define it != (C).end(); ++it)
#define two(x) (1<<(x))

const int maxn = 13;
const int mod = 1007;
int req[maxn];
int sreq[1<<maxn], cnt[1<<maxn];
int n;
int tot_st;

int main() {
	int m;
	scanf("%d%d", &n, &m);
	int x, y;
	while(m--) {
		scanf("%d%d", &x, &y);
		req[x] |= two(y);
	}

	tot_st = 1<<n;
	sreq[0] = 0;
	Rep(i, n) {
		sreq[two(i)] = req[i];
	}
	Rep(i, tot_st) {
		if((i > 0) && ((i & -i) != i)) {
			int lowbit = i & -i;
			sreq[i] = sreq[i ^ lowbit] | sreq[lowbit];
		}
	}
	cnt[0] = 1;
	Rep(i, 10) {
		for(int j = tot_st - 1; j > 0; --j) {
			int A = j;
			while(A > 0) {
				if((sreq[A] & j) == sreq[A]) {
					cnt[j] += cnt[j ^ A];
				}

				A = (A - 1) & j;
			}
			cnt[j] %= mod;
		}

	}
	
	printf("%d\n", cnt[tot_st - 1]);
	return 0;
}








In Java :






import java.io.*;
import java.math.BigInteger;
import java.util.Random;
import java.util.StringTokenizer;

public class Solution {

    // leave empty to read from stdin/stdout
    private static final String TASK_NAME_FOR_IO = "";

    // file names
    private static final String FILE_IN = TASK_NAME_FOR_IO + ".in";
    private static final String FILE_OUT = TASK_NAME_FOR_IO + ".out";

    BufferedReader in;
    PrintWriter out;
    StringTokenizer tokenizer = new StringTokenizer("");

    public static void main(String[] args) {
        new Solution().run();
    }

    int n;
    boolean[][] a;

    private void solve() throws IOException {
        // stress();
        // timing();

        n = nextInt();
        int m = nextInt();
        a = new boolean[n][n];
        for (int k = 0; k < m; k++) {
            int u = nextInt();
            int v = nextInt();
            a[v][u] = true;
        }

        out.print(solveFast());
    }

    private void timing() {

        Random r = new Random(987654321L);
        int tcNum = 10000;

        /*
        for (int tcIdx = 0; tcIdx < tcNum; tcIdx++) {

            n = r.nextInt(9);
            a = new boolean[n][n];

            int m = r.nextInt(n * (n - 1) / 2 + 1);
            while (m > 0) {
                int i = r.nextInt(n);
                int j = r.nextInt(n);
                int k = r.nextInt(2);
                if (k == 0) {
                    a[i][j] = true;
                } else {
                    a[j][i] = true;
                }
                m--;
            }

            int ans = solveFast();
            System.out.println("OK (" + tcIdx + "/" + tcNum + "): " + ans);
        }
        */

        n = 13;
        a = new boolean[n][n];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++) {
                a[i][j] = true;
            }
        solveFast();

        /*
        for (int tcIdx = 0; tcIdx < tcNum; tcIdx++) {

            n = 13;
            a = new boolean[n][n];
            for (int i = 0; i < n; i++)
                for (int j = i + 1; j < n; j++) {
                    int k = r.nextInt(2);
                    if (k == 0) {
                        a[i][j] = true;
                    } else {
                        a[j][i] = true;
                    }
                }

            long timeStart = System.currentTimeMillis();
            int ans = solveFast();
            long timeEnd = System.currentTimeMillis();

            System.out.println("OK (" + tcIdx + "/" + tcNum + "): " + ans);
            if (timeEnd - timeStart >= 2000) {
                System.err.println("!!! TL: " + (timeEnd - timeStart));

                int m = 0;
                for (int i = 0; i < n; i++)
                    for (int j = 0; j < n; j++)
                        if (a[i][j]) {
                            m++;
                        }

                System.err.println(n + " " + m);
                for (int i = 0; i < n; i++)
                    for (int j = 0; j < n; j++)
                        if (a[i][j]) {
                            System.err.println(i + " " + j);
                        }
            }
        }
        */
    }

    private void stress() {

        Random r = new Random(123456789L);
        int tcNum = 10000;
        for (int tcIdx = 0; tcIdx < tcNum; tcIdx++) {

            n = r.nextInt(8);
            a = new boolean[n][n];

            int m = r.nextInt(n * (n - 1) / 2 + 1);
            while (m > 0) {
                int i = r.nextInt(n);
                int j = r.nextInt(n);
                int k = r.nextInt(2);
                if (k == 0) {
                    a[i][j] = true;
                } else {
                    a[j][i] = true;
                }
                m--;
            }

            int ans1 = solveNaive();
            int ans2 = solveFast();
            if (ans1 == ans2) {
                System.out.println("OK (" + tcIdx + "/" + tcNum + "): "+ ans1 + " - " + ans2);
            } else {
                throw new IllegalStateException("Mismatch: " + ans1 + " " + ans2);
            }
        }

    }

    private int solveFast() {

        for (int i = 0; i < n; i++) {
            a[i][i] = false;
        }

        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                for (int k = 0; k < n; k++)
                    if (a[i][j] && a[j][k]) {
                        a[i][k] = false;
                    }

        for (int i = 0; i < n; i++) {
            reduce(i, i, 0, 0);
        }

        /*
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                for (int k = 0; k < n; k++)
                    if (a[i][j] && a[j][k]) {
                        a[i][k] = false;
                    }

        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                for (int k = 0; k < n; k++)
                    for (int l = 0; l < n; l++)
                        if (a[i][j] && a[j][k] && a[k][l]) {
                            a[i][l] = false;
                        }
        */


        int bestMask = getBestDominatingMask();
        assignedV = new int[n];
        return calcFast(0, bestMask);
    }

    private void reduce(int u, int src, int dist, int visited) {
        if ((visited & (1 << u)) != 0) {
            return;
        }
        visited |= 1 << u;

        if (dist > 1 && a[src][u]) {
            a[src][u] = false;
        }

        for (int v = 0; v < n; v++)
            if (a[u][v]) {
                reduce(v, src, dist + 1, visited);
            }
    }

    private int calcFast(int pos, int bestMask) {
        if (pos >= n) {

            // let's check where we are
            int answer = 1;
            for (int i = 0; i < n; i++)
                if ((bestMask & (1 << i)) != 0) {

                    for (int j = 0; j < n; j++) {
                        if (a[i][j] && ((bestMask & (1 << j)) != 0)) {
                            if (!(assignedV[i] >= assignedV[j])) {
                                return 0;
                            }
                        }
                        if (a[j][i] && ((bestMask & (1 << j)) != 0)) {
                            if (!(assignedV[j] >= assignedV[i])) {
                                return 0;
                            }
                        }
                    }

                } else {

                    // we have to determine the boundaries of i-th variable
                    int lo = 0;
                    int hi = 9;
                    for (int j = 0; j < n; j++) {

                        if (a[i][j]) {
                            if ((bestMask & (1 << j)) == 0) {
                                throw new IllegalStateException("Mask is not dominating");
                            }
                            lo = Math.max(lo, assignedV[j]);
                        }

                        if (a[j][i]) {
                            if ((bestMask & (1 << j)) == 0) {
                                throw new IllegalStateException("Mask is not dominating");
                            }
                            hi = Math.min(hi, assignedV[j]);
                        }

                    }

                    if (lo > hi) {
                        return 0;
                    }

                    answer *= hi - lo + 1;
                    if (answer >= MOD) {
                        answer %= MOD;
                    }

                }

            return answer;
        }

        // skip irrelevant vertices
        if ((bestMask & (1 << pos)) == 0) {
            return calcFast(pos + 1, bestMask);
        }

        // brute force
        int result = 0;
        for (int v = 0; v <= 9; v++){
            assignedV[pos] = v;
            result += calcFast(pos + 1, bestMask);
            if (result >= MOD) {
                result -= MOD;
            }
        }

        return result;
    }

    private int getBestDominatingMask() {
        int n2 = 1 << n;

        int bestBits = Integer.MAX_VALUE;
        int bestMask = Integer.MAX_VALUE;
        for (int mask = 0; mask < n2; mask++) {

            // let's iterate over all unmarked vertices
            boolean good = true;
            for (int i = 0; i < n; i++)
                if ((mask & (1 << i)) == 0) {

                    for (int j = 0; j < n; j++)
                        if (a[i][j] || a[j][i]) {
                            if ((mask & (1 << j)) == 0) {
                                good = false;
                                break;
                            }
                        }

                }

            if (good) {
                int bits = getBitCount(mask);
                if (bits < bestBits) {
                    bestBits = bits;
                    bestMask = mask;
                }
            }
        }
        return bestMask;
    }

    private int getBitCount(int mask) {
        int bits = 0;
        for (int j = 0; j < n; j++)
            if ((mask & (1 << j)) != 0) {
                bits++;
            }
        return bits;
    }

    private int solveNaive() {
        assignedV = new int[n];
        return calcNaive(0);
    }

    int[] assignedV;
    int MOD = 1007;

    private int calcNaive(int pos) {
        if (pos >= n) {
            boolean good = true;
            for (int i = 0; i < n; i++) {
                good &= checkAssignment(i, n - 1);
            }

            if (good) {
                return 1;
            }
            return 0;
        }

        int result = 0;
        for (int v = 0; v <= 9; v++){
            assignedV[pos] = v;
            if (checkAssignment(pos, pos)) {
                result += calcNaive(pos + 1);
                if (result >= MOD) {
                    result -= MOD;
                }
            }
        }

        return result;
    }

    private boolean checkAssignment(int pos, int limit) {
        // means that X[pos] >= X[i]
        boolean good = true;
        for (int i = 0; i < n; i++) {
            // variable has not been defined yet
            if (i > limit) {
                break;
            }

            // the following should hold: X[pos] >= X[i]
            if (a[pos][i] && !(assignedV[pos] >= assignedV[i])) {
                good = false;
                break;
            }

        }

        for (int i = 0; i < n; i++) {
            // variable has not been defined yet
            if (i > limit) {
                break;
            }

            // the following should hold: X[i] >= X[pos]
            if (a[i][pos] && !(assignedV[i] >= assignedV[pos])) {
                good = false;
                break;
            }
        }

        return good;
    }

    public void run() {
        long timeStart = System.currentTimeMillis();

        boolean fileIO = TASK_NAME_FOR_IO.length() > 0;
        try {

            if (fileIO) {
                in = new BufferedReader(new FileReader(FILE_IN));
                out = new PrintWriter(new FileWriter(FILE_OUT));
            } else {
                in = new BufferedReader(new InputStreamReader(System.in));
                out = new PrintWriter(new OutputStreamWriter(System.out));
            }

            solve();

            in.close();
            out.close();
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
        long timeEnd = System.currentTimeMillis();

        if (fileIO) {
            System.out.println("Time spent: " + (timeEnd - timeStart) + " ms");
        }
    }

    private String nextToken() throws IOException {
        while (!tokenizer.hasMoreTokens()) {
            String line = in.readLine();
            if (line == null) {
                return null;
            }
            tokenizer = new StringTokenizer(line);
        }
        return tokenizer.nextToken();
    }

    private int nextInt() throws IOException {
        return Integer.parseInt(nextToken());
    }

    private BigInteger nextBigInt() throws IOException {
        return new BigInteger(nextToken());
    }

    private long nextLong() throws IOException {
        return Long.parseLong(nextToken());
    }

    private double nextDouble() throws IOException {
        return Double.parseDouble(nextToken());
    }

}








In C :





#include <stdio.h>
#include <stdlib.h>

#define REQ_NONE 0
#define REQ_LE 1
#define REQ_EQ 2
#define REQ_GE 3

int n;
int m;

struct Req {
	int x;
	int y;
};

int ireq;
struct Req* oreqs;
int* counts;
int* sorted;

int** reqs;
int* depends;
int* conf;
int* start;
int* end;

void init() {
	ireq = 0;
	oreqs = (struct Req *)malloc(m * sizeof(struct Req));

	counts = (int *)malloc(n * sizeof(int));

	sorted = (int *)malloc(n * sizeof(int));

	reqs = (int **)malloc(n * sizeof(int *));
	for (int i = 0; i < n; ++i) {
		reqs[i] = (int *)malloc(n * sizeof(int));
		for (int j = 0; j < n; ++j) {
			reqs[i][j] = REQ_NONE;
		}
	}

	depends = (int *)malloc(n * sizeof(int));

	conf = (int *)malloc(n * sizeof(int));

	start = (int *)malloc(n * sizeof(int));
	end = (int *)malloc(n * sizeof(int));
}

void addReq(int x, int y) {
	oreqs[ireq].x = x;
	oreqs[ireq].y = y;
	++ireq;

	++counts[x];
	++counts[y];
}

void sort() {
	for (int i = 0; i < n; ++i) {
		sorted[i] = i;
	}

	for (int i = 0; i < n-1; ++i) {
		for (int j = 0; j < n; ++j) {
			if (counts[sorted[i]] > counts[sorted[j]]) {
				int t = sorted[i];
				sorted[i] = sorted[j];
				sorted[j] = t;
			}
		}
	}
}

void setReq(int x, int y) {
	if (x < y) {
		if (reqs[x][y] == REQ_NONE) {
			reqs[x][y] = REQ_LE;
		} else if (reqs[x][y] == REQ_GE) {
			reqs[x][y] = REQ_EQ;
		}
	} else {
		if (reqs[y][x] == REQ_NONE) {
			reqs[y][x] = REQ_GE;
		} else if (reqs[x][y] == REQ_LE) {
			reqs[y][x] = REQ_EQ;
		}
	}
}

void initReqs() {
	sort();

	for (int i = 0; i < m; ++i) {
		setReq(sorted[oreqs[i].x], sorted[oreqs[i].y]);
	}
}

void initDepends() {
	for (int i = 0; i < n; ++i) {
		depends[i] = 0;
		for (int j = i + 1; j < n; ++j) {
			if (reqs[i][j] != REQ_NONE) {
				depends[i] = 1;
				break;
			}
		}
	}

	for (int i = 0; i < n; ++i) {
		int p;

		for (p = 0; p < i; ++p) {
			if (reqs[p][i] != REQ_NONE) {
				break;
			}
		}
		start[i] = p;

		for (p = i - 1; p >= 0; --p) {
			if (reqs[p][i] != REQ_NONE) {
				break;
			}
		}
		end[i] = p + 1;
	}
}

int count(int i) {
	int min = 0;
	int max = 9;

	for (int p = start[i]; p < end[i]; ++p) {
		if (reqs[p][i] != REQ_NONE) {
			if (reqs[p][i] == REQ_LE) {
				if (conf[p] > min) {
					min = conf[p];
					if (min > max) {
						return 0;
					}
				}
			} else if (reqs[p][i] == REQ_GE) {
				if (conf[p] < max) {
					max = conf[p];
					if (min > max) {
						return 0;
					}
				}
			} else {
				if (min == max && min != conf[p]) {
					return 0;
				}
				min = conf[p];
				max = conf[p];
			}
		}
	}

	if (!depends[i]) {
		if (i == n - 1) {
			return max - min + 1;
		}
		return ((max - min + 1) * count(i + 1)) % 1007;
	}

	int c = 0;
	for (int x = min; x <= max; ++x) {
		conf[i] = x;
		c = (c + count(i + 1)) % 1007;
	}
	return c;
}

void printReqs() {
	static char symbols[] = { '.', '<', '=', '>' };
	for (int i = 0; i < n; ++i) {
		for (int j = 0; j < n; ++j) {
			printf("%c ", symbols[reqs[i][j]]);
		}
		printf("\n");
	}
	printf("\n");
}

int main() {
	//n = 6;
	//m = 7;

	scanf("%d %d", &n, &m);

	//n = 14;
	//m = n - 1;

	init();

	for (int i = 0; i < m; ++i) {
		int x, y;
		scanf("%d %d", &x, &y);
		addReq(x, y);
	}

	//addReq(1, 3);
	//addReq(0, 1);
	//addReq(2, 4);
	//addReq(0, 4);
	//addReq(2, 5);
	//addReq(3, 4);
	//addReq(0, 2);

	//for (int i = 0; i < n - 1; ++i) {
	//	addReq(i, n-1);
	//}

	initReqs();
	//printReqs();

	initDepends();

	printf("%d\n", count(0));

	return 0;
}








In Python3 :





'''
Created on Mar 26, 2013

@author: edogyaz
'''
import sys

n = 6 # between 0-9
maxn = 10
reqs = [(0,1), (1,2)]
reqs3 = [(1,3), (1,2)]
reqs2 = [(1,3), (0,1), (2,4),(0,4), (2,5),(3,4),(0,2)]

## how many different assignments (modulo by 1007)

def match_reqs(acc_list, reqs):
    for a,b in reqs:
        if acc_list[a] > acc_list[b]:
            return False
    
        
    return True

def req(n, reqs, acc_list):
    print(n, reqs, acc_list)
    summ = 0
    if (n == 0):
        if match_reqs(acc_list, reqs):
            return 1
        else:
            return 0
    
    
    for i in range(maxn):
        summ += req(n-1, reqs, acc_list + [i])
         
#    return summ % 1007
    return summ


def req2(n, reqs):
    if (n == 0):
        assert(reqs == [])
        return list(map(lambda x: [x], range(maxn)))
    
    reqs1, reqs2 = split_reqs(reqs, n)
    
    solutions = []
    subsolutions = req2(n-1, reqs1)
    print(n, len(subsolutions))
    print("FUCK YOU")
    for i in range(maxn):
        solutions += filter_list(subsolutions, i, reqs2)
    
    return solutions

def req22(n, reqs):
    return len(req2(n - 1, reqs)) % 1007

def split_reqs(reqs, n):
    reqs1 = []
    reqs2 = []
    for a,b in reqs:
        if a == n or b == n:
            reqs2.append((a,b))
        else:
            reqs1.append((a,b))
    return reqs1, reqs2

def filter_list(solutions, newval, reqs):
    result = []
    for solution in solutions:
        if match_reqs(solution + [newval], reqs):
            result.append(solution + [newval])
    return result
    
from operator import mul
from functools import reduce

def rlen(r):
    a,b = r
    if a > b:
        return 0
    return b-a+1

def update_ranges(ranges, val, reqs):
    removed_var = len(ranges)
    updated = list(ranges)
    for a,b in reqs:
        if a == removed_var:
            x, y = updated[b]
            if val > x:
                updated[b] = (val, y)
        if b == removed_var:
            x, y = updated[a]
            if val < y:
                updated[a] = (x, val)
    return updated

    
memodict = {}    
def req3(ranges, reqs):
    if (reqs == []):
        return reduce(mul, map(rlen, ranges), 1)
    
    key = (tuple(ranges),tuple(reqs))
    if key in memodict:
        return memodict[key]
        
    
    summ = 0
    lastr = ranges[-1]
    rest = ranges[:-1]
    
    a,b = lastr
    unrelated, related = split_reqs(reqs, len(rest))
    
    for val in range(a,b+1):
        updated = update_ranges(rest, val, related)
        summ += req3(updated, unrelated)

    summ = summ % 1007       
    memodict[key] = summ
    return summ


def req33(n, reqs):
    return req3([(0, maxn-1)] * n, reqs) % 1007

#print(req(n, reqs2, []) % 1007)

def runcommand():
    req_list = []
    n,m = map(int, sys.stdin.readline().split())
    for _ in range(m):
        a,b = map(int, sys.stdin.readline().split())
        req_list.append((a,b))
        
    print(req33(n, req_list))

runcommand()

#print(req22(6, reqs2))
#print(req33(6, reqs2))
                        








View More Similar Problems

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 →

Compare two linked lists

You’re given the pointer to the head nodes of two linked lists. Compare the data in the nodes of the linked lists to check if they are equal. If all data attributes are equal and the lists are the same length, return 1. Otherwise, return 0. Example: list1=1->2->3->Null list2=1->2->3->4->Null The two lists have equal data attributes for the first 3 nodes. list2 is longer, though, so the lis

View Solution →

Merge two sorted linked lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the heads of two sorted linked lists, merge them into a single, sorted linked list. Either head pointer may be null meaning that the corresponding list is empty. Example headA refers to 1 -> 3 -> 7 -> NULL headB refers to 1 -> 2 -> NULL The new list is 1 -> 1 -> 2 -> 3 -> 7 -> NULL. Function Description C

View Solution →

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 →