You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?

The first line contains two integers n, m (1 ≤ n, m ≤ 2000) — the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0 ≤ x, y ≤ 109) — the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles.

Print exactly one integer — the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.

NoteCells, reachable in the corresponding example, are marked with '+'.First example:  +++..+***.+++***+++. Second example:  .++..+*..++..++.

import core.bitop, std.bitmanip;
import std.algorithm, std.functional;
import std.array, std.container;
import std.conv;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

immutable int INF = 10L ^^ 9 + 23;

void main()
{
    int n, m;
    readf("%s %s", &n, &m);
    readln;

    int r, c;
    readf("%s %s", &r, &c);
    readln;
    --r, --c;

    int x, y;
    readf("%s %s", &x, &y);
    readln;

    string[] arr;
    foreach (_; 0 .. n) { arr ~= readln.chomp; }

    auto vis = new int[][][] (n, m, 2);
    foreach (i; 0 .. n) {
        foreach (j; 0 .. m) {
            vis[i][j].fill([-1, -1]);
        }
    }

    int bfs(int sx, int sy, int mvle, int mvr) {
        auto q = make!(DList!(Tuple!(int, int)));

        vis[sx][sy] = [mvle, mvr];
        q.insertFront(tuple(sx, sy));

        auto dirs = [[-1, 0], [1, 0], [0, -1], [0, 1]];
        auto qback = (int a, int b) => q.insertBack(tuple(a, b));
        auto qfront = (int a, int b) => q.insertFront(tuple(a, b));
        auto qfunc = [qfront, qfront, qback, qback];
        auto rcchg = [(int a, int b) => [a, b], (int a, int b) => [a, b],
                      (int a, int b) => [a-1, b], (int a, int b) => [a, b-1]];

        int ans = 0;
        while (! q.empty()) {
            auto t = q.front;
            q.removeFront();

            debug { writeln(t, ' ', vis[t[0]][t[1]]); }
            ++ans;
            auto cx = t[0], cy = t[1];
            auto cle = vis[cx][cy][0], cr = vis[cx][cy][1];

            foreach (i; 0 .. 4) {
                int nx = cx + dirs[i][0], ny = cy + dirs[i][1];
                if (nx < 0 || nx >= n || ny < 0 || ny >= m) { continue; }
                if (arr[nx][ny] == '*') { continue; }

                if (vis[nx][ny][0] != -1) { continue; }

                auto nchg = rcchg[i](cle, cr);
                if (nchg[0] < 0 || nchg[1] < 0) { continue; }

                vis[nx][ny] = nchg;
                qfunc[i](nx, ny);
            }
        }

        return ans;
    }

    bfs(r, c, x, y).writeln;
}

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;
import std.typecons;

void main ()
{
	int rows, cols;
	while (readf (" %s %s", &rows, &cols) > 0)
	{
		int sRow, sCol;
		readf (" %s %s", &sRow, &sCol);
		int lLimit, rLimit;
		readf (" %s %s", &lLimit, &rLimit);
		auto board = new char [] [] (rows + 2, cols + 2);
		foreach (ref line; board)
		{
			line[] = '#';
		}
		foreach (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				readf (" %s", &board[row + 1][col + 1]);
			}
		}

		alias Coord = Tuple !(int, q{row}, int, q{col});
		auto deque = new Coord [rows * cols * 4 + 1];
		int qb = rows * cols * 2;
		int qe = rows * cols * 2;
		auto f = new int [] [] (rows + 2, cols + 2);

		void go (int row, int col, int extra, int add)
		{
			debug {writeln (extra, " ", add, " ", row, " ", col);}
			if (board[row][col] != '.')
			{
				if (board[row][col] != '+' ||
				    f[row][col] <= extra + add)
				{
					return;
				}
			}
			if (add)
			{
				deque[qe] = Coord (row, col);
				qe += 1;
			}
			else
			{
				qb -= 1;
				deque[qb] = Coord (row, col);
			}
			board[row][col] = '+';
			f[row][col] = extra + add;
		}

		go (sRow, sCol, 0, 0);

		while (qb < qe)
		{
			int row = deque[qb].row;
			int col = deque[qb].col;
			int extra = f[row][col];
			qb += 1;

			go (row - 1, col, extra, 0);
			go (row + 1, col, extra, 0);

			{
				int nRow = row;
				int nCol = col + 1;
				int add = (nCol <= sCol);
				int rSteps = max (0, nCol - sCol) +
				    extra + add;
				if (rSteps <= rLimit)
				{
					go (nRow, nCol, extra, add);
				}
			}

			{
				int nRow = row;
				int nCol = col - 1;
				int add = (sCol <= nCol);
				int lSteps = max (0, sCol - nCol) +
				    extra + add;
				if (lSteps <= lLimit)
				{
					go (nRow, nCol, extra, add);
				}
			}
		}

		debug {writefln ("%-(%s\n%)", board);}
		writeln (board.map !(line => line.count ('+')).sum);
		break;
	}
}

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;
import std.typecons;

void main ()
{
	int rows, cols;
	while (readf (" %s %s", &rows, &cols) > 0)
	{
		int sRow, sCol;
		readf (" %s %s", &sRow, &sCol);
		int lLimit, rLimit;
		readf (" %s %s", &lLimit, &rLimit);
		auto board = new char [] [] (rows + 2, cols + 2);
		foreach (ref line; board)
		{
			line[] = '#';
		}
		foreach (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				readf (" %s", &board[row + 1][col + 1]);
			}
		}

		alias Coord = Tuple !(int, q{row}, int, q{col});
		auto deque = new Coord [rows * cols * 2 + 1];
		int qb = rows * cols;
		int qe = rows * cols;
		auto f = new int [] [] (rows + 2, cols + 2);

		void go (int row, int col, int extra, int add)
		{
			if (board[row][col] != '.')
			{
				return;
			}
			if (add)
			{
				deque[qe] = Coord (row, col);
				qe += 1;
			}
			else
			{
				qb -= 1;
				deque[qb] = Coord (row, col);
			}
			board[row][col] = '+';
			f[row][col] = extra + add;
		}

		qb -= 1;
		deque[qb] = Coord (sRow, sCol);
		board[sRow][sCol] = '+';

		while (qb < qe)
		{
			int row = deque[qb].row;
			int col = deque[qb].col;
			int extra = f[row][col];
			qb += 1;

			go (row - 1, col, extra, 0);
			go (row + 1, col, extra, 0);

			{
				int nRow = row;
				int nCol = col + 1;
				int add = (nCol <= sCol);
				int rSteps = max (0, nCol - sCol) +
				    extra + add;
				if (rSteps <= rLimit)
				{
					go (nRow, nCol, extra, add);
				}
			}

			{
				int nRow = row;
				int nCol = col - 1;
				int add = (sCol <= nCol);
				int lSteps = max (0, sCol - nCol) +
				    extra + add;
				if (lSteps <= lLimit)
				{
					go (nRow, nCol, extra, add);
				}
			}
		}

		debug {writefln ("%-(%s\n%)", board);}
		writeln (board.map !(line => line.count ('+')).sum);
	}
}


This is an interactive problemGinny is taking an exam on game theory. The professor is tired of hearing the same answers over and over again, so he offered Ginny to play a game instead of a standard exam. As known from the course, a combinatorial game on a graph with multiple starting positions is a game with a directed graph and multiple starting vertices holding a token each. Two players take turns moving one of the tokens along the graph edges on each turn. The player who can't make a move loses the game. If both players can play an infinitely long game without losing, a draw is called.For the exam, the professor drew an acyclic directed graph and chose one of its vertices. Ginny needs to guess the vertex the professor chose. To do so, Ginny can choose a multiset of vertices $$$S$$$ several times and ask the professor: "If I put one token in each vertex of the given graph for each occurrence of the vertex in the multiset $$$S$$$, and then one more in the selected vertex, what would be the result of the combinatorial game?". Having given the task, the professor left the room to give Ginny some time to prepare for the game. Ginny thinks that she's being tricked because the problem is impossible to solve. Therefore, while the professor is away, she wants to add or remove several edges from the graph. Even though the original graph was acyclic, edges could be added to the graph to make cycles appear.

3 2 3
1 2
2 3

Lose

Correct

Win

Correct

Draw

Correct

NoteIn the sample test, the empty lines represent waiting for the input by the other side of the interaction. The real interactor will not print empty lines, and the solution should not print them either.   The image above illustrates the sample test. Added edges are coloured in red, and the removed edges are drawn with a dotted line. Three guessing phases denote different ways of getting the answer.   If the solution will query just the chosen vertex, the interactor will return the result of the game in that vertex. The first player loses only if the chosen vertex has the number $$$1$$$.  If we add a single vertex $$$2$$$ to the chosen vertex, then if the chosen vertex is either $$$1$$$ or $$$2$$$, the game should end in a draw. If vertex number $$$3$$$ is chosen, then the first player wins.  If we place three tokens in vertex $$$1$$$ and two tokens in vertex $$$3$$$, then the game will end in a draw only if vertex $$$2$$$ is chosen. If the professor chose vertex $$$3$$$, the first player will win, if the professor chose vertex $$$1$$$, then the second player will win. In the first test, the interactor will behave as if the chosen vertices are the same as those in the example above. However, if you will try to guess the answer before it limits the options to one single vertex, the solution will get "Wrong Answer", even if you print the same answers. That's because the interactor is allowed to change the chosen vertex if it's consistent with the previous query answers.

import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.bitmanip, std.complex, std.container, std.math, std.mathspecial, std.numeric, std.regex, std.typecons;
import core.bitop;

class EOFException : Throwable { this() { super("EOF"); } }
string[] tokens;
string readToken() { for (; tokens.empty; ) { if (stdin.eof) { throw new EOFException; } tokens = readln.split; } auto token = tokens.front; tokens.popFront; return token; }
int readInt() { return readToken.to!int; }
long readLong() { return readToken.to!long; }
real readReal() { return readToken.to!real; }

bool chmin(T)(ref T t, in T f) { if (t > f) { t = f; return true; } else { return false; } }
bool chmax(T)(ref T t, in T f) { if (t < f) { t = f; return true; } else { return false; } }

int binarySearch(alias pred, T)(in T[] as) { int lo = -1, hi = cast(int)(as.length); for (; lo + 1 < hi; ) { const mid = (lo + hi) >> 1; (unaryFun!pred(as[mid]) ? hi : lo) = mid; } return hi; }
int lowerBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a >= val)); }
int upperBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a > val)); }

int N, M;
int[] A, B;

int[][] G;
bool[] vis;
int[] us;

void dfs(int u) {
  if (!vis[u]) {
    vis[u] = true;
    foreach (i; G[u]) {
      dfs(B[i]);
    }
    us ~= u;
  }
}

void main() {
  N = readInt();
  M = readInt();
  const T = readInt();
  A = new int[M];
  B = new int[M];
  foreach (i; 0 .. M) {
    A[i] = readInt() - 1;
    B[i] = readInt() - 1;
  }

  G = new int[][N];
  foreach (i; 0 .. M) {
    G[A[i]] ~= i;
  }
  vis = new bool[N];
  foreach (u; 0 .. N) {
    dfs(u);
  }
  debug {
    writeln("us = ", us);
  }

  auto ids = new int[N];
  foreach (x; 0 .. N) {
    ids[us[x]] = x;
  }
  auto adj = new bool[][](N, N);
  foreach (i; 0 .. M) {
    adj[ids[A[i]]][ids[B[i]]] = true;
  }
  alias Entry = Tuple!(char, "sig", int, "x", int, "y");
  Entry[] es;
  void add(int x, int y) {
    assert(!adj[x][y]);
    adj[x][y] = true;
    es ~= Entry('+', x, y);
  }
  void rem(int x, int y) {
    assert(adj[x][y]);
    adj[x][y] = false;
    es ~= Entry('-', x, y);
  }
  void flip(int x, int y) {
    if (!adj[x][y]) {
      add(x, y);
    } else {
      rem(x, y);
    }
  }

  debug {
    const K = min(N, 2);
  } else {
    const K = min(N, 20);
  }
  foreach (x; 0 .. K) {
    foreach (y; 0 .. N) {
      if (x != y) {
        if (adj[x][y] != (y < x)) {
          flip(x, y);
        }
      }
    }
  }
  int[] ps;
  foreach (l; 0 .. 3 + 1) {
    foreach (p; 0 .. 1 << K) {
      if (popcnt(p) == l) {
        ps ~= p;
      }
    }
  }
  auto tr = new int[1 << K];
  tr[] = -1;
  foreach (x; K .. N) {
    add(x, x);
    int key;
    foreach (y; 0 .. K) {
      if (adj[x][y]) {
        key ^= 1 << y;
      }
    }
    foreach (p; ps) {
      const q = key ^ p;
      if (tr[q] == -1 && q != (1 << K) - 1) {
        tr[q] = x;
        foreach (y; 0 .. K) {
          if (p & 1 << y) {
            flip(x, y);
          }
        }
        break;
      }
    }
  }

  writeln(es.length);
  foreach (ref e; es) {
    writefln("%s %s %s", e.sig, us[e.x] + 1, us[e.y] + 1);
  }
  stdout.flush;

  int ask(int[] xs) {
    writef("? %s", xs.length);
    foreach (x; xs) {
      writef(" %s", us[x] + 1);
    }
    writeln;
    stdout.flush;
    const res = readToken();
    switch (res) {
      case "Win": return +1;
      case "Lose": return 0;
      case "Draw": return -1;
      default: assert(false);
    }
  }

  foreach (t; 0 .. T) {
    auto ress = new int[K];
    foreach (x; 0 .. K) {
      ress[x] = ask([x]);
    }
    int ans = -1;
    if (ress.all!"a != -1") {
      foreach (x; 0 .. K) {
        if (ress[x] == 0) {
          ans = x;
        }
      }
    } else {
      int p;
      foreach (x; 0 .. K) {
        if (ress[x] == 1) {
          p ^= 1 << x;
        }
      }
      ans = tr[p];
    }
    writefln("! %s", us[ans] + 1);
    stdout.flush;
    const verdict = readToken();
    assert(verdict == "Correct");
  }
}


