# 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

### Solution :

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";

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;
}
*/

assignedV = new int[n];
}

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
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;
}

}

}

// skip irrelevant vertices
if ((bestMask & (1 << pos)) == 0) {
}

// 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;
}

int n2 = 1 << n;

int bestBits = Integer.MAX_VALUE;

// 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) {
if (bits < bestBits) {
bestBits = bits;
}
}
}
}

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) {
out = new PrintWriter(new FileWriter(FILE_OUT));
} else {
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()) {
if (line == null) {
return null;
}
tokenizer = new StringTokenizer(line);
}
}

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);
}

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

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 = []
for _ in range(m):
req_list.append((a,b))

print(req33(n, req_list))

runcommand()

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

## Unique Colors

You are given an unrooted tree of n nodes numbered from 1 to n . Each node i has a color, ci. Let d( i , j ) be the number of different colors in the path between node i and node j. For each node i, calculate the value of sum, defined as follows: Your task is to print the value of sumi for each node 1 <= i <= n. Input Format The first line contains a single integer, n, denoti

## 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

## 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

## 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

## 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

## 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