You are given an array $$$a$$$ consisting of $$$n$$$ distinct positive integers.Let's consider an infinite integer set $$$S$$$ which contains all integers $$$x$$$ that satisfy at least one of the following conditions: $$$x = a_i$$$ for some $$$1 \leq i \leq n$$$. $$$x = 2y + 1$$$ and $$$y$$$ is in $$$S$$$. $$$x = 4y$$$ and $$$y$$$ is in $$$S$$$.For example, if $$$a = [1,2]$$$ then the $$$10$$$ smallest elements in $$$S$$$ will be $$$\{1,2,3,4,5,7,8,9,11,12\}$$$.Find the number of elements in $$$S$$$ that are strictly smaller than $$$2^p$$$. Since this number may be too large, print it modulo $$$10^9 + 7$$$.

The first line contains two integers $$$n$$$ and $$$p$$$ $$$(1 \leq n, p \leq 2 \cdot 10^5)$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ $$$(1 \leq a_i \leq 10^9)$$$. It is guaranteed that all the numbers in $$$a$$$ are distinct.

Print a single integer, the number of elements in $$$S$$$ that are strictly smaller than $$$2^p$$$. Remember to print it modulo $$$10^9 + 7$$$.

import std.stdio;
import core.bitop;
import std.math;
import std.numeric;
import std.container;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

struct ModInt(long mod) {
    invariant() {
        assert(0 <= val && val < mod);
    }
    long val;
    this(long v) { this.val = (mod * mod + v) % mod; }
    ModInt opBinary(string op : "+")(int y) const { return ModInt(this.val + y); }
    ModInt opBinary(string op : "-")(int y) const { return ModInt(this.val - y); }
    ModInt opBinary(string op : "*")(int y) const { return ModInt(this.val * y); }
    ModInt opBinary(string op : "/")(int y) const { return ModInt(this.val * inv(y)); }
    ModInt opBinary(string op : "+")(long y) const { return ModInt(this.val + y); }
    ModInt opBinary(string op : "-")(long y) const { return ModInt(this.val - y); }
    ModInt opBinary(string op : "*")(long y) const { return ModInt(this.val * y); }
    ModInt opBinary(string op : "/")(long y) const { return ModInt(this.val * inv(y)); }
    ModInt opBinary(string op : "+")(ModInt y) const { return ModInt(this.val + y.val); }
    ModInt opBinary(string op : "-")(ModInt y) const { return ModInt(this.val - y.val); }
    ModInt opBinary(string op : "*")(ModInt y) const { return ModInt(this.val * y.val); }
    ModInt opBinary(string op : "/")(ModInt y) const { return ModInt(this.val * inv(y.val)); }
    ModInt opBinaryRight(string op : "+")(int y) const { return ModInt(this.val + y); }
    ModInt opBinaryRight(string op : "-")(int y) const { return ModInt(y - this.val); }
    ModInt opBinaryRight(string op : "*")(int y) const { return ModInt(this.val * y); }
    ModInt opBinaryRight(string op : "/")(int y) const { return ModInt(inv(this.val) * y); }
    ModInt opBinaryRight(string op : "+")(long y) const { return ModInt(this.val + y); }
    ModInt opBinaryRight(string op : "-")(long y) const { return ModInt(y - this.val); }
    ModInt opBinaryRight(string op : "*")(long y) const { return ModInt(this.val * y); }
    ModInt opBinaryRight(string op : "/")(long y) const { return ModInt(inv(this.val) * y); }
    void opAssign(int y) { this.val = y; }
    void opAssign(long y) { this.val = y; }
    void opOpAssign(string op : "+")(int y) { this.val = (this.val + mod * mod + y) % mod; }
    void opOpAssign(string op : "-")(int y) { this.val = (this.val + mod * mod - y) % mod; }
    void opOpAssign(string op : "*")(int y) { this.val = (this.val * y) % mod; }
    void opOpAssign(string op : "/")(int y) { this.val = (this.val * inv(y)) % mod; }
    void opOpAssign(string op : "+")(long y) { this.val = (this.val + mod * mod + y) % mod; }
    void opOpAssign(string op : "-")(long y) { this.val = (this.val + mod * mod - y) % mod; }
    void opOpAssign(string op : "*")(long y) { this.val = (this.val * y) % mod; }
    void opOpAssign(string op : "/")(long y) { this.val = (this.val * inv(y)) % mod; }
    void opOpAssign(string op : "+")(ModInt y) { this.val = (this.val + mod * mod + y.val) % mod; }
    void opOpAssign(string op : "-")(ModInt y) { this.val = (this.val + mod * mod - y.val) % mod; }
    void opOpAssign(string op : "*")(ModInt y) { this.val = (this.val * y.val) % mod; }
    void opOpAssign(string op : "/")(ModInt y) { this.val = (this.val * inv(y.val)) % mod; }
    ModInt opUnary(string op : "-")() const { return ModInt(mod - this.val); }
    string toString() const { return val.to!string; }
    static long extgcd(long a, long b, ref long x, ref long y) {
        if (b == 0) {
            x = 1;
            y = 0;
            return a;
        }
        long d = extgcd(b, a % b, y, x);
        y -= a / b * x;
        return d;
    }
    static long inv(long a) {
        long x, y;
        extgcd(a, mod, x, y);
        return (x % mod + mod) % mod;
    }
}
alias MInt = ModInt!(cast(long)(1e9+7));

void main() {
    int N, P; readf("%d %d\n", &N, &P);
    auto A = readarray!int;
    A.sort;
    bool[int] S;
    bool find(int a) {
        // a is already in S
        for (int k = 0; k <= 31; k++) {
            int x = a >> k;
            if (x in S) {
                // check
                auto fmt = "%0" ~ k.to!string ~ "b";
                string s = format(fmt, a & ((1<<k) - 1));
                bool c() {
                    for (int j = 0; j < s.length; j++) {
                        if (s[j] == '0') {
                            if (j == s.length - 1 || s[j + 1] != '0') return false;
                            j++;
                        }
                    }
                    return true;
                }
                if (c()) {
                    return true;
                }
            }
        }
        return false;
    }

    auto f = new MInt[P + 1];
    f[0] = 0;
    f[1] = 1;
    for (int n = 2; n <= P; n++) {
        f[n] = f[n - 2] + f[n - 1];
    }
    auto g = new MInt[P + 2];
    g[0] = 0;
    for (int n = 0; n <= P; n++) {
        g[n + 1] = g[n] + f[n];
    }
    //writeln(f);

    MInt ans = 0;
    for (int i = 0; i < N; i++) {
        int a = A[i];
        //writeln("a: ", a);
        if (find(a)) continue;
        int k = bsr(a);
        MInt nd = g[max(0, P - k + 1)];
        ans += nd;
        //writeln("k: ", k);
        //writeln("d: ", d);
        S[a] = true;
    }
    writeln(ans);
}

import std.stdio;
import core.bitop;
import std.math;
import std.numeric;
import std.container;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

struct ModInt(long mod) {
    invariant() {
        assert(0 <= val && val < mod);
    }
    long val;
    this(long v) { this.val = (mod * mod + v) % mod; }
    ModInt opBinary(string op : "+")(int y) const { return ModInt(this.val + y); }
    ModInt opBinary(string op : "-")(int y) const { return ModInt(this.val - y); }
    ModInt opBinary(string op : "*")(int y) const { return ModInt(this.val * y); }
    ModInt opBinary(string op : "/")(int y) const { return ModInt(this.val * inv(y)); }
    ModInt opBinary(string op : "+")(long y) const { return ModInt(this.val + y); }
    ModInt opBinary(string op : "-")(long y) const { return ModInt(this.val - y); }
    ModInt opBinary(string op : "*")(long y) const { return ModInt(this.val * y); }
    ModInt opBinary(string op : "/")(long y) const { return ModInt(this.val * inv(y)); }
    ModInt opBinary(string op : "+")(ModInt y) const { return ModInt(this.val + y.val); }
    ModInt opBinary(string op : "-")(ModInt y) const { return ModInt(this.val - y.val); }
    ModInt opBinary(string op : "*")(ModInt y) const { return ModInt(this.val * y.val); }
    ModInt opBinary(string op : "/")(ModInt y) const { return ModInt(this.val * inv(y.val)); }
    ModInt opBinaryRight(string op : "+")(int y) const { return ModInt(this.val + y); }
    ModInt opBinaryRight(string op : "-")(int y) const { return ModInt(y - this.val); }
    ModInt opBinaryRight(string op : "*")(int y) const { return ModInt(this.val * y); }
    ModInt opBinaryRight(string op : "/")(int y) const { return ModInt(inv(this.val) * y); }
    ModInt opBinaryRight(string op : "+")(long y) const { return ModInt(this.val + y); }
    ModInt opBinaryRight(string op : "-")(long y) const { return ModInt(y - this.val); }
    ModInt opBinaryRight(string op : "*")(long y) const { return ModInt(this.val * y); }
    ModInt opBinaryRight(string op : "/")(long y) const { return ModInt(inv(this.val) * y); }
    void opAssign(int y) { this.val = y; }
    void opAssign(long y) { this.val = y; }
    void opOpAssign(string op : "+")(int y) { this.val = (this.val + mod * mod + y) % mod; }
    void opOpAssign(string op : "-")(int y) { this.val = (this.val + mod * mod - y) % mod; }
    void opOpAssign(string op : "*")(int y) { this.val = (this.val * y) % mod; }
    void opOpAssign(string op : "/")(int y) { this.val = (this.val * inv(y)) % mod; }
    void opOpAssign(string op : "+")(long y) { this.val = (this.val + mod * mod + y) % mod; }
    void opOpAssign(string op : "-")(long y) { this.val = (this.val + mod * mod - y) % mod; }
    void opOpAssign(string op : "*")(long y) { this.val = (this.val * y) % mod; }
    void opOpAssign(string op : "/")(long y) { this.val = (this.val * inv(y)) % mod; }
    void opOpAssign(string op : "+")(ModInt y) { this.val = (this.val + mod * mod + y.val) % mod; }
    void opOpAssign(string op : "-")(ModInt y) { this.val = (this.val + mod * mod - y.val) % mod; }
    void opOpAssign(string op : "*")(ModInt y) { this.val = (this.val * y.val) % mod; }
    void opOpAssign(string op : "/")(ModInt y) { this.val = (this.val * inv(y.val)) % mod; }
    ModInt opUnary(string op : "-")() const { return ModInt(mod - this.val); }
    string toString() const { return val.to!string; }
    static long extgcd(long a, long b, ref long x, ref long y) {
        if (b == 0) {
            x = 1;
            y = 0;
            return a;
        }
        long d = extgcd(b, a % b, y, x);
        y -= a / b * x;
        return d;
    }
    static long inv(long a) {
        long x, y;
        extgcd(a, mod, x, y);
        return (x % mod + mod) % mod;
    }
}
alias MInt = ModInt!(cast(long)(1e9+7));

void main() {
    int N, P; readf("%d %d\n", &N, &P);
    auto A = readarray!int;
    A.sort;
    bool[int] S;
    bool find(int a) {
        // a is already in S
        for (int k = 0; k <= 31; k++) {
            int x = a >> k;
            if (x in S) {
                // check
                auto fmt = "%0" ~ k.to!string ~ "b";
                string s = format(fmt, a & ((1<<k) - 1));
                bool c() {
                    for (int j = 0; j < s.length; j++) {
                        if (s[j] == '0') {
                            if (j == s.length - 1 || s[j + 1] != '0') return false;
                            j++;
                        }
                    }
                    return true;
                }
                if (c()) {
                    return true;
                }
            }
        }
        return false;
    }

    auto f = new MInt[P + 1];
    f[0] = 0;
    f[1] = 1;
    for (int n = 2; n <= P; n++) {
        f[n] = f[n - 2] + f[n - 1];
    }
    auto g = new MInt[P + 2];
    g[0] = 0;
    for (int n = 0; n <= P; n++) {
        g[n + 1] = g[n] + f[n];
    }
    //writeln(f);

    MInt ans = 0;
    for (int i = 0; i < N; i++) {
        int a = A[i];
        //writeln("a: ", a);
        if (find(a)) continue;
        int k = bsr(a);
        MInt d = 0;
        foreach (j; 0 .. (P - k + 1)) {
            d += f[j];
        }
        //ans += d;
        MInt nd = g[P - k + 1];
        ans += nd;
        assert(d == nd);
        //writeln("k: ", k);
        //writeln("d: ", d);
        S[a] = true;
    }
    writeln(ans);
}

import std.stdio;
import core.bitop;
import std.math;
import std.numeric;
import std.container;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

struct ModInt(long mod) {
    invariant() {
        assert(0 <= val && val < mod);
    }
    long val;
    this(long v) { this.val = (mod * mod + v) % mod; }
    ModInt opBinary(string op : "+")(int y) const { return ModInt(this.val + y); }
    ModInt opBinary(string op : "-")(int y) const { return ModInt(this.val - y); }
    ModInt opBinary(string op : "*")(int y) const { return ModInt(this.val * y); }
    ModInt opBinary(string op : "/")(int y) const { return ModInt(this.val * inv(y)); }
    ModInt opBinary(string op : "+")(long y) const { return ModInt(this.val + y); }
    ModInt opBinary(string op : "-")(long y) const { return ModInt(this.val - y); }
    ModInt opBinary(string op : "*")(long y) const { return ModInt(this.val * y); }
    ModInt opBinary(string op : "/")(long y) const { return ModInt(this.val * inv(y)); }
    ModInt opBinary(string op : "+")(ModInt y) const { return ModInt(this.val + y.val); }
    ModInt opBinary(string op : "-")(ModInt y) const { return ModInt(this.val - y.val); }
    ModInt opBinary(string op : "*")(ModInt y) const { return ModInt(this.val * y.val); }
    ModInt opBinary(string op : "/")(ModInt y) const { return ModInt(this.val * inv(y.val)); }
    ModInt opBinaryRight(string op : "+")(int y) const { return ModInt(this.val + y); }
    ModInt opBinaryRight(string op : "-")(int y) const { return ModInt(y - this.val); }
    ModInt opBinaryRight(string op : "*")(int y) const { return ModInt(this.val * y); }
    ModInt opBinaryRight(string op : "/")(int y) const { return ModInt(inv(this.val) * y); }
    ModInt opBinaryRight(string op : "+")(long y) const { return ModInt(this.val + y); }
    ModInt opBinaryRight(string op : "-")(long y) const { return ModInt(y - this.val); }
    ModInt opBinaryRight(string op : "*")(long y) const { return ModInt(this.val * y); }
    ModInt opBinaryRight(string op : "/")(long y) const { return ModInt(inv(this.val) * y); }
    void opAssign(int y) { this.val = y; }
    void opAssign(long y) { this.val = y; }
    void opOpAssign(string op : "+")(int y) { this.val = (this.val + mod * mod + y) % mod; }
    void opOpAssign(string op : "-")(int y) { this.val = (this.val + mod * mod - y) % mod; }
    void opOpAssign(string op : "*")(int y) { this.val = (this.val * y) % mod; }
    void opOpAssign(string op : "/")(int y) { this.val = (this.val * inv(y)) % mod; }
    void opOpAssign(string op : "+")(long y) { this.val = (this.val + mod * mod + y) % mod; }
    void opOpAssign(string op : "-")(long y) { this.val = (this.val + mod * mod - y) % mod; }
    void opOpAssign(string op : "*")(long y) { this.val = (this.val * y) % mod; }
    void opOpAssign(string op : "/")(long y) { this.val = (this.val * inv(y)) % mod; }
    void opOpAssign(string op : "+")(ModInt y) { this.val = (this.val + mod * mod + y.val) % mod; }
    void opOpAssign(string op : "-")(ModInt y) { this.val = (this.val + mod * mod - y.val) % mod; }
    void opOpAssign(string op : "*")(ModInt y) { this.val = (this.val * y.val) % mod; }
    void opOpAssign(string op : "/")(ModInt y) { this.val = (this.val * inv(y.val)) % mod; }
    ModInt opUnary(string op : "-")() const { return ModInt(mod - this.val); }
    string toString() const { return val.to!string; }
    static long extgcd(long a, long b, ref long x, ref long y) {
        if (b == 0) {
            x = 1;
            y = 0;
            return a;
        }
        long d = extgcd(b, a % b, y, x);
        y -= a / b * x;
        return d;
    }
    static long inv(long a) {
        long x, y;
        extgcd(a, mod, x, y);
        return (x % mod + mod) % mod;
    }
}
alias MInt = ModInt!(cast(long)(1e9+7));

void main() {
    int N, P; readf("%d %d\n", &N, &P);
    auto A = readarray!int;
    A.sort;
    bool[int] S;
    bool find(int a) {
        // a is already in S
        for (int k = 0; k <= 31; k++) {
            int x = a >> k;
            if (x in S) {
                // check
                auto fmt = "%0" ~ k.to!string ~ "b";
                string s = format(fmt, a & ((1<<k) - 1));
                bool c() {
                    for (int j = 0; j < s.length; j++) {
                        if (s[j] == '0') {
                            if (j == s.length - 1 || s[j + 1] != '0') return false;
                            j++;
                        }
                    }
                    return true;
                }
                if (c()) {
                    return true;
                }
            }
        }
        return false;
    }

    auto f = new MInt[P + 1];
    f[0] = 0;
    f[1] = 1;
    for (int n = 2; n <= P; n++) {
        f[n] = f[n - 2] + f[n - 1];
    }
    auto g = new MInt[P + 2];
    g[0] = 0;
    for (int n = 0; n <= P; n++) {
        g[n + 1] = g[n] + f[n];
    }
    //writeln(f);

    MInt ans = 0;
    for (int i = 0; i < N; i++) {
        int a = A[i];
        //writeln("a: ", a);
        if (find(a)) continue;
        int k = bsr(a);
        /*
        MInt d = 0;
        foreach (j; 0 .. (P - k + 1)) {
            d += f[j];
        }
        ans += d;
        */
        MInt nd = g[P - k + 1];
        ans += nd;
        //writeln("k: ", k);
        //writeln("d: ", d);
        S[a] = true;
    }
    writeln(ans);
}

import std.stdio;
import core.bitop;
import std.math;
import std.numeric;
import std.container;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

struct ModInt(long mod) {
    invariant() {
        assert(0 <= val && val < mod);
    }
    long val;
    this(long v) { this.val = v % mod; }
    ModInt opBinary(string op : "+")(int y) const { return ModInt(this.val + y); }
    ModInt opBinary(string op : "-")(int y) const { return ModInt(this.val - y); }
    ModInt opBinary(string op : "*")(int y) const { return ModInt(this.val * y); }
    ModInt opBinary(string op : "/")(int y) const { return ModInt(this.val * inv(y)); }
    ModInt opBinary(string op : "+")(long y) const { return ModInt(this.val + y); }
    ModInt opBinary(string op : "-")(long y) const { return ModInt(this.val - y); }
    ModInt opBinary(string op : "*")(long y) const { return ModInt(this.val * y); }
    ModInt opBinary(string op : "/")(long y) const { return ModInt(this.val * inv(y)); }
    ModInt opBinary(string op : "+")(ModInt y) const { return ModInt(this.val + y.val); }
    ModInt opBinary(string op : "-")(ModInt y) const { return ModInt(this.val - y.val); }
    ModInt opBinary(string op : "*")(ModInt y) const { return ModInt(this.val * y.val); }
    ModInt opBinary(string op : "/")(ModInt y) const { return ModInt(this.val * inv(y.val)); }
    ModInt opBinaryRight(string op : "+")(int y) const { return ModInt(this.val + y); }
    ModInt opBinaryRight(string op : "-")(int y) const { return ModInt(y - this.val); }
    ModInt opBinaryRight(string op : "*")(int y) const { return ModInt(this.val * y); }
    ModInt opBinaryRight(string op : "/")(int y) const { return ModInt(inv(this.val) * y); }
    ModInt opBinaryRight(string op : "+")(long y) const { return ModInt(this.val + y); }
    ModInt opBinaryRight(string op : "-")(long y) const { return ModInt(y - this.val); }
    ModInt opBinaryRight(string op : "*")(long y) const { return ModInt(this.val * y); }
    ModInt opBinaryRight(string op : "/")(long y) const { return ModInt(inv(this.val) * y); }
    void opAssign(int y) { this.val = y; }
    void opAssign(long y) { this.val = y; }
    void opOpAssign(string op : "+")(int y) { this.val = (this.val + mod * mod + y) % mod; }
    void opOpAssign(string op : "-")(int y) { this.val = (this.val + mod * mod - y) % mod; }
    void opOpAssign(string op : "*")(int y) { this.val = (this.val * y) % mod; }
    void opOpAssign(string op : "/")(int y) { this.val = (this.val * inv(y)) % mod; }
    void opOpAssign(string op : "+")(long y) { this.val = (this.val + mod * mod + y) % mod; }
    void opOpAssign(string op : "-")(long y) { this.val = (this.val + mod * mod - y) % mod; }
    void opOpAssign(string op : "*")(long y) { this.val = (this.val * y) % mod; }
    void opOpAssign(string op : "/")(long y) { this.val = (this.val * inv(y)) % mod; }
    void opOpAssign(string op : "+")(ModInt y) { this.val = (this.val + mod * mod + y.val) % mod; }
    void opOpAssign(string op : "-")(ModInt y) { this.val = (this.val + mod * mod - y.val) % mod; }
    void opOpAssign(string op : "*")(ModInt y) { this.val = (this.val * y.val) % mod; }
    void opOpAssign(string op : "/")(ModInt y) { this.val = (this.val * inv(y.val)) % mod; }
    ModInt opUnary(string op : "-")() const { return ModInt(mod - this.val); }
    string toString() const { return val.to!string; }
    static long extgcd(long a, long b, ref long x, ref long y) {
        if (b == 0) {
            x = 1;
            y = 0;
            return a;
        }
        long d = extgcd(b, a % b, y, x);
        y -= a / b * x;
        return d;
    }
    static long inv(long a) {
        long x, y;
        extgcd(a, mod, x, y);
        return (x % mod + mod) % mod;
    }
}
alias MInt = ModInt!(cast(long)(1e9+7));

void main() {
    int N, P; readf("%d %d\n", &N, &P);
    auto A = readarray!int;
    A.sort;
    bool[int] S;
    bool find(int a) {
        // a is already in S
        for (int k = 0; k <= 30; k++) {
            int x = a >> k;
            if (x in S) {
                // check
                auto fmt = "%0" ~ k.to!string ~ "b";
                string s = format(fmt, a & ((1<<k) - 1));
                bool c() {
                    for (int j = 0; j < s.length; j++) {
                        if (s[j] == '0') {
                            if (j == s.length - 1 || s[j + 1] != '0') return false;
                            j++;
                        }
                    }
                    return true;
                }
                if (c()) {
                    return true;
                }
            }
        }
        return false;
    }

    auto f = new MInt[P + 1];
    f[0] = 0;
    f[1] = 1;
    for (int n = 2; n <= P; n++) {
        f[n] = f[n - 2] + f[n - 1];
    }
    auto g = new MInt[P + 2];
    g[0] = 0;
    for (int n = 0; n <= P; n++) {
        g[n + 1] = g[n] + f[n];
    }
    //writeln(f);

    MInt ans = 0;
    for (int i = 0; i < N; i++) {
        int a = A[i];
        //writeln("a: ", a);
        if (find(a)) continue;
        int k = bsr(a);
        /*
        MInt d = 0;
        foreach (j; 0 .. (P - k + 1)) {
            d += f[j];
        }
        */
        auto d = g[P - k + 1];
        ans += d;
        //writeln("k: ", k);
        //writeln("d: ", d);
        S[a] = true;
    }
    writeln(ans);
}

import std.stdio;
import core.bitop;
import std.math;
import std.numeric;
import std.container;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

struct ModInt(long mod) {
    invariant() {
        assert(0 <= val && val < mod);
    }
    long val;
    this(long v) { this.val = (mod * mod + v) % mod; }
    ModInt opBinary(string op : "+")(int y) const { return ModInt(this.val + y); }
    ModInt opBinary(string op : "-")(int y) const { return ModInt(this.val - y); }
    ModInt opBinary(string op : "*")(int y) const { return ModInt(this.val * y); }
    ModInt opBinary(string op : "/")(int y) const { return ModInt(this.val * inv(y)); }
    ModInt opBinary(string op : "+")(long y) const { return ModInt(this.val + y); }
    ModInt opBinary(string op : "-")(long y) const { return ModInt(this.val - y); }
    ModInt opBinary(string op : "*")(long y) const { return ModInt(this.val * y); }
    ModInt opBinary(string op : "/")(long y) const { return ModInt(this.val * inv(y)); }
    ModInt opBinary(string op : "+")(ModInt y) const { return ModInt(this.val + y.val); }
    ModInt opBinary(string op : "-")(ModInt y) const { return ModInt(this.val - y.val); }
    ModInt opBinary(string op : "*")(ModInt y) const { return ModInt(this.val * y.val); }
    ModInt opBinary(string op : "/")(ModInt y) const { return ModInt(this.val * inv(y.val)); }
    ModInt opBinaryRight(string op : "+")(int y) const { return ModInt(this.val + y); }
    ModInt opBinaryRight(string op : "-")(int y) const { return ModInt(y - this.val); }
    ModInt opBinaryRight(string op : "*")(int y) const { return ModInt(this.val * y); }
    ModInt opBinaryRight(string op : "/")(int y) const { return ModInt(inv(this.val) * y); }
    ModInt opBinaryRight(string op : "+")(long y) const { return ModInt(this.val + y); }
    ModInt opBinaryRight(string op : "-")(long y) const { return ModInt(y - this.val); }
    ModInt opBinaryRight(string op : "*")(long y) const { return ModInt(this.val * y); }
    ModInt opBinaryRight(string op : "/")(long y) const { return ModInt(inv(this.val) * y); }
    void opAssign(int y) { this.val = y; }
    void opAssign(long y) { this.val = y; }
    void opOpAssign(string op : "+")(int y) { this.val = (this.val + mod * mod + y) % mod; }
    void opOpAssign(string op : "-")(int y) { this.val = (this.val + mod * mod - y) % mod; }
    void opOpAssign(string op : "*")(int y) { this.val = (this.val * y) % mod; }
    void opOpAssign(string op : "/")(int y) { this.val = (this.val * inv(y)) % mod; }
    void opOpAssign(string op : "+")(long y) { this.val = (this.val + mod * mod + y) % mod; }
    void opOpAssign(string op : "-")(long y) { this.val = (this.val + mod * mod - y) % mod; }
    void opOpAssign(string op : "*")(long y) { this.val = (this.val * y) % mod; }
    void opOpAssign(string op : "/")(long y) { this.val = (this.val * inv(y)) % mod; }
    void opOpAssign(string op : "+")(ModInt y) { this.val = (this.val + mod * mod + y.val) % mod; }
    void opOpAssign(string op : "-")(ModInt y) { this.val = (this.val + mod * mod - y.val) % mod; }
    void opOpAssign(string op : "*")(ModInt y) { this.val = (this.val * y.val) % mod; }
    void opOpAssign(string op : "/")(ModInt y) { this.val = (this.val * inv(y.val)) % mod; }
    ModInt opUnary(string op : "-")() const { return ModInt(mod - this.val); }
    string toString() const { return val.to!string; }
    static long extgcd(long a, long b, ref long x, ref long y) {
        if (b == 0) {
            x = 1;
            y = 0;
            return a;
        }
        long d = extgcd(b, a % b, y, x);
        y -= a / b * x;
        return d;
    }
    static long inv(long a) {
        long x, y;
        extgcd(a, mod, x, y);
        return (x % mod + mod) % mod;
    }
}
alias MInt = ModInt!(cast(long)(1e9+7));

void main() {
    int N, P; readf("%d %d\n", &N, &P);
    auto A = readarray!int;
    A.sort;
    bool[int] S;
    bool find(int a) {
        // a is already in S
        for (int k = 0; k <= 30; k++) {
            int x = a >> k;
            if (x in S) {
                // check
                auto fmt = "%0" ~ k.to!string ~ "b";
                string s = format(fmt, a & ((1<<k) - 1));
                bool c() {
                    for (int j = 0; j < s.length; j++) {
                        if (s[j] == '0') {
                            if (j == s.length - 1 || s[j + 1] != '0') return false;
                            j++;
                        }
                    }
                    return true;
                }
                if (c()) {
                    return true;
                }
            }
        }
        return false;
    }

    auto f = new MInt[P + 1];
    f[0] = 0;
    f[1] = 1;
    for (int n = 2; n <= P; n++) {
        f[n] = f[n - 2] + f[n - 1];
    }
    auto g = new MInt[P + 2];
    g[0] = 0;
    for (int n = 0; n <= P; n++) {
        g[n + 1] = g[n] + f[n];
    }
    //writeln(f);

    MInt ans = 0;
    for (int i = 0; i < N; i++) {
        int a = A[i];
        //writeln("a: ", a);
        if (find(a)) continue;
        int k = bsr(a);
        /*
        MInt d = 0;
        foreach (j; 0 .. (P - k + 1)) {
            d += f[j];
        }
        */
        auto d = g[P - k + 1];
        ans += d;
        //writeln("k: ", k);
        //writeln("d: ", d);
        S[a] = true;
    }
    writeln(ans);
}

import std.stdio;
import core.bitop;
import std.math;
import std.numeric;
import std.container;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

struct ModInt(long mod) {
    invariant() {
        assert(0 <= val && val < mod);
    }
    long val;
    this(long v) { this.val = (mod * mod + v) % mod; }
    ModInt opBinary(string op : "+")(int y) const { return ModInt(this.val + y); }
    ModInt opBinary(string op : "-")(int y) const { return ModInt(this.val - y); }
    ModInt opBinary(string op : "*")(int y) const { return ModInt(this.val * y); }
    ModInt opBinary(string op : "/")(int y) const { return ModInt(this.val * inv(y)); }
    ModInt opBinary(string op : "+")(long y) const { return ModInt(this.val + y); }
    ModInt opBinary(string op : "-")(long y) const { return ModInt(this.val - y); }
    ModInt opBinary(string op : "*")(long y) const { return ModInt(this.val * y); }
    ModInt opBinary(string op : "/")(long y) const { return ModInt(this.val * inv(y)); }
    ModInt opBinary(string op : "+")(ModInt y) const { return ModInt(this.val + y.val); }
    ModInt opBinary(string op : "-")(ModInt y) const { return ModInt(this.val - y.val); }
    ModInt opBinary(string op : "*")(ModInt y) const { return ModInt(this.val * y.val); }
    ModInt opBinary(string op : "/")(ModInt y) const { return ModInt(this.val * inv(y.val)); }
    ModInt opBinaryRight(string op : "+")(int y) const { return ModInt(this.val + y); }
    ModInt opBinaryRight(string op : "-")(int y) const { return ModInt(y - this.val); }
    ModInt opBinaryRight(string op : "*")(int y) const { return ModInt(this.val * y); }
    ModInt opBinaryRight(string op : "/")(int y) const { return ModInt(inv(this.val) * y); }
    ModInt opBinaryRight(string op : "+")(long y) const { return ModInt(this.val + y); }
    ModInt opBinaryRight(string op : "-")(long y) const { return ModInt(y - this.val); }
    ModInt opBinaryRight(string op : "*")(long y) const { return ModInt(this.val * y); }
    ModInt opBinaryRight(string op : "/")(long y) const { return ModInt(inv(this.val) * y); }
    void opAssign(int y) { this.val = y; }
    void opAssign(long y) { this.val = y; }
    void opOpAssign(string op : "+")(int y) { this.val = (this.val + mod * mod + y) % mod; }
    void opOpAssign(string op : "-")(int y) { this.val = (this.val + mod * mod - y) % mod; }
    void opOpAssign(string op : "*")(int y) { this.val = (this.val * y) % mod; }
    void opOpAssign(string op : "/")(int y) { this.val = (this.val * inv(y)) % mod; }
    void opOpAssign(string op : "+")(long y) { this.val = (this.val + mod * mod + y) % mod; }
    void opOpAssign(string op : "-")(long y) { this.val = (this.val + mod * mod - y) % mod; }
    void opOpAssign(string op : "*")(long y) { this.val = (this.val * y) % mod; }
    void opOpAssign(string op : "/")(long y) { this.val = (this.val * inv(y)) % mod; }
    void opOpAssign(string op : "+")(ModInt y) { this.val = (this.val + mod * mod + y.val) % mod; }
    void opOpAssign(string op : "-")(ModInt y) { this.val = (this.val + mod * mod - y.val) % mod; }
    void opOpAssign(string op : "*")(ModInt y) { this.val = (this.val * y.val) % mod; }
    void opOpAssign(string op : "/")(ModInt y) { this.val = (this.val * inv(y.val)) % mod; }
    ModInt opUnary(string op : "-")() const { return ModInt(mod - this.val); }
    string toString() const { return val.to!string; }
    static long extgcd(long a, long b, ref long x, ref long y) {
        if (b == 0) {
            x = 1;
            y = 0;
            return a;
        }
        long d = extgcd(b, a % b, y, x);
        y -= a / b * x;
        return d;
    }
    static long inv(long a) {
        long x, y;
        extgcd(a, mod, x, y);
        return (x % mod + mod) % mod;
    }
}
alias MInt = ModInt!(cast(long)(1e9+7));

void main() {
    int N, P; readf("%d %d\n", &N, &P);
    auto A = readarray!int;
    A.sort;
    bool[int] S;
    bool find(int a) {
        // a is already in S
        for (int k = 0; k <= 30; k++) {
            int x = a >> k;
            if (x in S) {
                // check
                auto fmt = "%0" ~ k.to!string ~ "b";
                string s = format(fmt, a & ((1<<k) - 1));
                bool c() {
                    for (int j = 0; j < s.length; j++) {
                        if (s[j] == '0') {
                            if (j == s.length - 1 || s[j + 1] != '0') return false;
                            j++;
                        }
                    }
                    return true;
                }
                if (c()) {
                    return true;
                }
            }
        }
        return false;
    }

    auto f = new MInt[P + 1];
    f[0] = 0;
    f[1] = 1;
    for (int n = 2; n <= P; n++) {
        f[n] = f[n - 2] + f[n - 1];
    }
    auto g = new MInt[P + 1];
    for (int n = 0; n <= P; n++) {
        g[n + 1] = g[n] + f[n];
    }
    //writeln(f);

    MInt ans = 0;
    for (int i = 0; i < N; i++) {
        int a = A[i];
        //writeln("a: ", a);
        if (find(a)) continue;
        int k = bsr(a);
        /*
        MInt d = 0;
        foreach (j; 0 .. (P - k + 1)) {
            d += f[j];
        }
        */
        auto d = g[P - k + 1];
        ans += d;
        //writeln("k: ", k);
        //writeln("d: ", d);
        S[a] = true;
    }
    writeln(ans);
}

import std.stdio;
import core.bitop;
import std.math;
import std.numeric;
import std.container;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

struct ModInt(long mod) {
    invariant() {
        assert(0 <= val && val < mod);
    }
    long val;
    this(long v) { this.val = (mod * mod + v) % mod; }
    ModInt opBinary(string op : "+")(int y) const { return ModInt(this.val + y); }
    ModInt opBinary(string op : "-")(int y) const { return ModInt(this.val - y); }
    ModInt opBinary(string op : "*")(int y) const { return ModInt(this.val * y); }
    ModInt opBinary(string op : "/")(int y) const { return ModInt(this.val * inv(y)); }
    ModInt opBinary(string op : "+")(long y) const { return ModInt(this.val + y); }
    ModInt opBinary(string op : "-")(long y) const { return ModInt(this.val - y); }
    ModInt opBinary(string op : "*")(long y) const { return ModInt(this.val * y); }
    ModInt opBinary(string op : "/")(long y) const { return ModInt(this.val * inv(y)); }
    ModInt opBinary(string op : "+")(ModInt y) const { return ModInt(this.val + y.val); }
    ModInt opBinary(string op : "-")(ModInt y) const { return ModInt(this.val - y.val); }
    ModInt opBinary(string op : "*")(ModInt y) const { return ModInt(this.val * y.val); }
    ModInt opBinary(string op : "/")(ModInt y) const { return ModInt(this.val * inv(y.val)); }
    ModInt opBinaryRight(string op : "+")(int y) const { return ModInt(this.val + y); }
    ModInt opBinaryRight(string op : "-")(int y) const { return ModInt(y - this.val); }
    ModInt opBinaryRight(string op : "*")(int y) const { return ModInt(this.val * y); }
    ModInt opBinaryRight(string op : "/")(int y) const { return ModInt(inv(this.val) * y); }
    ModInt opBinaryRight(string op : "+")(long y) const { return ModInt(this.val + y); }
    ModInt opBinaryRight(string op : "-")(long y) const { return ModInt(y - this.val); }
    ModInt opBinaryRight(string op : "*")(long y) const { return ModInt(this.val * y); }
    ModInt opBinaryRight(string op : "/")(long y) const { return ModInt(inv(this.val) * y); }
    void opAssign(int y) { this.val = y; }
    void opAssign(long y) { this.val = y; }
    void opOpAssign(string op : "+")(int y) { this.val = (this.val + mod * mod + y) % mod; }
    void opOpAssign(string op : "-")(int y) { this.val = (this.val + mod * mod - y) % mod; }
    void opOpAssign(string op : "*")(int y) { this.val = (this.val * y) % mod; }
    void opOpAssign(string op : "/")(int y) { this.val = (this.val * inv(y)) % mod; }
    void opOpAssign(string op : "+")(long y) { this.val = (this.val + mod * mod + y) % mod; }
    void opOpAssign(string op : "-")(long y) { this.val = (this.val + mod * mod - y) % mod; }
    void opOpAssign(string op : "*")(long y) { this.val = (this.val * y) % mod; }
    void opOpAssign(string op : "/")(long y) { this.val = (this.val * inv(y)) % mod; }
    void opOpAssign(string op : "+")(ModInt y) { this.val = (this.val + mod * mod + y.val) % mod; }
    void opOpAssign(string op : "-")(ModInt y) { this.val = (this.val + mod * mod - y.val) % mod; }
    void opOpAssign(string op : "*")(ModInt y) { this.val = (this.val * y.val) % mod; }
    void opOpAssign(string op : "/")(ModInt y) { this.val = (this.val * inv(y.val)) % mod; }
    ModInt opUnary(string op : "-")() const { return ModInt(mod - this.val); }
    string toString() const { return val.to!string; }
    static long extgcd(long a, long b, ref long x, ref long y) {
        if (b == 0) {
            x = 1;
            y = 0;
            return a;
        }
        long d = extgcd(b, a % b, y, x);
        y -= a / b * x;
        return d;
    }
    static long inv(long a) {
        long x, y;
        extgcd(a, mod, x, y);
        return (x % mod + mod) % mod;
    }
}
alias MInt = ModInt!(cast(long)(1e9+7));

void main() {
    int N, P; readf("%d %d\n", &N, &P);
    auto A = readarray!int;
    A.sort;
    bool[int] S;
    bool find(int a) {
        // a is already in S
        for (int k = 0; k <= 31; k++) {
            int x = a >> k;
            if (x in S) {
                // check
                auto fmt = "%0" ~ k.to!string ~ "b";
                string s = format(fmt, a & ((1<<k) - 1));
                bool c() {
                    for (int j = 0; j < s.length; j++) {
                        if (s[j] == '0') {
                            if (j == s.length - 1 || s[j + 1] != '0') return false;
                            j++;
                        }
                    }
                    return true;
                }
                if (c()) {
                    return true;
                }
            }
        }
        return false;
    }

    auto f = new MInt[P + 1];
    f[0] = 0;
    f[1] = 1;
    for (int n = 2; n <= P; n++) {
        f[n] = f[n - 2] + f[n - 1];
    }
    auto g = new MInt[P + 2];
    for (int n = 0; n <= P; n++) {
        g[n + 1] = g[n] + f[n];
    }
    //writeln(f);

    MInt ans = 0;
    for (int i = 0; i < N; i++) {
        int a = A[i];
        //writeln("a: ", a);
        if (find(a)) continue;
        int k = bsr(a);
        /*
        MInt d = 0;
        foreach (j; 0 .. (P - k + 1)) {
            d += f[j];
        }
        */
        auto d = g[P - k + 1];
        ans += d;
        //writeln("k: ", k);
        //writeln("d: ", d);
        S[a] = true;
    }
    writeln(ans);
}


Given a tree with $$$n$$$ nodes numbered from $$$1$$$ to $$$n$$$. Each node $$$i$$$ has an associated value $$$V_i$$$.If the simple path from $$$u_1$$$ to $$$u_m$$$ consists of $$$m$$$ nodes namely $$$u_1 \rightarrow u_2 \rightarrow u_3 \rightarrow \dots u_{m-1} \rightarrow u_{m}$$$, then its alternating function $$$A(u_{1},u_{m})$$$ is defined as $$$A(u_{1},u_{m}) = \sum\limits_{i=1}^{m} (-1)^{i+1} \cdot V_{u_{i}}$$$. A path can also have $$$0$$$ edges, i.e. $$$u_{1}=u_{m}$$$.Compute the sum of alternating functions of all unique simple paths. Note that the paths are directed: two paths are considered different if the starting vertices differ or the ending vertices differ. The answer may be large so compute it modulo $$$10^{9}+7$$$.

The first line contains an integer $$$n$$$ $$$(2 \leq n \leq 2\cdot10^{5} )$$$ — the number of vertices in the tree. The second line contains $$$n$$$ space-separated integers $$$V_1, V_2, \ldots, V_n$$$ ($$$-10^9\leq V_i \leq 10^9$$$) — values of the nodes. The next $$$n-1$$$ lines each contain two space-separated integers $$$u$$$ and $$$v$$$ $$$(1\leq u, v\leq n, u \neq v)$$$ denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the given graph is a tree.

Print the total sum of alternating functions of all unique simple paths modulo $$$10^{9}+7$$$.

import std.algorithm, std.container, std.conv, std.math, std.range, std.typecons, std.stdio, std.string;

auto rdsp(){return readln.splitter;}
void pick(R,T)(ref R r,ref T t){t=r.front.to!T;r.popFront;}
void readV(T...)(ref T t){auto r=rdsp;foreach(ref v;t)pick(r,v);}
void readA(T)(size_t n,ref T[]t){t=new T[](n);auto r=rdsp;foreach(ref v;t)pick(r,v);}

const mod = 10^^9+7;
alias mint = FactorRing!mod;

void main()
{
  int n; readV(n);
  int[] w; readA(n, w);

  auto g = Graph!int(n);
  foreach (_; 0..n-1) {
    int u, v; readV(u, v);
    g.addEdgeB(--u, --v);
  }
  auto t = makeTree(g).rootify(0);

  auto ei = new int[int][](n);
  foreach (u; 0..n)
    foreach (int i, v; g[u]) ei[u][v] = i;

  auto vc = new VC[][](n), vct = new VC[](n);
  foreach (u; 0..n) vc[u] = new VC[](g[u].length);

  auto q = DList!int([0]), rt = new int[](0);
  while (!q.empty) {
    auto u = q.front; q.removeFront();
    rt ~= u;
    foreach (v; t[u])
      if (v != t.parent[u])
        q.insertBack(v);
  }
  rt = rt[1..$];

  foreach_reverse (u; rt) {
    auto p = t.parent[u];
    auto vci = VC(1, 0);
    foreach (i, v; g[u])
      if (v != p)
        vci = vci + vc[u][i].inv;
    vc[p][ei[p][u]] = vci;
  }

  foreach (u; 0..n)
    foreach (vci; vc[u])
      vct[u] = vct[u] + vci;

  foreach (u; rt) {
    auto p = t.parent[u];
    vc[u][ei[u][p]] = VC(1, 0) + (vct[p] - vc[p][ei[p][u]]).inv;
    vct[u] = vct[u] + vc[u][ei[u][p]];
  }

  auto ans = mint(0);
  foreach (u; 0..n) {
    auto vcti = vct[u];
    auto eo = mint(1);
    eo += vcti.o + vcti.e;
    eo += vcti.o - vcti.e;
    foreach (i, v; g[u]) {
      auto vci = vc[u][i], rvci = vcti - vci;
      eo += (mint(vci.o) - vci.e) * (rvci.o + rvci.e);
    }
    ans += eo * w[u];
  }

  writeln(ans);
}

struct VC
{
  int e, o;
  auto inv() { return VC(o, e); }
  auto opBinary(string op: "+")(VC a) { return VC(e+a.e, o+a.o); }
  auto opBinary(string op: "-")(VC a) { return VC(e-a.e, o-a.o); }
}

struct Graph(N = int)
{
  alias Node = N;
  Node n;
  Node[][] g;
  alias g this;
  this(Node n) { this.n = n; g = new Node[][](n); }
  void addEdge(Node u, Node v) { g[u] ~= v; }
  void addEdgeB(Node u, Node v) { g[u] ~= v; g[v] ~= u; }
}

struct Tree(Graph)
{
  import std.algorithm, std.container;
  alias Node = Graph.Node;
  Graph g;
  alias g this;
  Node root;
  Node[] parent;
  int[] size, depth;

  this(ref Graph g) { this.g = g; this.n = g.n; }

  ref auto rootify(Node r)
  {
    this.root = r;

    parent = new Node[](g.n);
    depth = new int[](g.n);
    depth[] = -1;

    struct UP { Node u, p; }
    auto st1 = SList!UP(UP(r, r));
    auto st2 = SList!UP();
    while (!st1.empty) {
      auto up = st1.front, u = up.u, p = up.p; st1.removeFront();

      parent[u] = p;
      depth[u] = depth[p] + 1;

      foreach (v; g[u])
        if (v != p) {
          st1.insertFront(UP(v, u));
          st2.insertFront(UP(v, u));
        }
    }

    size = new int[](g.n);
    size[] = 1;

    while (!st2.empty) {
      auto up = st2.front, u = up.u, p = up.p; st2.removeFront();
      size[p] += size[u];
    }

    return this;
  }

  auto children(Node u) { return g[u].filter!(v => v != parent[u]); }
}
ref auto makeTree(Graph)(ref Graph g) { return Tree!Graph(g); }

struct FactorRing(int m, bool pos = false)
{
  version(BigEndian) union { long vl; struct { int vi2; int vi; } } else union { long vl; int vi; }
  alias FR = FactorRing!(m, pos);
  @property static init() { return FR(0); }
  @property int value() { return vi; }
  @property void value(int v) { vi = mod(v); }
  alias value this;

  this(int v) { vi = v; }
  this(int v, bool runMod) { vi = runMod ? mod(v) : v; }
  this(long v) { vi = mod(v); }

  ref auto opAssign(int v) { vi = v; return this; }

  pure auto mod(int v) const { static if (pos) return v%m; else return (v%m+m)%m; }
  pure auto mod(long v) const { static if (pos) return cast(int)(v%m); else return cast(int)((v%m+m)%m); }

  static if (!pos) pure ref auto opUnary(string op: "-")() { return FR(mod(-vi)); }

  static if (m < int.max / 2) {
    pure ref auto opBinary(string op)(int r) if (op == "+" || op == "-") { return FR(mod(mixin("vi"~op~"r"))); }
    ref auto opOpAssign(string op)(int r) if (op == "+" || op == "-") { vi = mod(mixin("vi"~op~"r")); return this; }
  } else {
    pure ref auto opBinary(string op)(int r) if (op == "+" || op == "-") { return FR(mod(mixin("vl"~op~"r"))); }
    ref auto opOpAssign(string op)(int r) if (op == "+" || op == "-") { vi = mod(mixin("vl"~op~"r")); return this; }
  }
  pure ref auto opBinary(string op: "*")(int r) { return FR(mod(vl*r)); }
  ref auto opOpAssign(string op: "*")(int r) { vi = mod(vl*r); return this; }

  pure ref auto opBinary(string op)(ref FR r) if (op == "+" || op == "-" || op == "*") { return opBinary!op(r.vi); }
  ref auto opOpAssign(string op)(ref FR r) if (op == "+" || op == "-" || op == "*") { return opOpAssign!op(r.vi); }
}

import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.bitmanip, std.complex, std.container, std.math, std.mathspecial, std.numeric, std.regex, std.typecons;
import core.bitop;

class EOFException : Throwable { this() { super("EOF"); } }
string[] tokens;
string readToken() { for (; tokens.empty; ) { if (stdin.eof) { throw new EOFException; } tokens = readln.split; } auto token = tokens.front; tokens.popFront; return token; }
int readInt() { return readToken.to!int; }
long readLong() { return readToken.to!long; }
real readReal() { return readToken.to!real; }

bool chmin(T)(ref T t, in T f) { if (t > f) { t = f; return true; } else { return false; } }
bool chmax(T)(ref T t, in T f) { if (t < f) { t = f; return true; } else { return false; } }

int binarySearch(alias pred, T)(in T[] as) { int lo = -1, hi = cast(int)(as.length); for (; lo + 1 < hi; ) { const mid = (lo + hi) >> 1; (unaryFun!pred(as[mid]) ? hi : lo) = mid; } return hi; }
int lowerBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a >= val)); }
int upperBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a > val)); }

struct ModInt(int M_) {
  alias M = M_;
  int x;
  this(ModInt a) { x = a.x; }
  this(long a) { x = cast(int)(a % M); if (x < 0) x += M; }
  ref ModInt opAssign(long a) { return (this = ModInt(a)); }
  ref ModInt opOpAssign(string op)(ModInt a) {
    static if (op == "+") { x += a.x; if (x >= M) x -= M; }
    else static if (op == "-") { x -= a.x; if (x < 0) x += M; }
    else static if (op == "*") { x = cast(int)((cast(long)(x) * a.x) % M); }
    else static if (op == "/") { this *= a.inv(); }
    else static assert(false);
    return this;
  }
  ref ModInt opOpAssign(string op)(long a) {
    static if (op == "^^") {
      ModInt t2 = this, te = ModInt(1);
      for (long e = a; e; e >>= 1) {
        if (e & 1) te *= t2;
        t2 *= t2;
      }
      x = cast(int)(te.x);
      return this;
    } else return mixin("this " ~ op ~ "= ModInt(a)");
  }
  ModInt inv() const {
    int a = x, b = M, y = 1, z = 0, t;
    for (; ; ) {
      t = a / b; a -= t * b;
      if (a == 0) {
        assert(b == 1 || b == -1);
        return ModInt(b * z);
      }
      y -= t * z;
      t = b / a; b -= t * a;
      if (b == 0) {
        assert(a == 1 || a == -1);
        return ModInt(a * y);
      }
      z -= t * y;
    }
  }
  ModInt opUnary(string op)() const if (op == "-") { return ModInt(-x); }
  ModInt opBinary(string op, T)(T a) const { return mixin("ModInt(this) " ~ op ~ "= a"); }
  ModInt opBinaryRight(string op)(long a) const { return mixin("ModInt(a) " ~ op ~ "= this"); }
  string toString() const { return x.to!string; }
}

enum MO = 10^^9 + 7;
alias Mint = ModInt!MO;

int N;
Mint[] A;
int[] U, V;

int[][] G;
int[] par;
Mint[][] dp, DP;

void dfs(int u, int p) {
  par[u] = p;
  foreach (v; G[u]) {
    if (v != p) {
      dfs(v, u);
    }
  }
  auto sums = new Mint[2];
  foreach (v; G[u]) {
    if (v != p) {
      // add dp[v]
      sums[] += dp[v][];
    }
  }
  // calc dp[u]
  dp[u][0] = sums[1];
  dp[u][1] = 1 + sums[0];
}

void DFS(int u, int p) {
  auto sums = new Mint[2];
  foreach (v; G[u]) {
    if (v != p) {
      // add dp[v]
      sums[] += dp[v][];
    }
  }
  if (p != -1) {
    // add DP[u]
    sums[] += DP[u][];
  }
  foreach (v; G[u]) {
    if (v != p) {
      // calc DP[v], removing dp[v]
      sums[] -= dp[v][];
      DP[v][0] = sums[1];
      DP[v][1] = 1 + sums[0];
      sums[] += dp[v][];
    }
  }
  foreach (v; G[u]) {
    if (v != p) {
      DFS(v, u);
    }
  }
}

void main() {
  try {
    for (; ; ) {
      N = readInt();
      A = new Mint[N];
      foreach (u; 0 .. N) {
        A[u] = Mint(readLong());
      }
      U = new int[N - 1];
      V = new int[N - 1];
      foreach (i; 0 .. N - 1) {
        U[i] = readInt() - 1;
        V[i] = readInt() - 1;
      }

      G = new int[][N];
      foreach (i; 0 .. N - 1) {
        G[U[i]] ~= V[i];
        G[V[i]] ~= U[i];
      }
      par = new int[N];
      dp = new Mint[][](N, 2);
      DP = new Mint[][](N, 2);
      const rt = 0;
      dfs(rt, -1);
      DFS(rt, -1);
      debug {
        writeln("rt = ", rt);
        writeln("dp = ", dp);
        writeln("DP = ", DP);
      }

      Mint ans;
      foreach (u; 0 .. N) {
        auto sums = new Mint[2];
        Mint[][] seq;
        foreach (v; G[u]) {
          if (v != par[u]) {
            // add dp[v]
            sums[] += dp[v][];
            seq ~= dp[v];
          }
        }
        if (u != rt) {
          // add DP[u]
          sums[] += DP[u][];
          seq ~= DP[u];
        }
        // rooted at u
        Mint sum;
        sum += 1 * 1;
        sum += 1 * sums[0];
        sum += 1 * sums[1];
        foreach (j; 0 .. seq.length) {
          sum += seq[j][0] * 1;
          sum -= seq[j][1] * 1;
          sum += seq[j][0] * (sums[0] - seq[j][0]);
          sum += seq[j][0] * (sums[1] - seq[j][1]);
          sum -= seq[j][1] * (sums[0] - seq[j][0]);
          sum -= seq[j][1] * (sums[1] - seq[j][1]);
        }
        debug {
          writeln(u, ": ", sum);
        }
        ans += A[u] * sum;
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


Recently Vova found $$$n$$$ candy wrappers. He remembers that he bought $$$x$$$ candies during the first day, $$$2x$$$ candies during the second day, $$$4x$$$ candies during the third day, $$$\dots$$$, $$$2^{k-1} x$$$ candies during the $$$k$$$-th day. But there is an issue: Vova remembers neither $$$x$$$ nor $$$k$$$ but he is sure that $$$x$$$ and $$$k$$$ are positive integers and $$$k > 1$$$.Vova will be satisfied if you tell him any positive integer $$$x$$$ so there is an integer $$$k>1$$$ that $$$x + 2x + 4x + \dots + 2^{k-1} x = n$$$. It is guaranteed that at least one solution exists. Note that $$$k > 1$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 10^9$$$) — the number of candy wrappers Vova found. It is guaranteed that there is some positive integer $$$x$$$ and integer $$$k>1$$$ that $$$x + 2x + 4x + \dots + 2^{k-1} x = n$$$.

Print one integer — any positive integer value of $$$x$$$ so there is an integer $$$k>1$$$ that $$$x + 2x + 4x + \dots + 2^{k-1} x = n$$$.

NoteIn the first test case of the example, one of the possible answers is $$$x=1, k=2$$$. Then $$$1 \cdot 1 + 2 \cdot 1$$$ equals $$$n=3$$$.In the second test case of the example, one of the possible answers is $$$x=2, k=2$$$. Then $$$1 \cdot 2 + 2 \cdot 2$$$ equals $$$n=6$$$.In the third test case of the example, one of the possible answers is $$$x=1, k=3$$$. Then $$$1 \cdot 1 + 2 \cdot 1 + 4 \cdot 1$$$ equals $$$n=7$$$.In the fourth test case of the example, one of the possible answers is $$$x=7, k=2$$$. Then $$$1 \cdot 7 + 2 \cdot 7$$$ equals $$$n=21$$$.In the fifth test case of the example, one of the possible answers is $$$x=4, k=3$$$. Then $$$1 \cdot 4 + 2 \cdot 4 + 4 \cdot 4$$$ equals $$$n=28$$$.

import std.stdio, std.algorithm, std.conv, std.array, std.string, std.math, std.typecons, std.numeric;

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_; 0..T) {
        auto N = readln.chomp.to!long;
        long x = 1;
        foreach (k; 1..34) {
            x += 1L<<k;
            if (N%x == 0) {
                writeln(N/x);
                break;
            }
        }
    }
}

import std.stdio;

void main ()
{
	readln;
	int n;
	while (readf !(" %s") (n) > 0)
	{
		for (int w = 3; ; w += w + 1)
		{
			if (n % w == 0)
			{
				writeln (n / w);
				break;
			}
		}
	}
}

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
static string[] s_rd;
T _RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }

//long mod = 10^^9 + 7;
long mod = 998_244_353;
//long mod = 1_000_003;
void moda(T)(ref T x, T y) { x = (x + y) % mod; }
void mods(T)(ref T x, T y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(T)(ref T x, T y) { x = (x * y) % mod; }
void modpow(T)(ref T x, T y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(T)(ref T x, T y) { x.modm(y.modpow(mod - 2)); }

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD;
		long a = 3;
		while (true)
		{
			if (n % a == 0)
			{
				ans[ti] = n / a;
				break;
			}
			a <<= 1;
			++a;
		}
	}

	foreach (e; ans)
		writeln(e);
	stdout.flush;
	debug readln;
}


DZY has a hash table with p buckets, numbered from 0 to p - 1. He wants to insert n numbers, in the order they are given, into the hash table. For the i-th number xi, DZY will put it into the bucket numbered h(xi), where h(x) is the hash function. In this problem we will assume, that h(x) = x mod p. Operation a mod b denotes taking a remainder after division a by b.However, each bucket can contain no more than one element. If DZY wants to insert an number into a bucket which is already filled, we say a "conflict" happens. Suppose the first conflict happens right after the i-th insertion, you should output i. If no conflict happens, just output -1.

The first line contains two integers, p and n (2 ≤ p, n ≤ 300). Then n lines follow. The i-th of them contains an integer xi (0 ≤ xi ≤ 109).

Output a single integer — the answer to the problem.

import std.stdio;
import std.c.stdio;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.regex;
import std.typecons;

int P, N;
int[] X;
void main() {
    scanf("%d %d\n", &P, &N);

    int h(int x) {
        return x % P;
    }

    X = new int[P];
    X[] = -1;
    foreach (i; 0 .. N) {
        int x;
        scanf("%d\n", &x);
        int y = h(x);
        if (X[y] >= 0) {
            writeln(i + 1);
            return;
        } else {
            X[y] = x;
        }
    }
    writeln(-1);
}

import std.stdio, std.algorithm, std.container, std.conv, std.typecons, std.range, std.string;

void main() {
  int p, n;
  readf("%s %s\n", &p, &n);
  auto s = redBlackTree!int();
  int x, i, c=1;
  for (i=0; i<n; i++) {
    x = (readln.strip.to!int) % p;
    if (!(x in s)) {
      c++;
    } else break;
    s.insert(x);
  }
  if (i==n)
    writeln(-1);
  else
    writeln(c);
}

import std.stdio;
import std.string;
import std.bigint;
import std.array;
import std.ascii;
import std.math;
import std.numeric;
import std.algorithm;
import std.container;
import core.bitop;
import std.conv;

alias Int = long;

void main() {
  int p, n;
  readf(" %s", &p);
  readf(" %s", &n);
  auto list = new bool[300 + 1];
  list[] = false;
  foreach ( i; 0 .. n ) {
    Int x;
    readf(" %s", &x);
    if ( list[x % p] ) {
      writeln(i + 1);
      return;
    }
    list[x % p] = true;
  }
  writeln(-1);
}

//http://codeforces.com/contest/447/problem/A

import std.stdio;

void main(){
  uint p,n;
  readf("%s ",&p);
  readf("%s ",&n);
  uint[] l = new uint[n];
  for(uint i = 0; i < n; i++){
    readf("%s ",&l[i]);
  }
  writefln("%s",run(p,l));
}

long run(uint n, uint[] l){
  bool[] mt = new bool[n];
  for(uint i = 0; i < n; i++){
    mt[i] = false;
  }

  uint j = 0;
  foreach(uint x; l){
    uint h = x % n;
    if (mt[h] == false) {
      mt[h] = true;
    } else {
      return j + 1;
    }
    j++;
  }

  return -1;
}

// TEST CASE AREA
// void test_case(){
//   uint[][] rs;
//   rs ~= [run(10,[0,21,53,41,53]),4];
//   rs ~= [run(5,[0,1,2,3,4]),-1];
//
//   array_assert(rs);
// }
//
// void array_assert(uint[][] rs){
//   uint i = 1;
//   bool failed = false;
//   foreach(uint[] r;rs){
//     if(r[0] != r[1]){
//       failed = true;
//       writefln("%s Failed %s is NOT %s",i,r[0],r[1]);
//     }
//     i++;
//   }
//
//   if(!failed){
//     writefln("OK");
//   }
// }

import core.thread;
import std.conv, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.container, std.math, std.range, std.regex;

//	Input
class EOFException : Throwable { this() { super("EOF"); } }
string[] tokens;
string readToken() { for (; tokens.empty; ) { tokens = readln.split; if (stdin.eof) throw new EOFException; } auto token = tokens[0]; tokens.popFront; return token; }
int readInt() { return to!int(readToken); }
long readLong() { return to!long(readToken); }
real readReal() { return to!real(readToken); }

//	chmin/chmax
void chmin(T)(ref T t, const T f) { if (t > f) t = f; }
void chmax(T)(ref T t, const T f) { if (t < f) t = f; }

//	Pair
struct Pair(S, T) {
	S x; T y;
	int opCmp(ref const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; }
	string toString() const { return "(" ~ to!string(x) ~ ", " ~ to!string(y) ~ ")"; }
}
auto pair(S, T)(S x, T y) { return Pair!(S, T)(x, y); }

//	Array
int binarySearch(T)(T[] as, bool delegate(T) test) { int low = -1, upp = as.length; for (; low + 1 < upp; ) { int mid = (low + upp) >> 1; (test(as[mid]) ? low : upp) = mid; } return upp; }
int lowerBound(T)(T[] as, T val) { return as.binarySearch((T a) { return (a <  val); }); }
int upperBound(T)(T[] as, T val) { return as.binarySearch((T a) { return (a <= val); }); }
T[] unique(T)(T[] as) { T[] bs; foreach (a; as) if (bs.empty || bs[$ - 1] != a) bs ~= a; return bs; }

int P;
int N;
int[] X;

void main(string[] args) {
	try {
	for (; ; ) {
		P = readInt;
		N = readInt;
		X = new int[N];
		foreach (i; 0 .. N) {
			X[i] = readInt;
		}

		int ans = -1;
		bool[] app = new bool[P];
		foreach (i; 0 .. N) {
			const key = X[i] % P;
			if (app[key]) {
				ans = i + 1;
				break;
			}
			app[key] = true;
		}
		writeln(ans);

	}
	} catch (EOFException) {}
}

import std.stdio, std.algorithm, std.container, std.conv, std.typecons, std.range, std.string;

void main() {
  int p, n;
  readf("%s %s\n", &p, &n);
  auto s = redBlackTree!int();
  int x, i;
  for (i=0; i<n; i++) {
    x = (readln.strip.to!int) % p;
    if (x in s) {
      i++;
      break;
    }
    s.insert(x);
  }
  if (i==n)
    writeln(-1);
  else
    writeln(i);
}


Two integer sequences existed initially — one of them was strictly increasing, and the other one — strictly decreasing.Strictly increasing sequence is a sequence of integers $$$[x_1 < x_2 < \dots < x_k]$$$. And strictly decreasing sequence is a sequence of integers $$$[y_1 > y_2 > \dots > y_l]$$$. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.They were merged into one sequence $$$a$$$. After that sequence $$$a$$$ got shuffled. For example, some of the possible resulting sequences $$$a$$$ for an increasing sequence $$$[1, 3, 4]$$$ and a decreasing sequence $$$[10, 4, 2]$$$ are sequences $$$[1, 2, 3, 4, 4, 10]$$$ or $$$[4, 2, 1, 10, 4, 3]$$$.This shuffled sequence $$$a$$$ is given in the input.Your task is to find any two suitable initial sequences. One of them should be strictly increasing and the other one — strictly decreasing. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.If there is a contradiction in the input and it is impossible to split the given sequence $$$a$$$ to increasing and decreasing sequences, print "NO".

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.

If there is a contradiction in the input and it is impossible to split the given sequence $$$a$$$ to increasing and decreasing sequences, print "NO" in the first line. Otherwise print "YES" in the first line and any two suitable sequences. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing. In the second line print $$$n_i$$$ — the number of elements in the strictly increasing sequence. $$$n_i$$$ can be zero, in this case the increasing sequence is empty. In the third line print $$$n_i$$$ integers $$$inc_1, inc_2, \dots, inc_{n_i}$$$ in the increasing order of its values ($$$inc_1 < inc_2 < \dots < inc_{n_i}$$$) — the strictly increasing sequence itself. You can keep this line empty if $$$n_i = 0$$$ (or just print the empty line). In the fourth line print $$$n_d$$$ — the number of elements in the strictly decreasing sequence. $$$n_d$$$ can be zero, in this case the decreasing sequence is empty. In the fifth line print $$$n_d$$$ integers $$$dec_1, dec_2, \dots, dec_{n_d}$$$ in the decreasing order of its values ($$$dec_1 > dec_2 > \dots > dec_{n_d}$$$) — the strictly decreasing sequence itself. You can keep this line empty if $$$n_d = 0$$$ (or just print the empty line). $$$n_i + n_d$$$ should be equal to $$$n$$$ and the union of printed sequences should be a permutation of the given sequence (in case of "YES" answer).

import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, core.stdc.string;

immutable long MOD = 10^^9 + 7;

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!long).array;
    A.sort();

    long[] X;
    long[] Y;

    foreach (i; 0..N) {
        if (!X.empty && A[i] == X.back) {
            if (!Y.empty && A[i] == Y.back) {
                writeln("NO");
                return;
            }
            Y ~= A[i];
        } else {
            X ~= A[i];
        }
    }

    foreach (i; 0..Y.length.to!int/2) {
        swap(Y[i], Y[Y.length.to!int-i-1]);
    }

    writeln("YES");
    writeln(X.length);
    writeln(X.map!(to!string).join(" "));
    writeln(Y.length);
    writeln(Y.map!(to!string).join(" "));
}


Masha wants to open her own bakery and bake muffins in one of the n cities numbered from 1 to n. There are m bidirectional roads, each of whose connects some pair of cities.To bake muffins in her bakery, Masha needs to establish flour supply from some storage. There are only k storages, located in different cities numbered a1, a2, ..., ak.Unforunately the law of the country Masha lives in prohibits opening bakery in any of the cities which has storage located in it. She can open it only in one of another n - k cities, and, of course, flour delivery should be paid — for every kilometer of path between storage and bakery Masha should pay 1 ruble.Formally, Masha will pay x roubles, if she will open the bakery in some city b (ai ≠ b for every 1 ≤ i ≤ k) and choose a storage in some city s (s = aj for some 1 ≤ j ≤ k) and b and s are connected by some path of roads of summary length x (if there are more than one path, Masha is able to choose which of them should be used).Masha is very thrifty and rational. She is interested in a city, where she can open her bakery (and choose one of k storages and one of the paths between city with bakery and city with storage) and pay minimum possible amount of rubles for flour delivery. Please help Masha find this amount.

The first line of the input contains three integers n, m and k (1 ≤ n, m ≤ 105, 0 ≤ k ≤ n) — the number of cities in country Masha lives in, the number of roads between them and the number of flour storages respectively. Then m lines follow. Each of them contains three integers u, v and l (1 ≤ u, v ≤ n, 1 ≤ l ≤ 109, u ≠ v) meaning that there is a road between cities u and v of length of l kilometers . If k > 0, then the last line of the input contains k distinct integers a1, a2, ..., ak (1 ≤ ai ≤ n) — the number of cities having flour storage located in. If k = 0 then this line is not presented in the input.

Print the minimum possible amount of rubles Masha should pay for flour delivery in the only line. If the bakery can not be opened (while satisfying conditions) in any of the n cities, print  - 1 in the only line.

NoteImage illustrates the first sample case. Cities with storage located in and the road representing the answer are darkened.

import std.stdio;
import std.string;
import std.conv;
import std.algorithm;

struct Key
{
    int x;
    int y;
    this(int x_, int y_)
    {
        x = x_;
        y = y_;
    }
}

void main()
{
    auto s1 = split(readln());
    if (s1[2] == "0")
    {
        writeln(-1);
        return;
    }
    long[Key] hash;
    foreach (ind; 0 .. to!int(s1[1]))
    {
        auto s2 = split(readln);
        int[] keys;
        foreach (j; 0 .. 2)
            keys ~= to!int(s2[j]);
        sort(keys);
        auto key = Key(keys[0], keys[1]);
        if (key !in hash)
            hash[key] = to!long(s2[2]);
        else
            hash[key] = min(hash[key], to!long(s2[2]));
    }
    auto s3 = split(readln);
    bool[int] stores;
    foreach (j; 0 .. s3.length)
    {
        stores[to!int(s3[j])] = true;
    }
    long min_val = long.max;
    foreach (key; hash.keys)
    {
        if (key.x in stores && key.y !in  stores)
            min_val = min(min_val, hash[key]);
        if (key.x !in stores && key.y in stores)
            min_val = min(min_val, hash[key]);
    }
    if (min_val == long.max)
        writeln(-1);
    else
        writeln(min_val);

}


Yaroslav is playing a game called "Time". The game has a timer showing the lifespan he's got left. As soon as the timer shows 0, Yaroslav's character dies and the game ends. Also, the game has n clock stations, station number i is at point (xi, yi) of the plane. As the player visits station number i, he increases the current time on his timer by ai. The stations are for one-time use only, so if the player visits some station another time, the time on his timer won't grow.A player spends d·dist time units to move between stations, where dist is the distance the player has covered and d is some constant. The distance between stations i and j is determined as |xi - xj| + |yi - yj|.Initially, the player is at station number 1, and the player has strictly more than zero and strictly less than one units of time. At station number 1 one unit of money can increase the time on the timer by one time unit (you can buy only integer number of time units).Now Yaroslav is wondering, how much money he needs to get to station n. Help Yaroslav. Consider the time to buy and to increase the timer value negligibly small.

The first line contains integers n and d (3 ≤ n ≤ 100, 103 ≤ d ≤ 105) — the number of stations and the constant from the statement. The second line contains n - 2 integers: a2, a3, ..., an - 1 (1 ≤ ai ≤ 103). The next n lines contain the coordinates of the stations. The i-th of them contains two integers xi, yi (-100 ≤ xi, yi ≤ 100). It is guaranteed that no two stations are located at the same point.

In a single line print an integer — the answer to the problem.

import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

struct S {
    int x, y;
}

struct Edge {
    int from, to, cost;
}

void main() {
    int N, d; scanf("%d %d\n", &N, &d);
    auto A = [0] ~ readln.chomp.split(" ").map!(to!int).array ~ [0];
    auto ss = new S[N];
    foreach (i; 0 .. N) {
        int x, y; scanf("%d %d\n", &x, &y);
        ss[i].x = x;
        ss[i].y = y;
    }

    auto G = new Edge[][N];
    foreach (int i; 0 .. N) {
        foreach (int j; i + 1 .. N) {
            auto cost = d * (abs(ss[i].y - ss[j].y) + abs(ss[i].x - ss[j].x));
            G[i] ~= Edge(i, j, cost - A[j]);
            G[j] ~= Edge(j, i, cost - A[i]);
        }
    }

    struct P {
        int v, cost;
    }
    BinaryHeap!(Array!P, "a.cost > b.cost") PQ;
    PQ.insert(P(0, 0));
    auto D = new int[N];
    const INF = int.max / 2;
    D[] = INF;
    D[0] = 0;
    while (!PQ.empty) {
        auto cur = PQ.front; PQ.removeFront;
        foreach (e; G[cur.v]) {
            auto ncost = D[cur.v] + e.cost;
            if (D[e.to] > ncost) {
                D[e.to] = ncost;
                PQ.insert(P(e.to, ncost));
            }
        }
    }
    writeln(D[N - 1]);
}

import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

struct S {
    int x, y;
    int a;
}

void main() {
    int N, D; scanf("%d %d\n", &N, &D);
    auto A = readln.chomp.split(" ").map!(to!int).array;
    auto ss = new S[N];
    foreach (i; 0 .. N) {
        int x, y; scanf("%d %d\n", &x, &y);
        ss[i].x = x;
        ss[i].y = y;
        if (1 <= i && i < N - 1) {
            ss[i].a = A[i - 1];
        }
    }
    int ox = ss[0].x,
        oy = ss[0].y;
    foreach (i; 0 .. N) {
        ss[i].x -= ox;
        ss[i].y -= oy;
    }
    if (ss[N - 1].x < 0) {
        foreach (i; 0 .. N) {
            ss[i].x *= -1;
        }
    }
    if (ss[N - 1].y < 0) {
        foreach (i; 0 .. N) {
            ss[i].y *= -1;
        }
    }
    const long INF = long.max / 4;

    auto gy = ss[N - 1].y,
         gx = ss[N - 1].x;
    auto ly = gy * 2 + 5,
         lx = gx * 2 + 5;
    auto dp = new long[][](ly + 1, lx + 1);
    auto aa = new long[][](ly + 1, lx + 1);
    foreach (i; 0 .. ly + 1) dp[i][] = -INF;
    foreach (i; 1 .. N - 1) {
        int x = ss[i].x,
            y = ss[i].y;
        if (0 <= x && x <= lx && 0 <= y && y <= ly) {
            aa[y][x] += ss[i].a;
        }
    }

    const dy = [-1, 0, 1, 0],
          dx = [0, 1, 0, -1];
    struct P {
        int y, x;
    }
    DList!P Q;
    Q.insert(P(0, 0));
    dp[0][0] = 0;
    while (!Q.empty) {
        auto cur = Q.front; Q.removeFront;
        //writeln(cur);
        int y = cur.y,
            x = cur.x;
        foreach (k; 0 .. 4) {
            int ny = y + dy[k],
                nx = x + dx[k];
            if (ny < 0 || ny > ly) continue;
            if (nx < 0 || nx > lx) continue;
            if (dp[ny][nx] < dp[y][x] - D + aa[y][x]) {
                dp[ny][nx] = dp[y][x] - D + aa[y][x];
                Q.insert(P(ny, nx));
            }
        }
    }
    //writeln(dp);
    writeln(-dp[gy][gx]);
}

import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

struct S {
    int x, y;
    int a;
}

void main() {
    int N, D; scanf("%d %d\n", &N, &D);
    auto A = readln.chomp.split(" ").map!(to!int).array;
    auto ss = new S[N];
    foreach (i; 0 .. N) {
        int x, y; scanf("%d %d\n", &x, &y);
        ss[i].x = x;
        ss[i].y = y;
        if (1 <= i && i < N - 1) {
            ss[i].a = A[i - 1];
        }
    }
    int ox = ss[0].x,
        oy = ss[0].y;
    foreach (i; 0 .. N) {
        ss[i].x -= ox;
        ss[i].y -= oy;
    }
    if (ss[N - 1].x < 0) {
        foreach (i; 0 .. N) {
            ss[i].x *= -1;
        }
    }
    if (ss[N - 1].y < 0) {
        foreach (i; 0 .. N) {
            ss[i].y *= -1;
        }
    }
    const long INF = long.max / 4;

    auto gy = ss[N - 1].y,
         gx = ss[N - 1].x;
    auto dp = new long[][](gy + 1, gx + 1);
    auto aa = new long[][](gy + 1, gx + 1);
    foreach (i; 0 .. gy + 1) dp[i][] = -INF;
    foreach (i; 1 .. N - 1) {
        int x = ss[i].x,
            y = ss[i].y;
        if (0 <= x && x <= gx && 0 <= y && y <= gy) {
            aa[y][x] += ss[i].a;
        }
    }

    const dy = [-1, 0, 1, 0],
          dx = [0, 1, 0, -1];
    struct P {
        int y, x;
    }
    DList!P Q;
    Q.insert(P(0, 0));
    dp[0][0] = 0;
    while (!Q.empty) {
        auto cur = Q.front; Q.removeFront;
        //writeln(cur);
        int y = cur.y,
            x = cur.x;
        foreach (k; 0 .. 4) {
            int ny = y + dy[k],
                nx = x + dx[k];
            if (ny < 0 || ny > gy) continue;
            if (nx < 0 || nx > gx) continue;
            if (dp[ny][nx] < dp[y][x] - D + aa[y][x]) {
                dp[ny][nx] = dp[y][x] - D + aa[y][x];
                Q.insert(P(ny, nx));
            }
        }
    }
    //writeln(dp);
    writeln(-dp[gy][gx]);
}

import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

struct S {
    int x, y;
    int a;
}

void main() {
    int N, D; scanf("%d %d\n", &N, &D);
    auto A = readln.chomp.split(" ").map!(to!int).array;
    auto ss = new S[N];
    foreach (i; 0 .. N) {
        int x, y; scanf("%d %d\n", &x, &y);
        ss[i].x = x;
        ss[i].y = y;
        if (1 <= i && i < N - 1) {
            ss[i].a = A[i - 1];
        }
    }
    int ox = ss[0].x,
        oy = ss[0].y;
    foreach (i; 0 .. N) {
        ss[i].x -= ox;
        ss[i].y -= oy;
    }
    if (ss[N - 1].x < 0) {
        foreach (i; 0 .. N) {
            ss[i].x *= -1;
        }
    }
    if (ss[N - 1].y < 0) {
        foreach (i; 0 .. N) {
            ss[i].y *= -1;
        }
    }
    const INF = 1<<28;

    auto gy = ss[N - 1].y,
         gx = ss[N - 1].x;
    auto dp = new int[][](gy + 1, gx + 1);
    auto aa = new int[][](gy + 1, gx + 1);
    foreach (i; 0 .. gy + 1) dp[i][] = -INF;
    foreach (i; 1 .. N - 1) {
        int x = ss[i].x,
            y = ss[i].y;
        if (0 <= x && x <= gx && 0 <= y && y <= gy) {
            aa[y][x] += ss[i].a;
        }
    }

    const dy = [-1, 0, 1, 0],
          dx = [0, 1, 0, -1];
    struct P {
        int y, x;
    }
    DList!P Q;
    Q.insert(P(0, 0));
    dp[0][0] = 0;
    while (!Q.empty) {
        auto cur = Q.front; Q.removeFront;
        //writeln(cur);
        int y = cur.y,
            x = cur.x;
        foreach (k; 0 .. 4) {
            int ny = y + dy[k],
                nx = x + dx[k];
            if (ny < 0 || ny > gy) continue;
            if (nx < 0 || nx > gx) continue;
            if (dp[ny][nx] < dp[y][x] - D + aa[y][x]) {
                dp[ny][nx] = dp[y][x] - D + aa[y][x];
                Q.insert(P(ny, nx));
            }
        }
    }
    //writeln(dp);
    writeln(-dp[gy][gx]);
}

import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

struct S {
    int x, y;
    int a;
}

void main() {
    int N, D; scanf("%d %d\n", &N, &D);
    auto A = readln.chomp.split(" ").map!(to!int).array;
    auto ss = new S[N];
    foreach (i; 0 .. N) {
        int x, y; scanf("%d %d\n", &x, &y);
        ss[i].x = x;
        ss[i].y = y;
        if (1 <= i && i < N - 1) {
            ss[i].a = A[i - 1];
        }
    }
    int ox = ss[0].x,
        oy = ss[0].y;
    foreach (i; 0 .. N) {
        ss[i].x -= ox;
        ss[i].y -= oy;
    }
    if (ss[N - 1].x < 0) {
        foreach (i; 0 .. N) {
            ss[i].x *= -1;
        }
    }
    if (ss[N - 1].y < 0) {
        foreach (i; 0 .. N) {
            ss[i].y *= -1;
        }
    }
    const long INF = long.max / 4;

    auto gy = ss[N - 1].y,
         gx = ss[N - 1].x;
    auto dp = new long[][](gy + 1, gx + 1);
    auto aa = new long[][](gy + 1, gx + 1);
    foreach (i; 0 .. gy + 1) dp[i][] = -INF;
    foreach (i; 1 .. N - 1) {
        int x = ss[i].x,
            y = ss[i].y;
        if (0 <= x && x <= gx && 0 <= y && y <= gy) {
            aa[y][x] += ss[i].a;
        }
    }

    const dy = [-1, 0, 1, 0],
          dx = [0, 1, 0, -1];
    struct P {
        int y, x;
    }
    DList!P Q;
    Q.insert(P(0, 0));
    dp[0][0] = 0;
    while (!Q.empty) {
        auto cur = Q.front; Q.removeFront;
        //writeln(cur);
        int y = cur.y,
            x = cur.x;
        foreach (k; 0 .. 4) {
            int ny = y + dy[k],
                nx = x + dx[k];
            if (ny < 0 || ny > gy) continue;
            if (nx < 0 || nx > gx) continue;
            if (dp[ny][nx] < dp[y][x] - D*2 + aa[y][x]) {
                dp[ny][nx] = dp[y][x] - D*2 + aa[y][x];
                Q.insert(P(ny, nx));
            }
        }
    }
    //writeln(dp);
    writeln(-dp[gy][gx] - D * (gy + gx));
}

import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

struct S {
    int x, y;
    int a;
}

void main() {
    int N, D; scanf("%d %d\n", &N, &D);
    auto A = readln.chomp.split(" ").map!(to!int).array;
    auto ss = new S[N];
    foreach (i; 0 .. N) {
        int x, y; scanf("%d %d\n", &x, &y);
        ss[i].x = x;
        ss[i].y = y;
        if (1 <= i && i < N - 1) {
            ss[i].a = A[i - 1];
        }
    }
    int ox = ss[0].x,
        oy = ss[0].y;
    foreach (i; 0 .. N) {
        ss[i].x -= ox;
        ss[i].y -= oy;
    }
    if (ss[N - 1].x < 0) {
        foreach (i; 0 .. N) {
            ss[i].x *= -1;
        }
    }
    if (ss[N - 1].y < 0) {
        foreach (i; 0 .. N) {
            ss[i].y *= -1;
        }
    }
    const long INF = long.max / 4;

    auto gy = ss[N - 1].y,
         gx = ss[N - 1].x;
    auto ly = gy * 2 + 5,
         lx = gx * 2 + 5;
    auto dp = new long[][](ly + 1, lx + 1);
    auto aa = new long[][](ly + 1, lx + 1);
    foreach (i; 0 .. ly + 1) dp[i][] = INF;
    foreach (i; 1 .. N - 1) {
        int x = ss[i].x,
            y = ss[i].y;
        if (0 <= x && x <= lx && 0 <= y && y <= ly) {
            aa[y][x] -= ss[i].a;
        }
    }

    const dy = [-1, 0, 1, 0],
          dx = [0, 1, 0, -1];
    struct P {
        int y, x;
        long t;
    }
    BinaryHeap!(Array!P, "a.t > b.t") Q;
    Q.insert(P(0, 0, 0));
    dp[0][0] = 0;
    while (!Q.empty) {
        auto cur = Q.front; Q.removeFront;
        //writeln(cur);
        int y = cur.y,
            x = cur.x;
        foreach (k; 0 .. 4) {
            int ny = y + dy[k],
                nx = x + dx[k];
            if (ny < 0 || ny > ly) continue;
            if (nx < 0 || nx > lx) continue;
            if (dp[ny][nx] > dp[y][x] + D + aa[y][x]) {
                dp[ny][nx] = dp[y][x] + D + aa[y][x];
                Q.insert(P(ny, nx, dp[ny][nx]));
            }
        }
    }
    //writeln(dp);
    writeln(dp[gy][gx]);
}

import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

struct S {
    int x, y;
    int a;
}

void main() {
    int N, D; scanf("%d %d\n", &N, &D);
    auto A = readln.chomp.split(" ").map!(to!int).array;
    auto ss = new S[N];
    foreach (i; 0 .. N) {
        int x, y; scanf("%d %d\n", &x, &y);
        ss[i].x = x;
        ss[i].y = y;
        if (1 <= i && i < N - 1) {
            ss[i].a = A[i - 1];
        }
    }
    int ox = ss[0].x,
        oy = ss[0].y;
    foreach (i; 0 .. N) {
        ss[i].x -= ox;
        ss[i].y -= oy;
    }
    if (ss[N - 1].x < 0) {
        foreach (i; 0 .. N) {
            ss[i].x *= -1;
        }
    }
    if (ss[N - 1].y < 0) {
        foreach (i; 0 .. N) {
            ss[i].y *= -1;
        }
    }
    const INF = 1<<28;

    auto gy = ss[N - 1].y,
         gx = ss[N - 1].x;
    auto dp = new long[][](gy + 1, gx + 1);
    auto aa = new long[][](gy + 1, gx + 1);
    foreach (i; 0 .. gy + 1) dp[i][] = -INF;
    foreach (i; 1 .. N - 1) {
        int x = ss[i].x,
            y = ss[i].y;
        if (0 <= x && x <= gx && 0 <= y && y <= gy) {
            aa[y][x] += ss[i].a;
        }
    }

    const dy = [-1, 0, 1, 0],
          dx = [0, 1, 0, -1];
    struct P {
        int y, x;
    }
    DList!P Q;
    Q.insert(P(0, 0));
    dp[0][0] = 0;
    while (!Q.empty) {
        auto cur = Q.front; Q.removeFront;
        //writeln(cur);
        int y = cur.y,
            x = cur.x;
        foreach (k; 0 .. 4) {
            int ny = y + dy[k],
                nx = x + dx[k];
            if (ny < 0 || ny > gy) continue;
            if (nx < 0 || nx > gx) continue;
            if (dp[ny][nx] < dp[y][x] - D + aa[y][x]) {
                dp[ny][nx] = dp[y][x] - D + aa[y][x];
                Q.insert(P(ny, nx));
            }
        }
    }
    //writeln(dp);
    writeln(-dp[gy][gx]);
}