Search is not available for this dataset
name
stringlengths 2
112
| description
stringlengths 29
13k
| source
int64 1
7
| difficulty
int64 0
25
| solution
stringlengths 7
983k
| language
stringclasses 4
values |
---|---|---|---|---|---|
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 |
n,q=map(int,input().split())
st=input()
sum_st=[0]
add=0
for i in st:
if i=='1':
add+=1
sum_st.append(add)
count=0
M=10**9+7
ans=[]
for i in range(q):
l,r=map(int,input().split())
x=sum_st[r]-sum_st[l-1]
y=r-l-x+1
rs=(pow(2,x,M)-1)%M
ss=(rs*pow(2,y,M))%M
ans.append(ss)
for i in ans:
print(i)
| PYTHON3 |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | from sys import *
ans = []
n , q = map(int,stdin.readline().split())
s = stdin.readline()
MOD = 1000000007
t = [0 for i in range(n+1)]
t[0] = 0
for i in range(1,n+1):
t[i] = t[i-1]+1 if s[i-1]=="1" else t[i-1]
# print(t)
for i in range(q):
l , r = map(int,stdin.readline().split())
_sum = r-l+1
zero = _sum - t[r]+t[l-1]
res = (pow(2,_sum,MOD)-pow(2,zero,MOD))%MOD
ans.append(res)
stdout.write('\n'.join(map(str, ans))) | PYTHON3 |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 |
/**
* Date: 14 Nov, 2018
* Link:
*
* @author Prasad-Chaudhari
* @linkedIn: https://www.linkedin.com/in/prasad-chaudhari-841655a6/
* @git: https://github.com/Prasad-Chaudhari
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
public class newProgram8 {
public static void main(String[] args) throws IOException {
// TODO code application logic here
FastIO in = new FastIO();
int n = in.ni();
int q = in.ni();
char c[] = in.next().toCharArray();
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = c[i] - '0';
}
int ones[] = new int[n];
int zero[] = new int[n];
for (int i = 0; i < n; i++) {
ones[i] = a[i];
zero[i] = 1 - a[i];
}
for (int i = 1; i < n; i++) {
ones[i] += ones[i - 1];
zero[i] += zero[i - 1];
}
long power[] = new long[n + 1];
power[0] = 1;
long mod = 1000000007;
for (int i = 1; i <= n; i++) {
power[i] = 2 * power[i - 1];
power[i] %= mod;
}
while (q-- > 0) {
int l = in.ni() - 1;
int r = in.ni() - 1;
int one = ones[r];
if (l > 0) {
one -= ones[l - 1];
}
int zeros = zero[r];
if (l > 0) {
zeros -= zero[l - 1];
}
System.out.println((power[one + zeros] - power[zeros] + mod) % mod);
}
}
static class Expo {
static long a_pow_n_mod_m(long a, long n, long m) {
if (n == 0) {
return 1;
}
if (n == 1) {
return a;
}
long p = a_pow_n_mod_m(a, n / 2, m);
if (n % 2 == 0) {
return (p * p) % m;
} else {
return ((p * p) % m * a) % m;
}
}
static long a_pow_n(long a, long n) {
if (n == 0) {
return 1;
}
if (n == 1) {
return a;
}
long p = a_pow_n(a, n / 2);
if (n % 2 == 0) {
return (p * p);
} else {
return ((p * p) * a);
}
}
}
static class FastIO {
private final BufferedReader br;
private final BufferedWriter bw;
private String s[];
private int index;
private StringBuilder sb;
public FastIO() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out, "UTF-8"));
s = br.readLine().split(" ");
sb = new StringBuilder();
index = 0;
}
public int ni() throws IOException {
return Integer.parseInt(nextToken());
}
public double nd() throws IOException {
return Double.parseDouble(nextToken());
}
public long nl() throws IOException {
return Long.parseLong(nextToken());
}
public String next() throws IOException {
return nextToken();
}
public String nli() throws IOException {
try {
return br.readLine();
} catch (IOException ex) {
}
return null;
}
public int[] gia(int n) throws IOException {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}
public int[] gia(int n, int start, int end) throws IOException {
validate(n, start, end);
int a[] = new int[n];
for (int i = start; i < end; i++) {
a[i] = ni();
}
return a;
}
public double[] gda(int n) throws IOException {
double a[] = new double[n];
for (int i = 0; i < n; i++) {
a[i] = nd();
}
return a;
}
public double[] gda(int n, int start, int end) throws IOException {
validate(n, start, end);
double a[] = new double[n];
for (int i = start; i < end; i++) {
a[i] = nd();
}
return a;
}
public long[] gla(int n) throws IOException {
long a[] = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nl();
}
return a;
}
public long[] gla(int n, int start, int end) throws IOException {
validate(n, start, end);
long a[] = new long[n];
for (int i = start; i < end; i++) {
a[i] = nl();
}
return a;
}
public int[][] gg(int n, int m) throws IOException {
int adja[][] = new int[n + 1][];
int from[] = new int[m];
int to[] = new int[m];
int count[] = new int[n + 1];
for (int i = 0; i < m; i++) {
from[i] = ni();
to[i] = ni();
count[from[i]]++;
count[to[i]]++;
}
for (int i = 0; i <= n; i++) {
adja[i] = new int[count[i]];
}
for (int i = 0; i < m; i++) {
adja[from[i]][--count[from[i]]] = to[i];
adja[to[i]][--count[to[i]]] = from[i];
}
return adja;
}
public void print(String s) throws IOException {
bw.write(s);
}
public void println(String s) throws IOException {
bw.write(s);
bw.newLine();
}
private String nextToken() throws IndexOutOfBoundsException, IOException {
if (index == s.length) {
s = br.readLine().split(" ");
index = 0;
}
return s[index++];
}
private void validate(int n, int start, int end) {
if (start < 0 || end >= n) {
throw new IllegalArgumentException();
}
}
}
static class Data implements Comparable<Data> {
int a, b;
public Data(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(Data o) {
if (a == o.a) {
return Integer.compare(b, o.b);
}
return Integer.compare(a, o.a);
}
public static void sort(int a[]) {
Data d[] = new Data[a.length];
for (int i = 0; i < a.length; i++) {
d[i] = new Data(a[i], 0);
}
Arrays.sort(d);
for (int i = 0; i < a.length; i++) {
a[i] = d[i].a;
}
}
}
}
| JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import java.util.*;
import java.io.*;
import java.math.*;
public class Main2
{
static class Reader
{
private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;}
public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];}
public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;}
public String s(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();}
public long l(){int c = read();while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }long res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read();}while(!isSpaceChar(c));return res * sgn;}
public int i(){int c = read() ;while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }int res = 0;do{if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read() ;}while(!isSpaceChar(c));return res * sgn;}
public double d() throws IOException {return Double.parseDouble(s()) ;}
public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; }
public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; }
public int[] arr(int n){int[] ret = new int[n];for (int i = 0; i < n; i++) {ret[i] = i();}return ret;}
}
// |----| /\ | | ----- |
// | / / \ | | | |
// |--/ /----\ |----| | |
// | \ / \ | | | |
// | \ / \ | | ----- -------
static int n;
static int arr[];
public static long power(long x, long y, long p)
{
long res=1;
x = x % p;
while (y > 0)
{
if((y & 1)==1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
public static long compute(int onecount,int zerocount)
{
long ans1=(power(2,(long)onecount,1000000007)-1+1000000007)%1000000007;
long mul1=ans1;
long ans2=(mul1*(power(2,(long)zerocount,1000000007)-1+1000000007)%1000000007)%1000000007;
return (ans1+ans2)%1000000007;
}
public static void main(String[] args)throws IOException
{
PrintWriter out= new PrintWriter(System.out);
Reader sc=new Reader();
int n=sc.i();
int q=sc.i();
String s=sc.s();
arr=new int[n+1];
for(int i=1;i<=n;i++)
arr[i]=arr[i-1]+(s.charAt(i-1)=='0'?0:1);
while(q-->0)
{
int l=sc.i();
int r=sc.i();
out.println(compute(arr[r]-arr[l-1],(r-l+1)-(arr[r]-arr[l-1])));
}
out.flush();
}
} | JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class CodeforcesFun {
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static long moduloPow(long num, int power, int modulo) {
long result = 1;
while (power > 0) {
if ((power & 1) == 1) {
result = result * num % modulo;
}
power = power >> 1;
num = num * num % modulo;
}
return result;
}
public static void main(String[] args) {
MyScanner myScanner = new MyScanner();
String[] firstLine = myScanner.nextLine().split("\\s");
int modulo = (int) Math.pow(10, 9) + 7;
int n = Integer.parseInt(firstLine[0]);
int q = Integer.parseInt(firstLine[1]);
String nums = myScanner.nextLine();
int[] arr = new int[n];
int[] sums = new int[n];
int cnt = 0;
for (int i = 0; i <= n - 1; i++) {
arr[i] = nums.charAt(i) - '0';
if (arr[i] == 1) {
cnt++;
}
sums[i] = cnt;
}
for (int i = 1; i <= q; i++) {
int l = Integer.parseInt(myScanner.next());
int r = Integer.parseInt(myScanner.next());
int ones = sums[r - 1] - sums[l - 1] + arr[l - 1];
int zeros = r - l - ones + 1;
System.out.println((moduloPow(2, r - l + 1, modulo) - moduloPow(2, zeros, modulo) + modulo) % modulo);
}
}
}
| JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
long long dx[] = {-1, 1, 0, 0};
long long dy[] = {0, 0, -1, 1};
long long sub(long long a, long long b, long long p = 1000000007) {
return ((a % p) - (b % p) + p) % p;
}
long long mult(long long a, long long b, long long p = 1000000007) {
return ((a % p) * (b % p)) % p;
}
long long add(long long a, long long b, long long p = 1000000007) {
return (a % p + b % p) % p;
}
long long fpow(long long n, long long k, long long p = 1000000007) {
long long r = 1;
while (k > 0) {
if (k & 1) r = r * n % p;
n = n * n % p;
k = k >> 1;
}
return r;
}
inline long long powr(long long a, long long b) {
long long x = 1;
while (b) {
if (b & 1) x *= a;
a *= a;
b >>= 1;
}
return x;
}
long long inv(long long a, long long p = 1000000007) {
return fpow(a, p - 2, p);
}
long long fdiv(long long a, long long b, long long p = 1000000007) {
long long yinv = inv(b);
long long ans = (a * yinv) % p;
return ans;
}
long long _pow(long long p, long long q) {
long long res = 1;
while (q) {
if (q & 1) res = (res * p) % 1000000007;
p = (p * p) % 1000000007;
q = q >> 1;
}
return (res + 1000000007) % 1000000007;
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long n, q;
cin >> n >> q;
string s;
cin >> s;
vector<long long> ones(n + 1);
for (long long i = 0; i < n; ++i) {
if (s[i] == '1')
ones[i + 1] = ones[i] + 1;
else
ones[i + 1] = ones[i];
}
for (long long i = 0; i < q; ++i) {
long long l, r;
cin >> l >> r;
long long one = ones[r] - ones[l - 1];
long long z = r - l + 1 - one;
long long p = _pow(2ll, one) - 1;
long long k = mult(z, z + 1) / 2;
long long ans = add(p, mult((_pow(2ll, z) - 1), p));
cout << ans << "\n";
}
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | from sys import stdin
from collections import deque
mod = 10**9 + 7
import sys
sys.setrecursionlimit(10**5)
from queue import PriorityQueue
# def rl():
# return [int(w) for w in stdin.readline().split()]
from bisect import bisect_right
from bisect import bisect_left
from collections import defaultdict
from math import sqrt,factorial,gcd,log2,inf,ceil
# map(int,input().split())
# # l = list(map(int,input().split()))
# from itertools import permutations
import heapq
# input = lambda: sys.stdin.readline().rstrip()
input = lambda : sys.stdin.readline().rstrip()
from sys import stdin, stdout
from heapq import heapify, heappush, heappop
n,q = map(int,input().split())
l = list(input())
pref = [0]
for i in l:
pref.append(pref[-1] + int(i))
for i in range(q):
a,b = map(int,input().split())
z = pref[b] - pref[a-1]
k1 = pow(2,z,mod)-1
z1 = b-a + 1 - z
k2 = k1%mod*(pow(2,z1,mod)-1)
k2%=mod
print((k1+k2)%mod)
| PYTHON3 |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
long long N, Q, S[(int)1e5 + 5], i, L, R, p1, p2;
long long Putere(long long p1, long long ex) {
long long i, sol = 1;
for (i = 0; (1 << i) <= ex; i++) {
if (((1 << i) & ex) > 0) sol = (sol * p1) % 1000000007;
p1 = (p1 * p1) % 1000000007;
}
return sol;
}
string str;
int main() {
cin >> N >> Q;
cin >> str;
for (i = 0; i < str.length(); i++) {
if (str[i] == '1')
S[i + 1] = S[i] + 1;
else
S[i + 1] = S[i];
}
while (Q--) {
cin >> L >> R;
p1 = S[R] - S[L - 1];
p2 = R - L + 1 - p1;
cout << ((Putere(2, p1) - 1 + (Putere(2, p1) - 1) * (Putere(2, p2) - 1))) %
1000000007
<< "\n";
}
return 0;
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import sys
import io, os
input = sys.stdin.readline
def main():
n, q = map(int, input().split())
A = str(input().rstrip())
A = [int(a) for a in A]
from itertools import accumulate
C = [0]+A
C = list(accumulate(C))
N = 10**5+50
mod = 10**9+7
table = [0]*N
table[0] = 1
for i in range(1, N):
table[i] = table[i-1]*2
table[i] %= mod
for i in range(q):
l, r = map(int, input().split())
l, r = l-1, r-1
c1 = C[r+1]-C[l]
c0 = (r-l+1)-c1
ans = (table[r-l+1]-1)-(table[c0]-1)
print(ans%mod)
if __name__ == '__main__':
main()
| PYTHON3 |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | M=1000000007
R=lambda:map(int,raw_input().split())
n,q=R()
a=[0]+map(int,raw_input())
for i in range(n):
a[i+1]+=a[i]
v=[]
for _ in range(q):
l,r=R()
o=a[r]-a[l-1]
z=r-l+1-o
x=pow(2,o+z,M)-pow(2,z,M)
v+=x+M*(x<0),
print '\n'.join(map(str,v))
| PYTHON |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class C {
static int mod = (int)1e9 + 7;
public static void main(String[] args) {
MyScanner sc = new MyScanner();
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
int q = sc.nextInt();
int[] pow2 = new int[1000000];
pow2[0] = 1;
for (int i = 1; i < pow2.length; i++) {
pow2[i] = (int)((1l*pow2[i-1]*2)%mod);
}
char[] arr = sc.next().toCharArray();
int[] cumOnes = new int[n];
int[] cumZeros = new int[n];
for (int i = 0; i < n; i++) {
if(arr[i] == '1')
cumOnes[i] = 1;
else
cumZeros[i] = 1;
if(i > 0) {
cumOnes[i] += cumOnes[i - 1];
cumZeros[i] += cumZeros[i-1];
}
}
while(q-->0)
{
int l = sc.nextInt()-1;
int r = sc.nextInt()-1;
int cntOnes = cumOnes[r];
int cntZeros = cumZeros[r];
if(l > 0){
cntOnes -= cumOnes[l-1];
cntZeros -= cumZeros[l-1];
}
int ans = adj(pow2[cntOnes]-1);
ans = adj(ans + adj(1l*ans*(adj(pow2[cntZeros]-1))));
pw.println(ans);
}
pw.flush();
pw.close();
}
static int adj(long a){
return (int)(((a%mod) + mod) %mod);
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
void no() { cout << "NO\n"; }
void yes() { cout << "YES\n"; }
long long int pow_(long long int a, long long int n) {
if (n == 0) return 1;
if (n == 1) return a;
if (n % 2 == 0)
return ((pow_(a, n / 2) % 1000000007) * (pow_(a, n / 2) % 1000000007)) %
1000000007;
else
return ((((pow_(a, n / 2) % 1000000007) * (pow_(a, n / 2) % 1000000007)) %
1000000007) *
(a % 1000000007)) %
1000000007;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long int n, q;
string s;
cin >> n >> q >> s;
long long int o = 0;
long long int z = 0;
vector<pair<long long int, long long int> > v(n + 1);
v[0] = make_pair(0, 0);
for (long long int i = 0; i < n; i += 1) {
if (s[i] == '1') o++;
if (s[i] == '0') z++;
v[i + 1] = make_pair(o, z);
}
for (long long int i = 0; i < q; i += 1) {
long long int l, r;
cin >> l >> r;
long long int len = r - l + 1, ones = v[r].first - v[l - 1].first;
long long int a = pow_(2, len - ones) % 1000000007,
b = ((pow_(2, ones) % 1000000007) - (1 % 1000000007)) %
1000000007;
if (b < 0) b += 1000000007;
cout << ((a % 1000000007) * (b % 1000000007)) % 1000000007 << "\n";
}
return 0;
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
char a[100001];
int len[100001];
long long quick_pow(long long a, int b) {
long long ans = 1;
while (b) {
if (b & 1) ans = (ans * a) % 1000000007;
a = (a * a) % 1000000007;
b >>= 1;
}
return ans;
}
int main() {
int n, q;
while (scanf("%d%d", &n, &q) != EOF) {
memset(len, 0, sizeof(len));
scanf("%s", a);
if (a[0] == '0') len[0]++;
for (int i = 1; i < n; i++)
if (a[i] == '0')
len[i] = len[i - 1] + 1;
else
len[i] = len[i - 1];
while (q--) {
int l, r;
scanf("%d%d", &l, &r);
int x;
if (l >= 2)
x = len[r - 1] - len[l - 2];
else
x = len[r - 1];
long long re = (((quick_pow(2, r - l + 1 - x) - 1) % 1000000007) *
(quick_pow(2, x) % 1000000007) % 1000000007);
printf("%lld\n", re);
}
}
return 0;
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
bool cmp(pair<long long, long long> &a, pair<long long, long long> &b) {
if (a.first == b.first) return (a.second < b.second);
return a.first < b.first;
}
long long nCr(long long n, long long r) {
long long res = 1;
for (int i = n; i > max(r, n - r); i--) res *= i, res %= 1000000007;
for (int i = 2; i <= min(r, n - r); i++) res /= i;
return res % 1000000007;
}
long long exp(long long n, long long j) {
long long i = n, res = 1;
while (j > 0) {
if (j & 1) res *= i;
res %= 1000000007;
i = i * i;
i %= 1000000007;
j >>= 1;
}
return res % 1000000007;
}
int main() {
int T = 1;
while (T--) {
long long n, q, i, j;
cin >> n >> q;
string a;
cin >> a;
long long cone[n + 1];
cone[0] = 0;
for (i = 1; i < n + 1; i++) {
cone[i] = (a[i - 1] == '1') + cone[i - 1];
}
while (q--) {
long long l, r;
cin >> l >> r;
long long ones = cone[r] - cone[l - 1];
long long zeros = (r - l + 1) - ones;
long long x = (exp(2ll, ones) - 1ll) % 1000000007;
long long y = (x * (exp(2ll, zeros) - 1)) % 1000000007;
cout << ((x + y) % 1000000007) << '\n';
}
}
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import java.io.*;
import java.util.*;
public class Main {
static long[] degs;
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
String[] line = reader.readLine().split(" ");
int n = Integer.parseInt(line[0]);
int q = Integer.parseInt(line[1]);
char[] ch = reader.readLine().toCharArray();
int[] a = new int[n + 1];
a[1] = ch[0] - '0';
for(int i = 2; i <= n; i++) {
a[i] = a[i - 1] + (ch[i - 1] - '0');
}
degs = new long[n + 1];
deg(2, n + 1);
for(int i = 0; i < q; i++) {
line = reader.readLine().split(" ");
int l = Integer.parseInt(line[0]);
int r = Integer.parseInt(line[1]);
long oneSum = degs[a[r] - a[l - 1]] - 1;
long secSum = (degs[(r - l + 1) - (a[r] - a[l - 1])] - 1) * oneSum;
//println(oneSum + " " + secSum);
println((oneSum + secSum) % 1_000_000_007);
}
} catch (IOException e) {
}
}
static long deg(int num, int deg) {
long ans = 1;
for(int i = 0; i < deg; i++) {
degs[i] = ans;
ans *= num;
ans %= 1_000_000_007;
}
return ans;
}
static String reverse(String s) {
String ans = "";
char[] c = s.toCharArray();
for(int i = s.length() - 1; i >= 0; i--) {
ans += c[i];
}
return ans;
}
static long fac(int deg) {
long ans = 1;
for(int i = 2; i <= deg; i++) {
ans *= i;
}
return ans;
}
static int r(int a, int b) {
int ans = a / b;
if(a % b != 0)
ans++;
return ans;
}
static void print(Object o) {
System.out.print(o.toString());
}
static void println(Object o) {
System.out.println(o.toString());
}
} | JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
int A[100005][2];
char s[100005];
long long pow_mod(long long x, long long n, long long mod) {
long long res = 1;
while (n > 0) {
if (n & 1) res = res * x % mod;
x = x * x % mod;
n >>= 1;
}
return res;
}
int main() {
int n, q;
memset(A, 0, sizeof(A));
scanf("%d %d", &n, &q);
scanf("%s", s);
for (int i = 1; i <= n; i++) {
if (s[i - 1] == '1') {
A[i][1]++;
A[i + 1][1] = A[i][1];
A[i + 1][0] = A[i][0];
}
if (s[i - 1] == '0') {
A[i][0]++;
A[i + 1][0] = A[i][0];
A[i + 1][1] = A[i][1];
}
}
while (q--) {
int l, r;
scanf("%d %d", &l, &r);
long long x = A[r][1] - A[l - 1][1];
long long y = A[r][0] - A[l - 1][0];
long long tmp1 = pow_mod(2, x, 1000000007) - 1;
long long tmp2 =
(pow_mod(2, x, 1000000007) - 1) * (pow_mod(2, y, 1000000007) - 1);
long long ans = (tmp1 % 1000000007 + tmp2 % 1000000007) % 1000000007;
printf("%lld\n", ans);
}
return 0;
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import java.util.*;
import java.io.*;
public class cfc {
static final int MOD=(int)(1e9+7);
public static void main(String[] args) {
FastScanner scan=new FastScanner();
PrintWriter out=new PrintWriter(System.out);
int n=scan.nextInt(), q=scan.nextInt();
exp=new long[n+1];
exp[0]=1;
for(int i=1;i<exp.length;i++) exp[i]=(exp[i-1]<<1)%MOD;
String s=scan.next();
int[] ones=new int[n];
for(int i=0;i<n;i++) {
int add=i==0?0:ones[i-1];
ones[i]=s.charAt(i)=='1'?1+add:0+add;
}
// System.out.println(Arrays.toString(exp));
for(int i=0;i<q;i++) {
int l=scan.nextInt()-1, r=scan.nextInt()-1;
int one=ones[r];
if(l>0) one-=ones[l-1];
int zero=r-l+1-one;
// System.out.println(zero+" "+one);
long res=((long)exp[one]-1+MOD)%MOD;
res=(res*(long)exp[zero])%MOD;
// System.out.println(one+" "+zero);
out.println(res);
}
out.close();
}
static long[] exp;
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e){e.printStackTrace();}
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {st = new StringTokenizer(br.readLine());}
catch (Exception e) {e.printStackTrace();}
return st.nextToken();
}
public int nextInt() {return Integer.parseInt(next());}
public long nextLong() {return Long.parseLong(next());}
public double nextDouble() {return Double.parseDouble(next());}
public String nextLine() {
String line = "";
if(st.hasMoreTokens()) line = st.nextToken();
else try {return br.readLine();}catch(IOException e){e.printStackTrace();}
while(st.hasMoreTokens()) line += " "+st.nextToken();
return line;
}
}
} | JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
const long long mod = 1000000007;
int A[100005];
char Num[100005];
long long Pow(long long a, long long b) {
long long ans = 1;
while (b) {
if (b & 1) ans = (ans * a) % mod;
a = (a * a) % mod;
b >>= 1;
}
return ans;
}
int main() {
int n, q;
scanf("%d%d", &n, &q);
scanf("%s", Num);
for (int i = 1; i <= n; i++) {
A[i] = Num[i - 1] - '0';
A[i] = A[i] + A[i - 1];
}
int l, r;
for (int i = 1; i <= q; i++) {
scanf("%d%d", &l, &r);
long long x = A[r] - A[l - 1];
long long y = r - l + 1 - x;
long long ans = (Pow(2, y) * (Pow(2, x) - 1)) % mod;
printf("%lld\n", ans);
}
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import java.io.*;
import java.util.*;
public class yuy {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n=sc.nextInt();
int q=sc.nextInt();
String h=sc.nextLine();
int[] pow2 = new int[1000000];
pow2[0] = 1;
for (int i = 1; i < pow2.length; i++) {
pow2[i] = (int)((1l*pow2[i-1]*2)%mod);
}
count [] a=new count[n]; int o=0; int z=0;
for(int i=0;i<n;i++) {
if(h.charAt(i)=='1')
o++;
else if(h.charAt(i)=='0')
z++;
a[i]=new count(o,z);
}
long ans=1;
// System.out.println(Arrays.toString(a));
for(int i=0;i<q;i++) {
int l=sc.nextInt()-1;
int r=sc.nextInt()-1;
long x=0;
long y=0;
l--;
ans=1;
if(l==-1) {
x= a[r].one; y=a[r].zero;
/*while(x>0) {long w=x;
if(x>60)
w=60;
ans=((long)Math.pow(2,w)*ans)%1000000009;
x=x-60;
}*/
ans=(pow2[(int)x]-1l)*pow2[(int)y]%mod;
}
else {
x= a[r].one-a[l].one; y=a[r].zero-a[l].zero;
ans=(pow2[(int)x]-1l)*pow2[(int)y]%mod;
}
out.println(ans%mod);
}
out.flush();
}
static int mod = (int)1e9 + 7;
static class count{
int one;
int zero;
count(int o,int z){
one=o;
zero=z;
}
public String toString() {
return one+" "+zero;
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
} | JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | //package que_b;
import java.io.*;
import java.util.*;
import java.math.*;
public class utkarsh {
InputStream is;
PrintWriter out;
long mod = (long) (1e9 + 7), inf = (long) (3e18);
void solve() {
int n = ni(), q = ni();
char[] s = ns(n);
int a[] = new int[n+1];
for(int i = 0; i < n; i++) {
a[i+1] = a[i] + (s[i] == '1' ? 1 : 0);
}
while(q-- > 0) {
int l = ni(), r = ni();
long one = a[r] - a[l-1];
long zero = (r - l + 1) - one;
if(one == 0) out.println(0);
else {
long x = mp(2, one) - 1;
long y = mp(2, zero) - 1;
long ans = (x + x * y) % mod;
out.println(ans);
}
}
}
long mp(long b, long e) {
long r = 1;
while(e > 0) {
if((e&1) == 1) r = (r * b) % mod;
b = (b * b) % mod;
e >>= 1;
}
return r;
}
//---------- I/O Template ----------
public static void main(String[] args) { new utkarsh().run(); }
void run() {
is = System.in;
out = new PrintWriter(System.out);
solve();
out.flush();
}
byte input[] = new byte[1024];
int len = 0, ptr = 0;
int readByte() {
if(ptr >= len) { ptr = 0;
try { len = is.read(input); }
catch(IOException e) { throw new InputMismatchException(); }
if(len <= 0) { return -1; }
} return input[ptr++];
}
boolean isSpaceChar(int c) { return !( c >= 33 && c <= 126 ); }
int skip() {
int b = readByte();
while(b != -1 && isSpaceChar(b)) { b = readByte(); }
return b;
}
char nc() { return (char)skip(); }
String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while(!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); }
return sb.toString();
}
String nLine() {
int b = skip();
StringBuilder sb = new StringBuilder();
while( !(isSpaceChar(b) && b != ' ') ) { sb.appendCodePoint(b); b = readByte(); }
return sb.toString();
}
int ni() {
int n = 0, b = readByte();
boolean minus = false;
while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); }
if(b == '-') { minus = true; b = readByte(); }
if(b == -1) { return -1; } //no input
while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); }
return minus ? -n : n;
}
long nl() {
long n = 0L; int b = readByte();
boolean minus = false;
while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); }
if(b == '-') { minus = true; b = readByte(); }
while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); }
return minus ? -n : n;
}
double nd() { return Double.parseDouble(ns()); }
float nf() { return Float.parseFloat(ns()); }
int[] na(int n) {
int a[] = new int[n];
for(int i = 0; i < n; i++) { a[i] = ni(); }
return a;
}
char[] ns(int n) {
char c[] = new char[n];
int i, b = skip();
for(i = 0; i < n; i++) {
if(isSpaceChar(b)) { break; }
c[i] = (char)b; b = readByte();
} return i == n ? c : Arrays.copyOf(c,i);
}
} | JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
const int N = 100100;
int n, q, cum[N], mod = 1e9 + 7;
char a[N];
string s;
vector<long long> v;
int main() {
scanf("%d%d%s", &n, &q, &a);
s += '#';
s += a;
int p = 1;
for (int i = 0; i <= 100000; i++) {
if (i == 0)
v.push_back(p);
else
v.push_back((v[i - 1] + p) % mod);
p = (p * 2) % mod;
}
for (int i = 1; i <= n; i++)
if (s[i] == '0')
cum[i] = 0;
else
cum[i] = 1;
for (int i = 1; i <= n; i++) cum[i] += cum[i - 1];
while (q--) {
int l, r;
scanf("%d%d", &l, &r);
int ones = cum[r] - cum[l - 1];
int zeros = (r - l + 1) - ones;
if (ones == 0) {
printf("0\n");
continue;
}
long long ans = v[ones - 1];
if (zeros != 0) {
ans += (v[zeros + ones - 1] - v[ones - 1] + mod) % mod;
ans = (ans - v[zeros - 1] + mod) % mod;
}
printf("%d\n", ans);
}
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | //https://www.hackerearth.com/submission/5284067/
import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class Main {
public static int n, m;
public static ArrayList<Integer>[] adj, idx;
public static ArrayList<Long> num[];
public static int chainNo, ptr;
public static int[] chainHead, chainSize, chainIdx, posInBase, subtree;
public static long[] baseArray, segtree;
public static int[] depth, parent;
public static int[][] P;
public static int rev[];
public static int LOGMAXN;
public static int MOD=(int)(1e9+7);
public static void main(String args[]) {
new Thread(null, new Runnable() {
public void run() {
try {
solve();
} catch (Exception e) {
e.printStackTrace();
}
}
}, "1", 1 << 26).start();
}
@SuppressWarnings("unchecked")
public static void solve() {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n=in.nextInt();
int q=in.nextInt();
int a[]=new int[n];
String st=in.readString();
for(int i=0;i<n;i++) {
a[i]=st.charAt(i)-'0';
}
int pre[]=new int[n+1];
for(int i=1;i<=n;i++) {
pre[i]=pre[i-1]+a[i-1];
}
long pow[]=new long[n+1];
pow[0]=1;
for(int i=1;i<=n;i++){
pow[i]=pow[i-1]*2;
pow[i]%=MOD;
}
for(int i=0;i<q;i++){
int l=in.nextInt();
int r=in.nextInt();
int length= r-l+1;
int cnt= pre[r]-pre[l-1];
if(cnt==0){
out.println("0");
continue;
}
long sum = (pow[cnt]-1+MOD)%MOD;
int rem= length - cnt;
if(rem>0){
sum= sum+((sum*(pow[rem]-1+MOD)%MOD)%MOD);
sum%=MOD;
}
out.println(sum);
}
out.close();
}
public static int KMPSearch(String pat, String txt)
{
int M = pat.length();
int N = txt.length();
// create lps[] that will hold the longest
// prefix suffix values for pattern
int lps[] = new int[M];
int j = 0; // index for pat[]
// Preprocess the pattern (calculate lps[]
// array)
computeLPSArray(pat, M, lps);
int i = 0; // index for txt[]
while (i < N) {
if (pat.charAt(j) == txt.charAt(i)) {
j++;
i++;
}
if (j == M) {
return (i - j);
//j = lps[j - 1];
}
// mismatch after j matches
else if (i < N && pat.charAt(j) != txt.charAt(i)) {
// Do not match lps[0..lps[j-1]] characters,
// they will match anyway
if (j != 0)
j = lps[j - 1];
else
i = i + 1;
}
}
return -1;
}
public static void computeLPSArray(String pat, int M, int lps[])
{
// length of the previous longest prefix suffix
int len = 0;
int i = 1;
lps[0] = 0; // lps[0] is always 0
// the loop calculates lps[i] for i = 1 to M-1
while (i < M) {
if (pat.charAt(i) == pat.charAt(len)) {
len++;
lps[i] = len;
i++;
}
else // (pat[i] != pat[len])
{
// This is tricky. Consider the example.
// AAACAAAA and i = 7. The idea is similar
// to search step.
if (len != 0) {
len = lps[len - 1];
// Also, note that we do not increment
// i here
}
else // if (len == 0)
{
lps[i] = len;
i++;
}
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
} | JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
long long me(long long a, long long b) {
if (b == 0) return 1;
if (b % 2 == 0) return me((a * a) % 1000000007, b / 2);
if (b % 2 == 1) return (a * me((a * a) % 1000000007, b / 2)) % 1000000007;
}
void solve() {
long long n, q;
cin >> n >> q;
string s;
cin >> s;
long long a[n + 1];
a[0] = 0;
for (long long int i = 0; i < n; i++) {
a[i + 1] = a[i];
if (s[i] == '1') a[i + 1]++;
}
while (q--) {
long long a1, b1;
cin >> a1 >> b1;
long long x = a[b1] - a[a1 - 1];
if (x == 0) {
cout << 0 << '\n';
continue;
}
long long an;
long long y = b1 - a1 + 1 - x;
an = (me(2, x) - 1 + 1000000007) % 1000000007;
an = (an + (an * (me(2, y) - 1 + 1000000007) % 1000000007) % 1000000007) %
1000000007;
cout << an << '\n';
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
long long TESTS = 1;
while (TESTS--) {
solve();
}
return 0;
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* #
* @author pttrung
*/
public class C_Round_520_Div2 {
public static long MOD = 1000000007;
static long[][][]dp;
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
// "output.txt")));
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int n = in.nextInt();
int q = in.nextInt();
String line = in.nextLine();
int[]count = new int[n];
for(int i = 0; i < n; i++){
if(line.charAt(i) == '1'){
count[i]++;
}
if(i > 0){
count[i] += count[i - 1];
}
}
for(int i = 0; i < q;i++){
int l = in.nextInt() - 1;
int r = in.nextInt() - 1;
int one = count[r] - (l > 0 ? count[l -1] : 0);
int zero = r - l + 1 - one;
long v = (pow(2, one, MOD) - 1 + MOD) % MOD;
long other = pow(2, zero, MOD);
v *= other;
v %= MOD;
out.println(v);
}
out.close();
}
static long cal(int index, int last, int n, int left){
if(index == n ){
return left == 0 ? 1 : 0;
}
if(left < 0){
return 0;
}
if(dp[last][index][left] != -1){
return dp[last][index][left];
}
long result = 0;
for(int i = 0; i < 4; i++){
result += cal(index + 1, i, n, left - count(last, i));
result %= MOD;
}
return dp[last][index][left] = result;
}
static int count(int last, int cur){
if(last == cur){
return 0;
}
if(last == 0 && cur != 0){
return 1;
}
if(last == 1 ){
if(cur == 2){
return 2;
}
return 0;
}
if(last == 2){
if(cur == 1){
return 2;
}
return 0;
}
return 1;
}
public static boolean div(int need, String v) {
int cur = 0;
for (int i = 0; i < v.length(); i++) {
cur += v.charAt(i) - '0';
if (cur == need) {
cur = 0;
} else if (cur > need) {
return false;
}
}
return true;
}
public static int[] KMP(String val) {
int i = 0;
int j = -1;
int[] result = new int[val.length() + 1];
result[0] = -1;
while (i < val.length()) {
while (j >= 0 && val.charAt(j) != val.charAt(i)) {
j = result[j];
}
j++;
i++;
result[i] = j;
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
public static int digit(long n) {
int result = 0;
while (n > 0) {
n /= 10;
result++;
}
return result;
}
public static double dist(long a, long b, long x, long y) {
double val = (b - a) * (b - a) + (x - y) * (x - y);
val = Math.sqrt(val);
double other = x * x + a * a;
other = Math.sqrt(other);
return val + other;
}
public static class Point implements Comparable<Point> {
int x, y;
public Point(int start, int end) {
this.x = start;
this.y = end;
}
@Override
public int hashCode() {
int hash = 5;
hash = 47 * hash + this.x;
hash = 47 * hash + this.y;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Point other = (Point) obj;
if (this.x != other.x) {
return false;
}
if (this.y != other.y) {
return false;
}
return true;
}
@Override
public int compareTo(Point o) {
return Integer.compare(x, o.x);
}
}
public static class FT {
long[] data;
FT(int n) {
data = new long[n];
}
public void update(int index, long value) {
while (index < data.length) {
data[index] += value;
index += (index & (-index));
}
}
public long get(int index) {
long result = 0;
while (index > 0) {
result += data[index];
index -= (index & (-index));
}
return result;
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static long pow(long a, long b, long MOD) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2, MOD);
if (b % 2 == 0) {
return val * val % MOD;
} else {
return val * (val * a % MOD) % MOD;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
// System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
} | JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import sys
input = sys.stdin.readline
n, q = map(int, input().split())
MOD = 10**9+7
l = list(input())
acc = [0]
for li in l:
acc.append(acc[-1]+(1 if li=='1' else 0))
for _ in range(q):
l, r = map(int, input().split())
a = acc[r]-acc[l-1]
b = r-l+1-a
print(pow(2, b, MOD)*(pow(2, a, MOD)-1)%MOD) | PYTHON3 |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #------------------------template--------------------------#
import os
import sys
# from math import *
from collections import *
# from fractions import *
# from heapq import*
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcdefghijklmnopqrstuvwxyz'
M = 10**9 + 7
EPS = 1e-6
def Ceil(a,b): return a//b+int(a%b>0)
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
# vsInput()
for _ in range(1):
n,q = value()
a = [int(i) for i in input()]
pre = [0]*(n+1)
for i in range(n): pre[i+1] += pre[i] + a[i]
for i in range(q):
l,r = value()
ones = pre[r] - pre[l-1]
tot = r - l + 1
# den = pow(2,ones-1,M)
num = (pow(2,tot-ones,M) * (pow(2,ones,M) - 1 + M)%M )%M
# ans = (num * pow(den,M-2,M))%M
print(num)
| PYTHON3 |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | n, q = map(int, input().split())
s = input()
c0 = [0]
for i in s:
c0.append(c0[-1] + (i == '0'))
M = 10 ** 9 + 7
ans = []
for i in range(q):
l, r = map(int, input().split())
z = c0[r] - c0[l - 1]
on = (r - l + 1) - z
ans.append((pow(2, on, M) - 1) * pow(2, z, M) % M)
print('\n'.join(list(map(str, ans)))) | PYTHON3 |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
int bp(int x, int n) {
int res = 1;
while (n) {
if (n & 1) res = (long long)res * x % mod;
x = (long long)x * x % mod;
n >>= 1;
}
return res;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, q;
cin >> n >> q;
string s;
cin >> s;
vector<int> px(n + 1);
px[0] = 0;
for (int i = 1; i <= n; ++i) {
px[i] = px[i - 1];
if (s[i - 1] == '1') ++px[i];
}
while (q--) {
int l, r;
cin >> l >> r;
int k = px[r] - px[l - 1];
int a = bp(2, k) - 1;
if (a == -1) a = mod - 1;
k = r - l + 1 - k;
int b = bp(2, k);
int s = (long long)a * b % mod;
cout << s << endl;
}
return 0;
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import java.util.*;
import java.io.*;
import java.math.BigInteger;
import java.util.regex.*;
public class Codeforces{
static class MyScanner{
BufferedReader br;
StringTokenizer st;
MyScanner(FileReader fileReader){
br = new BufferedReader(fileReader);
}
MyScanner(){
br = new BufferedReader(new InputStreamReader(System.in));
}
String nn(){
while(st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}catch(IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
String nextLine(){
String s = "";
try{
s = br.readLine();
}catch(IOException e){
e.printStackTrace();
}
return s;
}
int ni(){
return Integer.parseInt(nn());
}
long nl(){
return Long.parseLong(nn());
}
double nd(){
return Double.parseDouble(nn());
}
}
private static PrintWriter out;
public static void main(String[] args) throws FileNotFoundException{
// Input from file
// File inputFile = new File("JavaFile.txt");
// File outputFile = new File("JavaOutputFile.txt");
// FileReader fileReader = new FileReader(inputFile);
// Here it ends
MyScanner sc = new MyScanner();
// MyScanner sc = new MyScanner(fileReader);
out = new PrintWriter(new BufferedOutputStream(System.out)); // Output to console
// out = new PrintWriter(new PrintStream(outputFile)); // Output to file
int n = sc.ni(), q = sc.ni();
char[] ar = sc.nn().toCharArray();
int[] zero = new int[n + 1];
int[] one = new int[n + 1];
for(int i = 0; i < n; i++){
if(ar[i] == '0') zero[i] = 1;
else one[i] = 1;
}
for(int i = 1; i < n; i++){
one[i] += one[i - 1];
zero[i] += zero[i - 1];
}
final long MOD = 1_000_000_007;
long power[] = new long[n + 1];
power[0] = 1;
for(int i = 1; i <= n; i++) power[i] = (2 * power[i - 1]) % MOD;
while(q-- > 0){
int x = sc.ni() - 1, y = sc.ni() - 1;
int curOne = one[y] - (x - 1 >= 0? one[x - 1]: 0);
int curZero = zero[y] - (x - 1 >= 0? zero[x - 1]: 0);
// System.out.println(curOne + " " + curZero);
long one1 = ((power[curOne] - 1) % MOD + MOD) % MOD;
long two = one1 * (((power[curZero] - 1) % MOD + MOD) % MOD) % MOD;
long ans = (one1 + two) % MOD;
out.println(ans);
}
out.close();
}
} | JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | /* In_The_Name_Of_Allah_The_Merciful */
import java.util.*;
import java.io.*;
public class Main
{
PrintWriter out;
FastReader sc;
long[] m1= {(long)(1e9+7),998244353};
long mod=m1[0];
long maxlong=Long.MAX_VALUE;
long minlong=Long.MIN_VALUE;
StringBuilder sb;
/******************************************************************************************
*****************************************************************************************/
public void sol() {
int n=ni(),q=ni();
char[] s=rl();
long pow[] =new long[100005];
pow[0]=1;
long h=1;
for(int i=1;i<100005;i++) {
h=(2*h)%mod;
pow[i]=h;
}
int[] a=new int[n+1],b=new int[n+1];
for(int i=1;i<=n;i++) {
if(s[i-1]=='1') {
a[i]=a[i-1]+1;
b[i]=b[i-1];
}else {
b[i]=b[i-1]+1;
a[i]=a[i-1];
}
}while(q-->0) {
int l=ni(),r=ni();
int x=a[r]-a[l-1],y=b[r]-b[l-1];
long p=(pow[x]-1+mod)%mod;
long u=(p*(pow[y]-1+mod)%mod)%mod;
pl((u+p)%mod);
}
}
public static void main(String[] args)
{
Main g=new Main();
g.out=new PrintWriter(System.out);
g.sc=new FastReader();
int t=1;
// t=g.ni();
while(t-->0)
g.sol();
g.out.flush();
}
/****************************************************************************************
*****************************************************************************************/
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
} public int ni(){
return sc.nextInt();
}public long nl(){
return sc.nextLong();
}public double nd(){
return sc.nextDouble();
}public char[] rl(){
return sc.nextLine().toCharArray();
}public String rl1(){
return sc.nextLine();
}
public void pl(Object s){
out.println(s);
}
public void pr(Object s){
out.print(s);
}public String next(){
return sc.next();
}public long abs(long x){
return Math.abs(x);
}
public int abs(int x){
return Math.abs(x);
}
public double abs(double x){
return Math.abs(x);
}public long min(long x,long y){
return (long)Math.min(x,y);
}
public int min(int x,int y){
return (int)Math.min(x,y);
}
public double min(double x,double y){
return Math.min(x,y);
}public long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}public long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
void sort1(int[] a) {
ArrayList<Integer> l = new ArrayList<>();
for (int i : a) {
l.add(i);
}
Collections.sort(l,Collections.reverseOrder());
for (int i = 0; i < a.length; i++) {
a[i] = l.get(i);
}
}
void sort(int[] a) {
ArrayList<Integer> l = new ArrayList<>();
for (int i : a) {
l.add(i);
}
Collections.sort(l);
for (int i = 0; i < a.length; i++) {
a[i] = l.get(i);
}
}void sort(char[] a) {
ArrayList<Character> l = new ArrayList<>();
for (char i : a) {
l.add(i);
}
Collections.sort(l);
for (int i = 0; i < a.length; i++) {
a[i] = l.get(i);
}
}void sort1(char[] a) {
ArrayList<Character> l = new ArrayList<>();
for (char i : a) {
l.add(i);
}
Collections.sort(l,Collections.reverseOrder());
for (int i = 0; i < a.length; i++) {
a[i] = l.get(i);
}
}
void sort(long[] a) {
ArrayList<Long> l = new ArrayList<>();
for (long i : a) {
l.add(i);
}
Collections.sort(l);
for (int i = 0; i < a.length; i++) {
a[i] = l.get(i);
}
}void sort1(long[] a) {
ArrayList<Long> l = new ArrayList<>();
for (long i : a) {
l.add(i);
}
Collections.sort(l,Collections.reverseOrder());
for (int i = 0; i < a.length; i++) {
a[i] = l.get(i);
}
}
void sort(double[] a) {
ArrayList<Double> l = new ArrayList<>();
for (double i : a) {
l.add(i);
}
Collections.sort(l);
for (int i = 0; i < a.length; i++) {
a[i] = l.get(i);
}
}long pow(long a,long b){
if(b==0){
return 1;
}long p=pow(a,b/2);
if(b%2==0) return mMultiplication(p,p)%mod;
else return (mMultiplication(mMultiplication(p,p),a))%mod;
}
int swap(int a,int b){
return a;
}long swap(long a,long b){
return a;
}double swap(double a,double b){
return a;
}
boolean isPowerOfTwo (int x)
{
return x!=0 && ((x&(x-1)) == 0);
}boolean isPowerOfTwo (long x)
{
return x!=0 && ((x&(x-1)) == 0);
}public long max(long x,long y){
return (long)Math.max(x,y);
}
public int max(int x,int y){
return (int)Math.max(x,y);
}
public double max(double x,double y){
return Math.max(x,y);
}long sqrt(long x){
return (long)Math.sqrt(x);
}int sqrt(int x){
return (int)Math.sqrt(x);
}void input(int[] ar,int n){
for(int i=0;i<n;i++)ar[i]=ni();
}void input(long[] ar,int n){
for(int i=0;i<n;i++)ar[i]=nl();
}void fill(int[] ar,int k){
Arrays.fill(ar,k);
}void yes(){
pl("YES");
}void no(){
pl("NO");
}
long c2(long n) {
return (n*(n-1))/2;
}
long[] sieve(int n)
{
long[] k=new long[n+1];
boolean[] pr=new boolean[n+1];
for(int i=1;i<=n;i++){
k[i]=i;
pr[i]=true;
}for(int i=2;i<=n;i++){
if(pr[i]){
for(int j=i+i;j<=n;j+=i){
pr[j]=false;
if(k[j]==j){
k[j]=i;
}
}
}
}return k;
}
int strSmall(int[] arr, int target)
{
int start = 0, end = arr.length-1;
int ans = -1;
while (start <= end) {
int mid = (start + end) / 2;
if (arr[mid] >= target) {
end = mid - 1;
}
else {
ans = mid;
start = mid + 1;
}
}
return ans;
} int strSmall(ArrayList<Integer> arr, int target)
{
int start = 0, end = arr.size()-1;
int ans = -1;
while (start <= end) {
int mid = (start + end) / 2;
if (arr.get(mid) > target) {
start = mid + 1;
ans=start;
}
else {
end = mid - 1;
}
}
return ans;
}long mMultiplication(long a,long b)
{
long res = 0;
a %= mod;
while (b > 0)
{
if ((b & 1) > 0)
{
res = (res + a) % mod;
}
a = (2 * a) % mod;
b >>= 1;
}
return res;
}long nCr(int n, int r ,long p)
{
if (n<r)
return 0;
if (r == 0)
return 1;
long[] fac = new long[n + 1];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = fac[i - 1] * i %p;
return (fac[n] * modInverse(fac[r], p)
% p * modInverse(fac[n - r], p)
% p)
% p;
}long power(long x, long y, long p)
{
long res = 1;
x = x % p;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}long modInverse(long n, long p)
{
return power(n, p - 2, p);
}
int[][] floydWarshall(int graph[][],int INF,int V)
{
int dist[][] = new int[V][V];
int i, j, k;
for (i = 0; i < V; i++)
for (j = 0; j < V; j++)
dist[i][j] = graph[i][j];
for (k = 0; k < V; k++)
{
for (i = 0; i < V; i++)
{
for (j = 0; j < V; j++)
{
if (dist[i][k] + dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}return dist;
}
class minque {
Deque<Long> q;
minque(){
q=new ArrayDeque<Long>();
}public void add(long p){
while(!q.isEmpty()&&q.peekLast()>p)q.pollLast();
q.addLast(p);
}public void remove(long p) {
if(!q.isEmpty()&&q.getFirst()==p)q.removeFirst();
}public long min() {
return q.getFirst();
}
}
int find(subset[] subsets, int i)
{
if (subsets[i].parent != i)
subsets[i].parent
= find(subsets, subsets[i].parent);
return subsets[i].parent;
}void Union(subset[] subsets, int x, int y)
{
int xroot = find(subsets, x);
int yroot = find(subsets, y);
if (subsets[xroot].rank < subsets[yroot].rank) {
subsets[xroot].parent = yroot;
}
else if (subsets[yroot].rank < subsets[xroot].rank) {
subsets[yroot].parent = xroot;
}
else {
subsets[xroot].parent = yroot;
subsets[yroot].rank++;
}
}class subset
{
int parent;
int rank;
}class pair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<pair<U, V>>
{
public U x;
public V y;
public pair(U x, V y) {
this.x = x;
this.y = y;
}
public int compareTo(pair<U, V> other) {
int i = x.compareTo(other.x);
if (i != 0) return i;
return y.compareTo(other.y);
}
public String toString() {
return x.toString() + " " + y.toString();
}
@SuppressWarnings("unchecked")
public boolean equals(Object obj){
if (this.getClass() != obj.getClass()) return false;
pair<U, V> other = (pair<U, V>) obj;
return x.equals(other.x) && y.equals(other.y);
}
public int hashCode(){
return 31 * x.hashCode() + y.hashCode();
}
}
} | JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import java.util.*;
import java.awt.geom.*;
import java.io.*;
import java.math.*;
public class Main
{
public static void main(String[] args) throws Exception
{
long startTime = System.nanoTime();
int n = in.nextInt();
int q = in.nextInt();
int [] zeroes = new int [n];
int [] ones = new int [n];
long MOD = 1_000_000_000 + 7;
char [] data = in.next().toCharArray();
if(data[0]=='0') zeroes[0] = 1;
if(data[0]=='1') ones[0] = 1;
for(int i=1;i<data.length;i++){
if(data[i]=='0'){
zeroes[i] = zeroes[i-1] + 1;
ones[i] = ones[i-1] ;
}
else{
zeroes[i] = zeroes[i-1] ;
ones[i] = ones[i-1] + 1;
}
}
for(int i=0;i<q;i++){
int l = in.nextInt();
int r = in.nextInt();
long z = (zeroes[r-1]-zeroes[l-1]) + (data[l-1]=='0' ? 1 : 0);
long o = (ones[r-1]-ones[l-1]) + (data[l-1]=='1' ? 1 : 0);
long temp = mod_pow(2L,z,MOD);
temp%=MOD;
long ans = (mod_pow(2L,o,MOD) - 1)%MOD * temp;
ans%=MOD;
out.println(ans);
}
long endTime = System.nanoTime();
err.println("Execution Time : +" + (endTime-startTime)/1000000 + " ms");
exit(0);
}
static long mod_pow(long base,long exponent,long mod)
{
if(mod==1) return 0;
long result=1;
base%=mod;
while(exponent>0)
{
if(exponent%2==1)
{
result=(result*base)%mod;
}
exponent=(exponent>>1);
base=(base*base)%mod;
}
return result;
}
static class InputReader
{
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble(){
return Double.parseDouble(next());
}
}
static void exit(int a)
{
out.close();
err.close();
System.exit(a);
}
static InputStream inputStream = System.in;
static OutputStream outputStream = System.out;
static OutputStream errStream = System.err;
static InputReader in = new InputReader(inputStream);
static PrintWriter out = new PrintWriter(outputStream);
static PrintWriter err = new PrintWriter(errStream);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
}
| JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
int n, q;
string s;
int ones[100005], zeros[100005];
int dt[100005];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> n >> q >> s;
for (int i = 0; i < n; ++i) {
if (i > 0) {
zeros[i + 1] += zeros[i];
ones[i + 1] += ones[i];
}
if (s[i] == '0') {
++zeros[i + 1];
} else {
++ones[i + 1];
}
}
long long x = 1;
for (int i = 0; i <= 100005; ++i) {
dt[i] = x;
x *= 2;
x %= 1000000007;
}
for (int i = 0; i < q; ++i) {
int l, r;
cin >> l >> r;
int d = r - l + 1;
int res;
if (zeros[r] - zeros[l - 1] > 0) {
res = dt[d] - dt[zeros[r] - zeros[l - 1]];
} else {
res = dt[ones[r] - ones[l - 1]] - 1;
}
while (res < 0) {
res += 1000000007;
}
cout << res % 1000000007 << "\n";
}
return 0;
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 5;
const int mod = 1e9 + 7;
char s[maxn];
int siz[maxn];
long long sum[maxn];
int main() {
int i, j, k, n, m, q, l, r, x, y;
long long num;
scanf("%d%d", &n, &q);
sum[0] = 0;
num = 1;
for (i = 1; i <= n; i++) {
sum[i] = (sum[i - 1] + num) % mod;
num = 1LL * 2 * num % mod;
}
scanf("%s", s);
siz[0] = 0;
for (i = 0; i < n; i++) {
siz[i + 1] = siz[i];
if (s[i] == '1') siz[i + 1]++;
}
while (q--) {
scanf("%d%d", &l, &r);
x = siz[r] - siz[l - 1];
x = r - l + 1 - x;
printf("%I64d\n", (sum[r - l + 1] - sum[x] + mod) % mod);
}
return 0;
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
const int SIZEN = 100010;
const long long mod = 1000000007;
int n, q;
int a[SIZEN] = {0};
long long qpow(long long x, long long len) {
long long ret = 1;
for (; len; len >>= 1) {
if (len & 1) ret = ret * x % mod;
x = x * x % mod;
}
return ret;
}
int main() {
scanf("%d%d", &n, &q);
for (int i = 1; i <= n; i++) scanf("%1d", &a[i]), a[i] += a[i - 1];
for (int i = 1; i <= q; i++) {
int l, r;
scanf("%d%d", &l, &r);
long long ans = qpow(2, a[r] - a[l - 1]) - 1;
ans += (qpow(2, r - l + 1 - a[r] + a[l - 1]) - 1) *
(qpow(2, a[r] - a[l - 1]) - 1) % mod;
ans = (ans % mod + mod) % mod;
printf("%lld\n", ans);
}
return 0;
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import java.util.*;
import java.io.*;
public class algo_603
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n=Integer.parseInt(st.nextToken());
int q=Integer.parseInt(st.nextToken());
BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out,"UTF8"));
String s=(new StringTokenizer(br.readLine())).nextToken();
int arr[]=new int[n];
arr[0]=s.charAt(0)-'0';
for(int i=1;i<n;i++)
arr[i]=arr[i-1]+s.charAt(i)-'0';
long mod=1000000007;
long pow[]=new long[n+1];
long num=1;
pow[0]=1;
for(int i=0;i<=n;i++)
{
pow[i]=num;
num=num*2;
num=num%mod;
}
while(q-->0)
{
st = new StringTokenizer(br.readLine());
int l=Integer.parseInt(st.nextToken())-1;
int r=Integer.parseInt(st.nextToken())-1;
int a1=arr[r];
if(l>0)
a1=a1-arr[l-1];
int a2=(r-l+1)-a1;
long ans=pow[a1+a2]-pow[a2];
if(ans<0)
ans=ans+mod;
log.write(ans+"\n");
}
log.flush();
}
} | JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
int32_t main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
long long n, q;
long long mod = 1e9 + 7;
cin >> n >> q;
vector<long long> p(n + 1), dg(n + 1, 1);
for (long long i = 0; i < n; i++) dg[i + 1] = dg[i] * 2 % mod;
for (long long i = 0; i < n; i++) {
char x;
cin >> x;
p[i + 1] += p[i] + (x == '1');
}
long long l, r;
for (long long i = 0; i < q; i++) {
cin >> l >> r;
long long s = p[r] - p[l - 1];
long long len = r - l + 1;
long long ans = dg[s] - 1;
if (len != s) ans = (dg[s] - 1) * dg[len - s];
ans %= mod;
cout << ans << '\n';
}
return 0;
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 6;
string s;
long long pp[N];
int pref[N];
const int mod = 1e9 + 7;
long long int fpower(long long int x, long long int y) {
long long int res = 1;
while (y > 0) {
if (y & 1) res = (res * x) % mod;
y = y >> 1;
x = (x * x) % mod;
}
return res;
}
int main() {
pp[0] = 1;
for (int i = 1; i < N; i++) {
pp[i] = (pp[i - 1] + pp[i - 1]) % mod;
}
int n, q;
cin >> n >> q;
string s;
cin >> s;
for (int i = 0; i < n; i++) {
pref[i + 1] = pref[i] + (s[i] == '1');
}
while (q--) {
int l, r;
scanf("%d%d", &l, &r);
int ones = pref[r] - pref[l - 1];
long long int ans = (pp[ones] - 1 + mod) % mod;
long long int zer = r - l + 1 - ones;
if (zer > 0) ans = (ans + (ans * (pp[zer] - 1)) % mod) % mod;
printf("%lld\n", ans);
}
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import java.util.*;
import java.io.*;
//import javafx.util.Pair;
public class Solution implements Runnable
{
class Pair implements Comparable <Pair>
{
int x;
long y;
Pair(int x,long y)
{
this.x=x;
this.y=y;
}
public int compareTo(Pair p)
{
return Long.compare(y,p.y);
}
}
public static void main(String[] args)
{
new Thread(null, new Solution(), "rev", 1 << 29).start();
}
public void run()
{
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(1,in,out);
out.close();
}
class Task
{
int m=(int)1E9+7;
long pow(long x,long y)
{
long l=1;
while(y>0)
{
if(y%2==1)
{
l*=x;
l%=m;
}
y>>=1;
x*=x;
x%=m;
}
return l;
}
void solve(int testNumber, InputReader in, PrintWriter out)
{
int n=in.nextInt();
int q=in.nextInt();
String s=in.nextString();
int []a=new int[n];
for(int i=0;i<n;i++)
a[i]=s.charAt(i)-48;
for(int i=1;i<n;i++)
a[i]+=a[i-1];
int x,y,sum,l;
long ans;
while(q-->0)
{
x=in.nextInt()-1;
y=in.nextInt()-1;
l=y-x+1;
sum=a[y];
if(x>0)
sum-=a[x-1];
ans=((pow(2,sum)-1)%m+m)%m;
ans=(ans*pow(2,l-sum))%m;
out.println(ans);
}
}
}
}
class InputReader
{
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int snext()
{
if(snumChars==-1)
throw new InputMismatchException();
if(curChar>=snumChars)
{
curChar=0;
try
{
snumChars = stream.read(buf);
}
catch(IOException e)
{
throw new InputMismatchException();
}
if(snumChars<=0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = snext();
while(isSpaceChar(c))
c=snext();
int sgn=1;
if(c=='-')
{
sgn = -1;
c = snext();
}
int res=0;
do
{
if(c<'0' || c>'9')
throw new InputMismatchException();
res*=10;
res+=c-'0';
c=snext();
}while(!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = snext();
while(isSpaceChar(c))
c=snext();
int sgn=1;
if(c=='-')
{
sgn=-1;
c=snext();
}
long res=0;
do{
if (c<'0' || c>'9')
throw new InputMismatchException();
res*=10;
res+=c-'0';
c=snext();
}while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int a[]=new int[n];
for(int i=0; i<n; i++)
a[i]=nextInt();
return a;
}
public String nextString()
{
int c=snext();
while(isSpaceChar(c))
c=snext();
StringBuilder res=new StringBuilder();
do{
res.appendCodePoint(c);
c = snext();
}while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if(filter != null)
return filter.isSpaceChar(c);
return c==' ' || c=='\n' || c=='\r' || c=='\t' || c==-1;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
} | JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
/**
* Created by Katushka on 31.01.2020.
*/
public class BahnMi {
private static long fastPow2(int y) {
if (y == 0) {
return 1;
}
long p = fastPow2(y / 2) % 1000000007;
p = p * p % 1000000007;
if (y % 2 == 1) {
p = p * 2 % 1000000007;
}
return p;
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
int n = in.nextInt();
int q = in.nextInt();
String s = in.nextString();
int[] zeroes = new int[s.length()];
int cur = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '0') {
cur += 1;
}
zeroes[i] = cur;
}
for (int i = 0; i < q; i++) {
int l = in.nextInt();
int r = in.nextInt();
int n0;
if (l == 1) {
n0 = zeroes[r - 1];
} else {
n0 = zeroes[r - 1] - zeroes[l - 2];
}
long p1 = fastPow2(r - l + 1) % 1000000007;
long p2 = fastPow2(n0) % 1000000007;
if (p1 >= p2) {
System.out.println(p1 - p2);
} else{
System.out.println(p1 + 1000000007 - p2);
}
}
}
private static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
final String str = reader.readLine();
tokenizer = new StringTokenizer(str);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextString() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public char nextChar() {
return next().charAt(0);
}
}
}
| JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 |
import java.io.*;
import java.util.*;
import java.math.BigInteger;
import java.lang.*;
public class Main {
static class sort implements Comparator<List<Integer>>
{
public int compare(List<Integer> a,List<Integer> b)
{
return (a.size() - b.size());
}
}
/*static class sort implements Comparator<int[]>
{
public int compare(int[] a,int[] b)
{
return -b[0]+a[0];
}
}*/
static class sort1 implements Comparator<long[]>
{
public int compare(long[] a,long[] b)
{
long c = -(a[0]-a[1]) + (b[0]-b[1]);
if(c==0l) return 0;
if(c>0l) return 1;
return -1;
}
}
static class sort11 implements Comparator<double[]>
{
public int compare(double[] a,double[] b)
{
//if(a[0] == b[0]) return a[1]-b[1];
if(a[1] < b[1]) return -1;
else if(a[1] > b[1]) return 1;
return 0;
}
}
public static String[] F(BufferedReader bf) throws Exception
{
return (bf.readLine().split(" "));
}
public static void pr(PrintWriter out,Object o)
{
out.println(o.toString());//out.flush();
}
public static void prW(PrintWriter out,Object o)
{
out.print(o.toString());//out.flush();
}
public static int intIn(String st)
{
return Integer.parseInt(st);
}
public static void pr(Object o)
{
System.out.println(o.toString());
}
public static void prW(Object o)
{
System.out.print(o.toString());
}
public static int inInt(String s)
{
return Integer.parseInt(s);
}
public static long in(String s)
{
return Long.parseLong(s);
}
static int[] toIntArray(String[] m)
{
int[] p=new int[m.length];
for(int o=0;o<m.length;o++)
{
p[o]= inInt(m[o]);
}
return p;
}
static double[] toDArray(String[] m)
{
double[] p=new double[m.length];
for(int o=0;o<m.length;o++)
{
p[o]= Double.parseDouble(m[o]);
}
return p;
}
static long[] toLArray(String[] m)
{
long[] p=new long[m.length];
for(int o=0;o<m.length;o++)
{
p[o]= in(m[o]);
}
return p;
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static long pow(long x, long y, long p)
{
if(y == 0) return 1l;
long res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
if (x == 0)
return 0l; // In case x is divisible by p;
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1) != 0)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
static long __gcd(long n1, long n2)
{
if(n1==0l) return n2;
if(n2==0l) return n1;
if(n1==1l || n2==1l) return 1l;
// long gcd = 1;
if(n1 == n2) return n1;
if(n1>n2) return __gcd(n1%n2,n2);
return __gcd(n1,n2%n1);
}
public static void main (String[] args) throws Exception {
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);;;
//int[] map=new int[1000001];
int yy=1;//inInt(bf.readLine());
//Long[][][] dp = new Long[100001][101][2];
for(int w=0;w<yy;w++)
{
//String str = bf.readLine();
out.flush();
String[] xlp = bf.readLine().split(" ");
//String st = bf.readLine();
int n;//boolean bol=false;
int m;//long a,b,c;
// int l;
//int k;//pr(out,"vbc");
n=inInt(xlp[0]);m=inInt(xlp[1]);//int ta=inInt(xlp[2]);int tb=inInt(xlp[3]);k=inInt(xlp[4]);
char[] arr = bf.readLine().toCharArray();
int[] count = new int[n];
int s=0;
long[] sum = new long[n];
long mod = 1000000000+7l;
long r=1l;
sum[0]=1l;
for(int i=1;i<n;i++)
{
sum[i] = (((r%mod)*(2))%mod);
r = sum[i];
}
for(int i=1;i<n;i++)
{
sum[i] = ((sum[i-1]%mod)+ sum[i]%mod)%mod;
}
for(int i=0;i<n;i++)
{
if(arr[i]=='1') s++;
count[i]=s+1;
}
for(int i=0;i<m;i++)
{
int[] tem = toIntArray(F(bf));
long res;
tem[0]--;tem[1]--;
int x = count[tem[1]]-1;
if(tem[0] > 0) x -= count[tem[0]-1]-1;
// pr(out,x);
if(x == 0)
{
//res = sum[tem[1]-tem[0]];
pr(out,0);
continue;
}
int y = (tem[1]-tem[0]+1-x);
if(y == 0)
{
res = sum[tem[1]-tem[0]];
pr(out,res);
continue;
}
res = (sum[x-1]%mod + ((sum[x-1]%mod)*(sum[y-1]%mod))%mod)%mod;
pr(out,res);
}
}
out.close();
bf.close();//
}}
/*
10
6 4 3 9 5 2 1 10 8 7
Kickstart
String rp;
rp = "Case #"+(w+1)+": "+(n-ans)+" ";
static int[][] dir={{0,1},{1,0},{-1,0},{0,-1}};
static class SegmentTreeRMQ
{
int st[];
int minVal(int x, int y) {
return (x > y) ? x : y;
}
int getMid(int s, int e) {
return s + (e - s) / 2;
}
int RMQUtil(int ss, int se, int qs, int qe, int index)
{
if (qs <= ss && qe >= se)
return st[index];
// If segment of this node is outside the given range
if (se < qs || ss > qe)
return Integer.MIN_VALUE;
// If a part of this segment overlaps with the given range
int mid = getMid(ss, se);
return minVal(RMQUtil(ss, mid, qs, qe, 2 * index + 1),
RMQUtil(mid + 1, se, qs, qe, 2 * index + 2));
}
// Return minimum of elements in range from index qs (query
// start) to qe (query end). It mainly uses RMQUtil()
int RMQ(int n, int qs, int qe)
{
// Check for erroneous input values
return RMQUtil(0, n - 1, qs, qe, 0);
}
// A recursive function that constructs Segment Tree for
// array[ss..se]. si is index of current node in segment tree st
int constructSTUtil(int arr[], int ss, int se, int si)
{
// If there is one element in array, store it in current
// node of segment tree and return
if (ss == se) {
st[si] = arr[ss];
return arr[ss];
}
// If there are more than one elements, then recur for left and
// right subtrees and store the minimum of two values in this node
int mid = getMid(ss, se);
st[si] = minVal(constructSTUtil(arr, ss, mid, si * 2 + 1),
constructSTUtil(arr, mid + 1, se, si * 2 + 2));
return st[si];
}
void con(int arr[])
{
// Allocate memory for segment tree
//Height of segment tree
int n = (arr.length);
int x = (int) (Math.ceil(Math.log(n) / Math.log(2)));
//Maximum size of segment tree
int max_size = 2 * (int) Math.pow(2, x) - 1;
st = new int[max_size]; // allocate memory
// Fill the allocated memory st
constructSTUtil(arr, 0, n - 1, 0);
}
}
static class DSU {
int[] p;int[] sz;int op;int c;;
int[] last;
public void G(int n)
{
last=new int[n];
p=new int[n];
sz=new int[n];c=n;
op=n;
for(int h=0;h<n;h++)
{
sz[h]=1;p[h]=h;
last[h]=h;
}
}
public int find(int x)
{
int y=x;
while(x!=p[x]) x=p[x];
while(y!=p[y])
{
int tem=p[y];
p[y]=x;y=tem;
}
return p[y];
}
public void union(int a,int b)
{
int x,y;
x=find(a);y=find(b);
if(x==y) return;
if(sz[x]>sz[y])
{
p[y] = x;
sz[x]+=sz[y];
last[x]=Math.max(last[x],last[y]);
}
else
{
p[x]=y;sz[y]+=sz[x];
last[y]=Math.max(last[y],last[x]);
}
c--;
}}
static long pow(long x, long y, long p)
{
long res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
if (x == 0)
return 0l; // In case x is divisible by p;
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1) != 0)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static int gcd(int a, int b,int o)
{
if (b == 0)
return a;
return gcd(b, a % b,o);
}
Geometric median
public static double F(double[] x,double[] w)
{
double d1,d2;
double S=0.00;
for(double dp : w) S += dp;
int k = 0;
double sum = S - w[0]; // sum is the total weight of all `x[i] > x[k]`
while(sum > S/2)
{
++k;
sum -= w[k];
}
d1=x[k];
return d1;
k = w.length-1;
sum = S - w[k]; // sum is the total weight of all `x[i] > x[k]`
while(sum > S/2)
{
--k;
sum -= w[k];
}
d2=x[k];
return new double[]{d1,d2};
}
*/
| JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.*;
public class C {
private String readLine() {
StringBuilder sb = new StringBuilder();
int b = 0;
while (b != '\n' && b >= 0) {
try {
b = System.in.read();
} catch (IOException e) {
return null;
}
if (b != '\r' && b != '\n' && b >= 0) {
sb.append((char) b);
}
}
if (sb.length() == 0 && b < 0) {
return null;
}
return sb.toString().trim();
}
private int parseInt(String s) {
int result = 0;
int sign = (s.charAt(0) == '-') ? -1 : 1;
if (sign == -1) {
s = s.substring(1);
}
if (s.charAt(0) == '+') {
s = s.substring(1);
}
int i = 0, max = s.length();
if (max > 0) {
while (i < max) {
result *= 10;
result += s.charAt(i++) - 48;
}
}
return sign * result;
}
private void work() {
p2 = new long[100010];
p2[0] = 1;
for (int i = 1; i < p2.length; i++) {
p2[i] = (2 * p2[i - 1]) % MOD;
}
String[] spl = readLine().split("\\s+");
int n = parseInt(spl[0]);
int q = parseInt(spl[1]);
char[] s = readLine().trim().toCharArray();
int[] a = new int[n + 1];
for (int i = 1; i <= n; i++) {
a[i] = a[i - 1];
if (s[i - 1] == '1') a[i]++;
}
while (q-- > 0) {
spl = readLine().split("\\s+");
int l = parseInt(spl[0]);
int r = parseInt(spl[1]);
int ones = a[r] - a[l - 1];
int zeros = r - l + 1 - ones;
System.out.println(f(ones, zeros));
}
}
private static final long MOD = 1000000007;
private long[] p2;
private long f(int ones, int zeros) {
if (ones == 0) return 0;
return ((p2[ones] - 1) * p2[zeros]) % MOD;
}
public static void main(String[] args) {
new C().work();
}
}
| JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
const long long int mod = 1000000007;
long long int powers(long long int a, long long int b) {
long long int ans = 1;
a %= mod;
while (b > 0) {
if (b % 2 == 1) ans = ((ans % mod) * (a % mod)) % mod;
b /= 2;
a = ((a % mod) * (a % mod)) % mod;
}
return ans;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
int n, q, l, r;
cin >> n >> q;
long long int arr[n], one[n + 1], zero[n];
string second;
cin >> second;
for (int i = 0; i < n; i++) {
if (second[i] == '1')
arr[i] = 1;
else
arr[i] = 0;
}
one[0] = zero[0] = 0;
for (int i = 1; i <= n; i++) {
one[i] = one[i - 1] + arr[i - 1];
zero[i] = zero[i - 1];
if (!arr[i - 1]) zero[i]++;
}
while (q--) {
cin >> l >> r;
long long int ans = (powers(2, one[r] - one[l - 1]) - 1) % mod;
long long int zans = (powers(2, zero[r] - zero[l - 1]) - 1) % mod;
cout << (((zans + 1) % mod) * ans) % mod << endl;
}
return 0;
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
long long power(long long x, unsigned long long y) {
int res = 1;
x = x % 1000000007;
while (y > 0) {
if (y & 1) res = (res * x) % 1000000007;
y = y >> 1;
x = (x * x) % 1000000007;
}
return res;
}
int main() {
int n, q;
vector<int> one(100005, 0), zero(100005, 0);
string s;
cin >> n >> q;
cin >> s;
for (int i = 1; i <= n; i++) {
zero[i] = zero[i - 1];
one[i] = one[i - 1];
if (s[i - 1] == '0')
zero[i]++;
else
one[i]++;
}
int l, r;
while (q--) {
cin >> l >> r;
int z = zero[r] - zero[l - 1];
int o = one[r] - one[l - 1];
long long ans = power(2, o) - 1;
long long aa = power(2, z) - 1;
long long b = (aa % 1000000007 * ans % 1000000007) % 1000000007;
cout << (ans % 1000000007 + b % 1000000007) % 1000000007 << "\n";
}
return 0;
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
long long int max2 = 1000000007;
long long int power(long long int base, long long int exp) {
long long int ans = 1;
while (exp) {
if (exp % 2 == 1) {
ans *= base;
ans %= max2;
}
exp /= 2;
base *= base;
base %= max2;
}
return ans;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cerr.tie(NULL);
int tab;
auto geti = [&]() {
cin >> tab;
return tab;
};
;
long long int n, q;
cin >> n >> q;
string s;
cin >> s;
long long int onescount[n];
if (s[0] == '0') {
onescount[0] = 0;
} else {
onescount[0] = 1;
}
for (long long int i = 1; i < n; i++) {
if (s[i] == '0') {
onescount[i] = onescount[i - 1];
} else {
onescount[i] = onescount[i - 1] + 1;
}
}
while (q > 0) {
long long int l, r;
cin >> l >> r;
l--;
r--;
long long int one = onescount[r] - onescount[l];
long long int zero = 0;
if (s[l] == '1' && s[l] == '1') {
one++;
} else if (s[l] == '1' && s[r] == '0') {
one++;
}
zero = r - l + 1 - one;
long long int count = 0;
long long int a = power(2, one) - 1;
long long int b = power(2, zero);
count = (a * b) % max2;
cout << count << endl;
q--;
}
return 0;
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
const long long MOD = 1e9 + 7;
vector<long long> p;
int main() {
int n, q;
cin >> n >> q;
string s;
cin >> s;
p.resize(1e5 + 1);
p[0] = 1;
for (int i = 1; i <= 1e5; i++) {
p[i] = (p[i - 1] * 2) % MOD;
}
vector<long long> kum(n + 1);
kum[0] = 0;
for (int i = 0; i < n; i++) {
if (s[i] == '1') {
kum[i + 1] = kum[i] + 1;
} else {
kum[i + 1] = kum[i];
}
}
for (int i = 0; i < q; i++) {
int l, r;
cin >> l >> r;
long long kol_1 = kum[r] - kum[l - 1];
long long kol_0 = r - l + 1 - kol_1;
long long ans_1 = p[kol_1] - 1;
long long ans_0 = ans_1 * (p[kol_0] - 1);
cout << (ans_1 + ans_0) % MOD << '\n';
}
return 0;
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner();
PrintWriter out = new PrintWriter(System.out);
int MAX = (int)1e5 + 10, MOD = (int)1e9 + 7;
int sum_powers[] = new int[MAX];
int powers[] = new int[MAX];
powers[0] = 1; sum_powers[0] = 1;
for(int i = 1; i < MAX; i++){
powers[i] = (int)(1L * powers[i - 1] * 2 % MOD);
sum_powers[i] = sum_powers[i - 1] + powers[i];
if (sum_powers[i] >= MOD) sum_powers[i] -= MOD;
}
int n = sc.nextInt(), q = sc.nextInt();
int[] arr = new int[n], ones = new int[n];
char[] x = sc.next().toCharArray();
for(int i = 0; i < n; i++){
arr[i] = x[i] - '0';
ones[i] = arr[i];
if(i > 0)ones[i] += ones[i - 1];
}
while (q-- > 0){
int l = sc.nextInt() - 1, r = sc.nextInt() - 1;
int ones_cnt = sum(ones, l, r), zeros_cnt = r - l + 1 - ones_cnt;
if(ones_cnt == 0){
out.println(0);
continue;
}
int res = sum_powers[ones_cnt - 1];
int res2 = (int)(1L * sum_powers[ones_cnt - 1] * (zeros_cnt == 0 ? 0 : sum_powers[zeros_cnt - 1]) % MOD);
out.println((res + res2) % MOD);
}
out.flush();
out.close();
}
static int sum (int[] a, int l, int r){
return a[r] - (l == 0 ? 0 : a[l - 1]);
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public Scanner(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(new File(s)));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | n,q =map(int,input().split())
delish = list(map(int,list(input())))
mod=10**9+7
sums = [0]+delish[:]
for i in range(n):
sums[i+1]+=sums[i]
op=[]
for _ in range(q):
l,r=map(int,input().split())
a=sums[r]-sums[l-1]
b = r-l+1-a
op.append((pow(2,a+b,mod)-pow(2,b,mod))%mod)
print('\n'.join(map(str,op))) | PYTHON3 |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.Scanner;
import java.util.StringTokenizer;
public class main {
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static long mod = 1000000007;
public static void main(String[] args) {
// TODO Auto-generated method stub
FastReader in = new FastReader();
int n = in.nextInt();
int q = in.nextInt();
//in.nextLine();
long num[] = new long[100001];
int c= 2;
num[0]=1;
for(int i = 1;i<100000;i++) {
num[i] = 2*((num[i-1])%mod)%mod;
}
String s = in.nextLine();
int[] nums = new int[s.length()+1];
int[] numsz = new int[s.length()+1];
//nums[0]=s.charAt(0)=='1'?1:0;
for(int i = 1;i<s.length()+1;i++) {
if(s.charAt(i-1)=='1')
nums[i]=nums[i-1]+1;
else
nums[i]=nums[i-1];
if(s.charAt(i-1)=='0')
numsz[i]=numsz[i-1]+1;
else
numsz[i]=numsz[i-1];
}
int t = 0;
while(t<q) {
int in1 = in.nextInt();
int in2 = in.nextInt();
int ones = nums[in2]-nums[in1-1];
int z = in2-in1+1-(ones);
long p = (fastpow(2L,ones)-1L)%mod*(fastpow(2L,z)%mod)%mod;
// BigInteger c = new BigInteger("2");
// BigInteger d = new BigInteger("2");
// c = c.pow(ones+1).subtract(new BigInteger("1")).multiply(d.pow(in2-in1+1-(ones+1))).mod(new BigInteger("1000000007"));;
//c= c.mod(new BigInteger("1000000007"));//(Math.pow(2, in2-in1+1)%1000000007)-(Math.pow(2, in2-in1+1-ones)%1000000007);
System.out.println(p);
t++;
}
}
static long fastpow(long base, long pow)
{
if (pow == 0)
return 1;
if (base == 0)
return 0;
if (pow == 1)
return base;
long x = fastpow(base, pow >>1) % mod;
if (pow % 2 == 0)
return ((x % mod) *(x % mod) % mod);
else
return ((((x % mod)* (x % mod) % mod) % mod) * (base % mod) % mod);
}
}
| JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;
import java.io.InputStream ;
import java.util.InputMismatchException;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) throws IOException {
PrintWriter out = new PrintWriter(System.out);
//Scanner sc = new Scanner();
Reader in = new Reader();
Main solver = new Main();
solver.solve(out, in);
out.flush();
out.close();
}
static int maxn = (int)1e5+1;
static int mod = (int)1e9+7;
void solve(PrintWriter out, Reader in) throws IOException{
int n = in.nextInt();
int q = in.nextInt();
long[] add =new long[n+1];
long[] pow = new long[maxn];
pow[1]=1;
for(int i=2;i<=n;i++) pow[i] = (pow[i-1]*2)%mod;
for(int i=1;i<=n;i++) add[i] = (pow[i] +add[i-1])%mod;
String str = in.next();
int[] arr = new int[n];
for(int i=0 ;i<n;i++){
arr[i] = str.charAt(i)-'0';
}
int[] pre = new int[n];
pre[0]=arr[0];
for(int i=1;i<n;i++) pre[i] = arr[i]+pre[i-1];
long ad[] = new long[maxn];
for(int i=1;i<maxn;i++){
ad[i] = (ad[i-1]+pow[i])%mod;
}
int l,r,size;
int cnt1,cnt2;
long ans=0L;
for(int i=0 ;i<q ;i++){
l = in.nextInt()-1;
r = in.nextInt()-1;
ans=0L;
if(l==0) size = pre[r];
else size = pre[r]-pre[l-1];
int d = size;
ans+=ad[size];
/*long temp=0;
for(int j=size;j>=1;j--){
ans = (ans+pow[size-j+1])%mod;
}*/
size = r-l+1-size;
long init = add[d];
//out.println(init*power(2,size));
out.println((ans-((init*(1-power(2L,size)))%mod)+mod)%mod);
}
}
static long power(long x, int y)
{
long res = 1L;
if(y==-1) return 0L;
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1)==1)
res = (res*x)%mod;
y = y>>1;
x = (x*x)%mod;
}
return res;
}
static class Reader {
private InputStream mIs;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public Reader() {
this(System.in);
}
public Reader(InputStream is) {
mIs = is;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = mIs.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String next() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
}
| JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | n, q = map(int, input().split())
arr = input()
cumulative = [0]
num_ones = 0
for i in range(n):
if arr[i] == '1':
num_ones += 1
cumulative.append(num_ones)
mod = 10**9+7
res = []
for i in range(q):
a, b = map(int, input().split())
ones = cumulative[b] - cumulative[a-1]
zeros = b-a+1 - ones
res.append(((pow(2, ones, mod)-1)*pow(2, zeros, mod)) % mod)
print("\n".join(map(str, res)))
| PYTHON3 |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
long long calc(long long n) {
if (!n) return 1;
if (n == 1) return 2;
long long u = calc(n / 2);
u = ((u % ((long long)(1e9 + 7))) * (u % ((long long)(1e9 + 7)))) %
((long long)(1e9 + 7));
if (n % 2 == 1) return (2 * u) % ((long long)(1e9 + 7));
return u % ((long long)(1e9 + 7));
}
int main() {
long long n, q;
scanf("%lld %lld", &n, &q);
vector<long long> v(n + 1, 0);
string s;
cin >> s;
for (long long i = 0; i < n; i++) {
v[i + 1] = (long long)(s[i] - '0');
}
for (long long i = 1; i < n + 1; i++) v[i] += v[i - 1];
while ((q--)) {
long long l, r;
scanf("%lld %lld", &l, &r);
cout << (((calc(v[r] - v[l - 1]) - 1) % ((long long)(1e9 + 7))) *
(calc(r - l + 1 - v[r] + v[l - 1]) % ((long long)(1e9 + 7)))) %
((long long)(1e9 + 7))
<< '\n';
}
return 0;
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import java.util.Scanner;
public class C {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int q = scan.nextInt();
String S = scan.next();
int[] ones = new int[n+1];
int[] zeros = new int[n+1];
int numOfOnes = 0;
int numOFZeros = 0;
for (int i = 0 ; i < n ; i++) {
if (S.charAt(i) == '1') {
numOfOnes++;
ones[i+1] = numOfOnes;
zeros[i+1] = numOFZeros;
} else {
numOFZeros++;
zeros[i+1] = numOFZeros;
ones[i+1] = numOfOnes;
}
}
long[] pow = new long[100001];
pow[0] = 1;
for (int i = 1 ; i < 100001 ; i++) {
pow[i] = (pow[i-1] * 2) % 1000000007;
}
for (int i = 0 ; i < q ; i++) {
int l = scan.nextInt();
int r = scan.nextInt();
int numOfOne = ones[r] - ones[l-1];
int numOfZero = zeros[r] - zeros[l-1];
long first = pow[numOfOne]-1;
// System.out.println(first);
long second = pow[numOfOne + numOfZero]-1;
// System.out.println(second);
long third = pow[numOfOne]-1;
long fourth = pow[numOfZero]-1;
// System.out.println(fourth);
// System.out.println(third);
if (numOfZero > 0) {
third = (third + fourth ) % 1000000007;
second -= third;
first = (first + second + 1000000007) % 1000000007;
System.out.println(first % 1000000007);
} else {
System.out.println(first % 1000000007);
}
}
}
static long power(long x,
long y, long p)
{
long res = 1; // Initialize result
// Update x if it is more
// than or equal to p
x = x % p;
while (y > 0)
{
// If y is odd, multiply
// x with the result
if ((y & 1) > 0)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
}
| JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | /*
*
* @Author Ajudiya_13(Bhargav Girdharbhai Ajudiya)
* Dhirubhai Ambani Institute of Information And Communication Technology
*
*/
import java.util.*;
import java.io.*;
import java.lang.*;
public class Code62
{
public static void main(String[] args)
{
InputReader in = new InputReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
int test_case = 1;
for(int t=0;t<test_case;t++)
{
int n = in.nextInt();
int query = in.nextInt();
char[] s = in.nextLine().toCharArray();
int[] a = new int[n];
for(int i=0;i<n;i++)
a[i] = s[i]-'0';
for(int i=1;i<n;i++)
a[i] += a[i-1];
for(int q = 0;q<query;q++){
int li = in.nextInt()-1;
int ri = in.nextInt()-1;
long ones = a[ri] - (li>0 ? a[li-1] : 0);
long zeros = ri+1-ones-li;
long ans = (modularExponentiation(2L,ones,mod) - 1L + mod)%mod;
ans = (ans * modularExponentiation(2L,zeros,mod))%mod;
pw.println(ans);
}
}
pw.flush();
pw.close();
}
static class InputReader
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int snext()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
public String readString()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static long mod = 1000000007;
public static int d;
public static int p;
public static int q;
public static int[] suffle(int[] a,Random gen)
{
int n = a.length;
for(int i=0;i<n;i++)
{
int ind = gen.nextInt(n-i)+i;
int temp = a[ind];
a[ind] = a[i];
a[i] = temp;
}
return a;
}
public static void swap(int a, int b){
int temp = a;
a = b;
b = temp;
}
public static HashSet<Integer> primeFactorization(int n)
{
HashSet<Integer> a =new HashSet<Integer>();
for(int i=2;i*i<=n;i++)
{
while(n%i==0)
{
a.add(i);
n/=i;
}
}
if(n!=1)
a.add(n);
return a;
}
public static void sieve(boolean[] isPrime,int n)
{
for(int i=1;i<n;i++)
isPrime[i] = true;
isPrime[0] = false;
isPrime[1] = false;
for(int i=2;i*i<n;i++)
{
if(isPrime[i] == true)
{
for(int j=(2*i);j<n;j+=i)
isPrime[j] = false;
}
}
}
public static int GCD(int a,int b)
{
if(b==0)
return a;
else
return GCD(b,a%b);
}
public static long GCD(long a,long b)
{
if(b==0)
return a;
else
return GCD(b,a%b);
}
public static void extendedEuclid(int A,int B)
{
if(B==0)
{
d = A;
p = 1 ;
q = 0;
}
else
{
extendedEuclid(B, A%B);
int temp = p;
p = q;
q = temp - (A/B)*q;
}
}
public static long LCM(long a,long b)
{
return (a*b)/GCD(a,b);
}
public static int LCM(int a,int b)
{
return (a*b)/GCD(a,b);
}
public static int binaryExponentiation(int x,int n)
{
int result=1;
while(n>0)
{
if(n % 2 ==1)
result=result * x;
x=x*x;
n=n/2;
}
return result;
}
public static long binaryExponentiation(long x,long n)
{
long result=1;
while(n>0)
{
if(n % 2 ==1)
result=result * x;
x=x*x;
n=n/2;
}
return result;
}
public static int modularExponentiation(int x,int n,int M)
{
int result=1;
while(n>0)
{
if(n % 2 ==1)
result=(result * x)%M;
x=(x*x)%M;
n=n/2;
}
return result;
}
public static long modularExponentiation(long x,long n,long M)
{
long result=1;
while(n>0)
{
if(n % 2 ==1)
result=(result * x)%M;
x=(x*x)%M;
n=n/2;
}
return result;
}
public static int modInverse(int A,int M)
{
return modularExponentiation(A,M-2,M);
}
public static long modInverse(long A,long M)
{
return modularExponentiation(A,M-2,M);
}
public static boolean isPrime(int n)
{
if (n <= 1) return false;
if (n <= 3) return true;
if (n%2 == 0 || n%3 == 0)
return false;
for (int i=5; i*i<=n; i=i+6)
{
if (n%i == 0 || n%(i+2) == 0)
return false;
}
return true;
}
static class pair implements Comparable<pair>
{
Integer x, y;
pair(int x,int y)
{
this.x=x;
this.y=y;
}
public int compareTo(pair o) {
int result = x.compareTo(o.x);
if(result==0)
result = y.compareTo(o.y);
return result;
}
public String toString()
{
return x+" "+y;
}
public boolean equals(Object o)
{
if (o instanceof pair)
{
pair p = (pair)o;
return (Math.abs(p.x-x)==0 && Math.abs(p.y-y)==0);
}
return false;
}
public int hashCode()
{
return new Long(x).hashCode()*31 + new Long(y).hashCode();
}
}
} | JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
int n, q, sl1, l, r;
string s;
long long f[100009], lt[100009], a[100009], so, res, sum[100009];
int main() {
int mod = 1000000007;
cin >> n >> q;
getline(cin, s);
getline(cin, s);
for (int i = 0; i < n; i++) {
if (s[i] == '1') a[i + 1] = 1;
}
for (int i = 1; i < n + 1; i++) {
a[i] = a[i - 1] + a[i];
}
lt[0] = 1;
sum[0] = 1;
for (int i = 1; i < n + 1; i++) {
lt[i] = (lt[i - 1] * 2) % mod;
sum[i] = (sum[i - 1] + lt[i]) % mod;
}
for (int i = 1; i < q + 1; i++) {
cin >> l >> r;
sl1 = a[r] - a[l - 1];
if (sl1 == 0) {
cout << 0 << endl;
continue;
}
res = sum[sl1 - 1];
so = sum[sl1 - 1];
if (r - l + 1 - sl1 > 0)
res = (res + (so * (sum[r - l - sl1])) % mod) % mod;
cout << res << endl;
}
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
char c;
int a[101001], n, p, l, r;
const long long mod = 1e9 + 7;
long long num[101010];
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> p;
num[0] = 1;
for (int i = 1; i < 100001; i++) num[i] = num[i - 1] * 2 % mod;
for (int i = 1; i <= n; i++) {
cin >> c;
a[i] = a[i - 1] + c - '0';
}
while (p--) {
cin >> l >> r;
cout << (long long)(num[a[r] - a[l - 1]] - 1) *
(long long)num[r - l + 1 - a[r] + a[l - 1]] % mod
<< endl;
}
return 0;
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
long long m0 = 0, m1 = 0;
vector<long long> v0, v1, v2;
int main() {
long long q, n, i, j, cnt = 0, l, r, one = 0, zero = 0, even = 0, odd = 0,
total = 0;
string s;
cin >> n >> q;
cin >> s;
v0.push_back(0);
v1.push_back(0);
long long p = 1;
for (i = 0; i <= 100005; i++) {
v2.push_back(p);
p = (p * 2) % 1000000007;
}
for (i = 0; i < n; i++) {
if (s[i] == '0')
m0++;
else
m1++;
v0.push_back(m0);
v1.push_back(m1);
}
while (q--) {
cin >> l >> r;
one = v1[r] - v1[l - 1];
zero = v0[r] - v0[l - 1];
even = (v2[one] - 1) % 1000000007;
long long qq = (v2[zero] - 1) % 1000000007;
odd = (even * qq) % 1000000007;
total = (even + odd) % 1000000007;
cout << total << endl;
}
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import java.io.*;
import java.util.*;
import java.text.*;
import java.lang.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.regex.*;
public class Myclass{
// public static ArrayList adj[]=new ArrayList[300001];
public static void main(String[] args)
{
InputReader in = new InputReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n=in.nextInt();
int q=in.nextInt();
char[] s=in.nextLine().toCharArray();
long dp[][]=new long[s.length+2][2];
for(int i=1;i<=n;i++) {
dp[i][0]=dp[i-1][0];
dp[i][1]=dp[i-1][1];
if(s[i-1]=='0')
dp[i][0]++;
else
dp[i][1]++;
}
while(q-->0) {
int l=in.nextInt();
int r=in.nextInt();
long zero=(dp[r][0]-dp[l-1][0]);
long one=(dp[r][1]-dp[l-1][1]);
long ans=(modularExponentiation(2,one,mod)-1)%mod;
if(ans<0)
ans+=mod;
long first=(modularExponentiation(2,one,mod)-1)%mod;
long ans2=(modularExponentiation(2,zero,mod)-1)%mod;
if(ans2<0)
ans2+=mod;
long fi=(ans2*first)%mod;
pw.println((fi+ans)%mod);
}
pw.flush();
pw.close();
}
private static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
static class InputReader
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int snext()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
static class tri implements Comparable<tri> {
int p, c, l;
tri(int p, int c, int l) {
this.p = p;
this.c = c;
this.l = l;
}
public int compareTo(tri o) {
return Integer.compare(l, o.l);
}
}
public String readString()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static long mod = 1000000007;
public static int d;
public static int p;
public static int q;
public static int[] suffle(int[] a,Random gen)
{
int n = a.length;
for(int i=0;i<n;i++)
{
int ind = gen.nextInt(n-i)+i;
int temp = a[ind];
a[ind] = a[i];
a[i] = temp;
}
return a;
}
public static void swap(int a, int b){
int temp = a;
a = b;
b = temp;
}
/* public static long primeFactorization(long n)
{
HashSet<Integer> a =new HashSet<Integer>();
long cnt=0;
for(int i=2;i*i<=n;i++)
{
while(a%i==0)
{
a.add(i);
a/=i;
}
}
if(a!=1)
cnt++;
//a.add(n);
return cnt;
}*/
public static void sieve(boolean[] isPrime,int n)
{
for(int i=1;i<n;i++)
isPrime[i] = true;
isPrime[0] = false;
isPrime[1] = false;
for(int i=2;i*i<n;i++)
{
if(isPrime[i] == true)
{
for(int j=(2*i);j<n;j+=i)
isPrime[j] = false;
}
}
}
public static int GCD(int a,int b)
{
if(b==0)
return a;
else
return GCD(b,a%b);
}
public static long GCD(long a,long b)
{
if(b==0)
return a;
else
return GCD(b,a%b);
}
public static void extendedEuclid(int A,int B)
{
if(B==0)
{
d = A;
p = 1 ;
q = 0;
}
else
{
extendedEuclid(B, A%B);
int temp = p;
p = q;
q = temp - (A/B)*q;
}
}
public static long LCM(long a,long b)
{
return (a*b)/GCD(a,b);
}
public static int LCM(int a,int b)
{
return (a*b)/GCD(a,b);
}
public static int binaryExponentiation(int x,int n)
{
int result=1;
while(n>0)
{
if(n % 2 ==1)
result=result * x;
x=x*x;
n=n/2;
}
return result;
}
public static long binaryExponentiation(long x,long n)
{
long result=1;
while(n>0)
{
if(n % 2 ==1)
result=result * x;
x=x*x;
n=n/2;
}
return result;
}
public static int modularExponentiation(int x,int n,int M)
{
int result=1;
while(n>0)
{
if(n % 2 ==1)
result=(result * x)%M;
x=(x%M*x)%M;
n=n/2;
}
return result;
}
public static long modularExponentiation(long x,long n,long M)
{
long result=1;
while(n>0)
{
if(n % 2 ==1)
result=(result%M * x%M)%M;
x=(x%M * x%M)%M;
n=n/2;
}
return result;
}
public static long modInverse(int A,int M)
{
return modularExponentiation(A,M-2,M);
}
public static long modInverse(long A,long M)
{
return modularExponentiation(A,M-2,M);
}
public static boolean isPrime(int n)
{
if (n <= 1) return false;
if (n <= 3) return true;
if (n%2 == 0 || n%3 == 0)
return false;
for (int i=5; i*i<=n; i=i+6)
{
if (n%i == 0 || n%(i+2) == 0)
return false;
}
return true;
}
public static long[] shuffle(long[] a, Random gen){
for(int i = 0, n = a.length;i < n;i++){
int ind = gen.nextInt(n-i)+i;
long d = a[i];
a[i] = a[ind];
a[ind] = d;
}
return a;
}
static class pair implements Comparable<pair>
{
Long x;
Integer y;
pair(long z,int sum)
{
this.x=z;
this.y=sum;
}
public int compareTo(pair o) {
int result = x.compareTo(o.x);
if(result==0)
result = y.compareTo(o.y);
return result;
}
public String toString()
{
return x+" "+y;
}
public boolean equals(Object o)
{
if (o instanceof pair)
{
pair p = (pair)o;
return p.x == x && p.y == y ;
}
return false;
}
public int hashCode()
{
return new Long(x).hashCode()*31 + new Long(y).hashCode();
}
}
}
class query {
Long x;
Integer y,z;
query(long x,int y,int z){
this.x=x;
this.y=y;
this.z=z;
}
} | JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import java.util.*;
import java.io.*;
import java.math.*;
// Solution to PCS Problem 89: Banh Mi
// https://pcs.cs.cloud.vt.edu/contests/89/problems/C
// Solution by: jLink23
public class BanhMi {
private static PrintWriter out;
public static final int MOD = 1000000007;
public static void main(String[] args) {
out = new PrintWriter(System.out);
FastScanner in = new FastScanner();
int n = in.nextInt();
int q = in.nextInt();
String banhmi = in.next();
// Create prefix sum array
int[] prefix = new int[n + 1];
for (int i = 1; i <= n; i++) {
if (banhmi.charAt(i-1) == '0') {
prefix[i] = prefix[i-1];
} else {
prefix[i] = prefix[i-1] + 1;
}
}
Long[] pow2 = new Long[100001];
pow2[0] = 1L;
for (int i = 1; i <= 100000; i++) {
pow2[i] = pow2[i-1] * 2L % MOD;
}
for (int i = 0; i < q; i++) {
int l = in.nextInt();
int r = in.nextInt();
int k = r-l+1;
int x = prefix[r] - prefix[l-1];
int y = k - x;
out.println(((pow2[x] - 1) * pow2[y]) % MOD);
// BigInteger b1 = new BigInteger("2");
// BigInteger b2 = new BigInteger("1");
// out.println((b1.pow(x).subtract(b2).multiply(b1.pow(y)))
// .mod(BigInteger.valueOf((long) Math.pow(10,9) + 7)));
}
// out.println(Arrays.toString(prefix));
out.flush();
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(Reader in) {
br = new BufferedReader(in);
}
public FastScanner() {
this(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String readNextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readIntArray(int n) {
int[] a = new int[n];
for (int idx = 0; idx < n; idx++) {
a[idx] = nextInt();
}
return a;
}
}
}
| JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
long du = 1e9 + 7;
long long muhai[100005];
int main() {
unsigned int n, q;
std::cin >> n >> q;
std::string x;
std::cin >> x;
muhai[0] = 1;
for (int i = 1; i < 100005; i++) {
muhai[i] = muhai[i - 1] * 2;
muhai[i] %= du;
}
int dem[n];
if (x[0] == '0')
dem[0] = 1;
else
dem[0] = 0;
for (int i = 1; i < n; i++) {
if (x[i] == '0')
dem[i] = dem[i - 1] + 1;
else
dem[i] = dem[i - 1];
}
unsigned int l, r, ko;
unsigned long long ans;
for (int i = 0; i < q; i++) {
std::cin >> l >> r;
if (x[l - 1] == '1')
ko = dem[r - 1] - dem[l - 1];
else
ko = dem[r - 1] - dem[l - 1] + 1;
ans = muhai[r - l + 1] % du - muhai[ko] % du;
ans += du;
ans %= du;
std::cout << ans << std::endl;
}
return 0;
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
const long long maxN = 2e5 + 5, MOD = 1e9 + 7, INF = 1e9 + 1;
int n, q, m, h, l, A[maxN];
int acum[maxN];
long long fastPow(long long x, long long n) {
long long ret = 1;
while (n) {
if (n & 1) ret = ret * x % MOD;
n >>= 1, x = x * x % MOD;
}
return ret;
}
int main() {
ios_base::sync_with_stdio(false), cin.tie(NULL);
cin >> n >> q;
for (int i = int(1); i < int(n + 1); i++) {
char c;
cin >> c;
acum[i] = acum[i - 1];
if (c == '0') {
acum[i]++;
}
}
int a, b;
while (q--) {
cin >> a >> b;
int tot = b - a + 1;
int ceros = acum[b] - acum[a - 1];
long long ans = (fastPow(2, tot) + MOD - 1) % MOD;
ans -= (fastPow(2, ceros) + MOD - 1) % MOD;
ans += MOD;
ans %= MOD;
cout << ans << '\n';
}
return 0;
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | from sys import stdin,stdout
n,q=map(int,stdin.readline().split())
s=stdin.readline()
mod=1000000007
powers=[1 for i in range(n+1)]
for i in range(1,n+1):
powers[i]=(powers[i-1]*2)%mod
cum=[0 for i in range(n+1)]
for i in range(n):
if s[i]=='0':
cum[i+1]=cum[i]+1
else:
cum[i+1]=cum[i]
while q:
l,r=map(int,stdin.readline().split())
lent=r-l+1
zeroes=cum[r]-cum[l-1]
if zeroes==0:
stdout.write(str( powers[lent]-1)+'\n')
else:
temp=powers[zeroes]%mod
temp2=(powers[lent-zeroes]-1)%mod
stdout.write(str((temp*temp2)%mod)+'\n')
q-=1 | PYTHON |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
*
* @author arvin
*/
public class Banh_mi_food {
public static void main(String args[]) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String a[]=br.readLine().split(" ");
int n=Integer.parseInt(a[0]);
int q=Integer.parseInt(a[1]);
String s=br.readLine();
int arr[]=new int[n+1];
int b[]=new int[n+1];
int mod=1000000007;
b[1]=1;
for(int i=2;i<=n;++i) b[i]=(b[i-1]*2)%mod;
for(int i=1;i<=n;++i) b[i]=(b[i]+b[i-1])%mod;
for(int i=1;i<=n;i++)
{
arr[i]=arr[i-1];
if(s.charAt(i-1)=='0')
arr[i]++;
}
while(q--!=0)
{
int count=0;
String t[]=br.readLine().split(" ");
int l=Integer.parseInt(t[0]);
int r=Integer.parseInt(t[1]);
if(r!=l)
count=arr[r]-arr[l-1];
else
count=arr[r]-arr[r-1];
int ans=(b[r-l+1]-b[count]);
System.out.println((long)(((long)ans+mod)%(mod)));
}
br.close();
}
}
| JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 5;
const int Mod = 1000000007;
const int INF = 0x3f3f3f3f;
const long long LL_INF = 0x3f3f3f3f3f3f3f3f;
const double e = exp(1);
const double PI = acos(-1);
const double ERR = 1e-10;
long long pow_(long long a, long long b) {
long long ans = 1;
while (b) {
if (b & 1) ans = (ans * a) % Mod;
b >>= 1;
a = (a * a) % Mod;
}
return ans;
}
long long inv(long long x) { return pow_(x, Mod - 2); }
long long sum[maxn][2];
char str[maxn];
int main() {
int n, q;
scanf("%d%d", &n, &q);
scanf("%s", str + 1);
for (int i = 1; i <= n; i++) {
sum[i][0] = sum[i - 1][0];
sum[i][1] = sum[i - 1][1];
if (str[i] == '0')
sum[i][0] = (sum[i][0] + 1) % Mod;
else
sum[i][1] = (sum[i][1] + 1) % Mod;
;
}
while (q--) {
int l, r;
scanf("%d%d", &l, &r);
long long sum0 = (sum[r][0] - sum[l - 1][0] + Mod) % Mod;
long long sum1 = (sum[r][1] - sum[l - 1][1] + Mod) % Mod;
long long ans = 0;
ans = (pow_(2, sum1) - 1 + Mod) % Mod;
long long st = (pow_(2, sum1) - 1 + Mod) % Mod;
long long tmp = (pow_(2, sum0) - 1 + Mod) % Mod;
tmp = (tmp * st) % Mod;
ans = (ans + tmp) % Mod;
printf("%lld\n", ans);
}
return 0;
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import java.io.*;
import java.util.*;
public class Main {
int [] pre;
void solve() throws IOException {
int n =readInt();
int q =readInt();
long mod = 1000_000_007;
long pow2[] = new long[1000_000];
pow2[0]=1;
for(int i =1;i<1000_000;i++){
pow2[i]=2*pow2[i-1];
pow2[i]%=mod;
}
char [] s =readString().toCharArray();
pre = new int [n];
for(int i =0;i<n;i++){
if(s[i]=='1') pre[i]++;
if(i>0){
pre[i]+=pre[i-1];
}
}
int l,r;
while(q-->0)
{
l=readInt()-1;
r=readInt()-1;
int len = r-l+1;
int units = get(r,l);
long req = pow2[units]-1;
long zero = pow2[units]-1;
int z = len - units;
zero*=pow2[z]-1;
zero%=mod;
out.println((req+zero)%mod);
}
}
int get(int r, int l){
if(l>0) return pre[r]-pre[l-1];
return pre[r];
}
void init() throws FileNotFoundException {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} catch (Exception e) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
tok = new
StringTokenizer("");
}
int minInt(int... values) {
int min = Integer.MAX_VALUE;
for (int value : values) {
min = Math.min(min, value);
}
return min;
}
int maxInt(int... values) {
int max = Integer.MIN_VALUE;
for (int value : values) {
max = Math.max(max, value);
}
return max;
}
long minLong(long... values) {
long min = Long.MAX_VALUE;
for (long value : values) {
min = Math.min(min, value);
}
return min;
}
long maxLong(long... values) {
long max = Long.MIN_VALUE;
for (long value : values) {
max = Math.max(max, value);
}
return max;
}
boolean checkIndex(int index, int size) {
return (0 <= index && index < size);
}
int abs(int a) {
if (a < 0) return -a;
return a;
}
long abs(long a) {
if (a < 0) return -a;
return a;
}
int gcd(int a, int b) {
int tmp = 0;
while (b != 0) {
tmp = a;
a = b;
b = tmp % a;
}
return a;
}
long gcd(long a, long b) {
long tmp = 0;
while (b != 0) {
tmp = a;
a = b;
b = tmp % a;
}
return a;
}
public static void main(String[] args) {
new Main().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
void run() {
try {
long timeStart = System.currentTimeMillis();
init();
solve();
out.close();
long timeEnd = System.currentTimeMillis();
System.err.println("time = " + (timeEnd - timeStart) + " compiled");
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
String readLine() throws IOException {
return in.readLine();
}
String delimiter = " ";
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
String nextLine = readLine();
if (null == nextLine)
return null;
tok = new StringTokenizer(nextLine);
}
return tok.nextToken(delimiter);
}
int[] readIntArray(int b) {
int a[] = new int[b];
for (int i = 0; i < b; i++) {
try {
a[i] = readInt();
} catch (IOException e) {
e.printStackTrace();
}
}
return a;
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
} | JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
const long long mod = 1000000007;
const long long OO = (long long)1e9;
const int dx[] = {0, 1, 0, -1, 1, -1, 1, -1};
const int dy[] = {1, 0, -1, 0, 1, -1, -1, 1};
long long gcd(long long a, long long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
void fast() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cout << fixed << setprecision(4);
}
vector<int> tree;
int arr[1000000];
long long vec[100005];
void build(int s, int e, int pos) {
if (s == e) {
tree[pos] = arr[e];
return;
}
int mid = (s + e) / 2;
build(s, mid, pos * 2);
build(mid + 1, e, pos * 2 + 1);
tree[pos] = tree[pos * 2] + tree[pos * 2 + 1];
}
int getQ(int l, int r, int s, int e, int pos) {
if (s >= l && e <= r) return tree[pos];
if (s > r || e < l) return 0;
int mid = (s + e) / 2;
int x = getQ(l, r, s, mid, pos * 2);
int y = getQ(l, r, mid + 1, e, pos * 2 + 1);
return (x + y);
}
int main() {
fast();
long long power = 1;
for (int i = 1; i <= 100000; i++) {
vec[i] = vec[i - 1] + power;
vec[i] %= mod;
power *= 2;
power %= mod;
}
int n, q;
cin >> n >> q;
char ch;
for (int i = 0; i < n; i++) {
cin >> ch;
arr[i] = ch - '0';
}
int sz = (int)(ceil(log(n) / log(2)));
sz = 2 * (int)(pow(2, sz));
tree.resize(sz + 1);
build(0, n - 1, 1);
int l, r, u, v;
long long ans = 0;
for (int i = 0; i < q; i++) {
cin >> l >> r;
l--, r--;
u = getQ(l, r, 0, n - 1, 1);
v = (r - l + 1) - u;
ans = vec[u] + ((vec[u] * vec[v]) % mod);
ans %= mod;
cout << ans << '\n';
}
return 0;
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import java.math.BigInteger;
import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class Solution {
static long m = (long)1e9+7;
static long modPow(int p){
long res = 1, a = 2;
while(p!=0){
if(p%2==1){
res = res*a;
p--;
}
else if(p%2==0){
a*=a;
p/=2;
}
res%=m;
a%=m;
}
return res%m;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt(), q = in.nextInt(), a[] = new int[n+1];
char c[] = in.next().toCharArray();
a[1] = c[0]=='0'?1:0;
for(int i = 1; i<n; i++){
if(c[i]=='0') a[i+1]++;
a[i+1]+=a[i];
}
for(; q>0; q--){
int l = in.nextInt(), r = in.nextInt(), k = r-l+1;
long ans = (modPow(k)%m - modPow(a[r]-a[l-1])%m)%m;
while(ans<0) ans+=m;
out.println(ans);
}
out.flush();
}
} | JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in Actual solution is at the top
*
* @author MaxHeap
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
CBanhMi solver = new CBanhMi();
solver.solve(1, in, out);
out.close();
}
static class CBanhMi {
long mod = (long) (1e9 + 7);
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int q = in.nextInt();
long[] two = new long[n + 1];
two[0] = 1;
for (int i = 1; i <= n; ++i) {
two[i] = (two[i - 1] * 2L);
two[i] %= mod;
}
char[] s = in.nextCharArray();
int[] acc = new int[n + 1];
for (int i = 1; i <= n; ++i) {
acc[i] = s[i - 1] == '0' ? 0 : 1;
acc[i] += acc[i - 1];
}
// 0 0 1 1 | 1: 1 1 2| 2: 2 3| 4: 5| 9
// 0 1 1 1| 1: 1 2 2| 2: 3 3| 5: 6| 11
// 0 1 1 wwqwq| 1: 1 2 2| 3: 5 3| 8: 8| 16
// 0 0 1 1| 1: 1 1 2| 3: 3 3| 6: 6| 12
// 0 0 0 1| 1: 1 1 1| 2: 2 2| 4: 4| 8
while (q-- > 0) {
int f = in.nextInt();
int t = in.nextInt();
int ones = acc[t] - acc[f - 1];
int zeros = (t - f + 1) - ones;
if (ones == 0) {
out.println(0);
} else {
long ans = two[t - f + 1] - (zeros > 0 ? two[zeros] : 0);
if (zeros == 0) {
--ans;
}
ans = (ans + mod) % mod;
out.println(ans);
}
}
}
}
static class InputReader implements FastIO {
private InputStream stream;
private static final int DEFAULT_BUFFER_SIZE = 1 << 16;
private static final int EOF = -1;
private byte[] buf = new byte[DEFAULT_BUFFER_SIZE];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (this.numChars == EOF) {
throw new UnknownError();
} else {
if (this.curChar >= this.numChars) {
this.curChar = 0;
try {
this.numChars = this.stream.read(this.buf);
} catch (IOException ex) {
throw new InputMismatchException();
}
if (this.numChars <= 0) {
return EOF;
}
}
return this.buf[this.curChar++];
}
}
public int nextInt() {
int c;
for (c = this.read(); isSpaceChar(c); c = this.read()) {
}
byte sgn = 1;
if (c == 45) {
sgn = -1;
c = this.read();
}
int res = 0;
while (c >= 48 && c <= 57) {
res *= 10;
res += c - 48;
c = this.read();
if (isSpaceChar(c)) {
return res * sgn;
}
}
throw new InputMismatchException();
}
public String next() {
int c;
while (isSpaceChar(c = this.read())) {
}
StringBuilder result = new StringBuilder();
result.appendCodePoint(c);
while (!isSpaceChar(c = this.read())) {
result.appendCodePoint(c);
}
return result.toString();
}
public static boolean isSpaceChar(int c) {
return c == 32 || c == 10 || c == 13 || c == 9 || c == EOF;
}
public char[] nextCharArray() {
return next().toCharArray();
}
}
static interface FastIO {
}
}
| JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 |
import java.io.*;
import java.util.Map;
/**
* Copyright © 2018 Chris. All rights reserved.
*
* @author Chris
* 2018/7/9 15:33
* @see format
*/
public class C {
private static BufferedReader br;
private static StreamTokenizer st;
private static PrintWriter pw;
static final int INF = 1000000007;
static final int MOD = 1000000007;
static int n, m, T;
static long num;
static int[] a, b, c;
static long[] al, bl, cl;
static String s, t;
private static void solve() throws IOException {
n = nextInt();
int q = nextInt();
nextLine();
s = nextLine();
a = new int[n + 1];
for (int i = 0; i < n; i++) {
a[i + 1] = a[i] + (s.charAt(i) - '0');
}
while (q-- > 0) {
int l = nextInt();
int r = nextInt();
long k = a[r] - a[l - 1];
long len = r - l + 1;
long m = len - k;
long v1 = (pow(2, k, MOD) + MOD - 1) % MOD;
long v2 = pow(2, m, MOD);
long ans = llMod(v1, v2, MOD);
pw.println(ans);
}
}
static void swap(long a[], int i, int j) {
a[i] ^= a[j];
a[j] ^= a[i];
a[i] ^= a[j];
}
static void swap(int a[], int i, int j) {
a[i] ^= a[j];
a[j] ^= a[i];
a[i] ^= a[j];
}
static void getDiv(Map<Integer, Integer> map, int n) {
int sqrt = (int) Math.sqrt(n);
for (int i = sqrt; i >= 2; i--) {
if (n % i == 0) {
getDiv(map, i);
getDiv(map, n / i);
return;
}
}
map.put(n, map.getOrDefault(n, 0) + 1);
}
public static boolean[] generatePrime(int n) {
boolean p[] = new boolean[n + 1];
p[2] = true;
for (int i = 3; i <= n; i += 2) {
p[i] = true;
}
for (int i = 3; i <= Math.sqrt(n); i += 2) {
if (!p[i]) {
continue;
}
for (int j = i * i; j <= n; j += i << 1) {
p[j] = false;
}
}
return p;
}
// 18位素数:154590409516822759
// 19位素数:2305843009213693951 (梅森素数)
// 19位素数:4384957924686954497
static boolean isPrime(long n) { //determines if n is a prime number
int p[] = {2, 3, 5, 233, 331};
int pn = p.length;
long s = 0, t = n - 1;//n - 1 = 2^s * t
while ((t & 1) == 0) {
t >>= 1;
++s;
}
for (int i = 0; i < pn; ++i) {
if (n == p[i]) {
return true;
}
long pt = pow(p[i], t, n);
for (int j = 0; j < s; ++j) {
long cur = llMod(pt, pt, n);
if (cur == 1 && pt != 1 && pt != n - 1) {
return false;
}
pt = cur;
}
if (pt != 1) {
return false;
}
}
return true;
}
static long llMod(long a, long b, long mod) {
return (a * b - (long) ((double) a / mod * b + 0.5) * mod + mod) % mod;
// long r = 0;
// a %= mod;
// b %= mod;
// while (b > 0) {
// if ((b & 1) == 1) {
// r = (r + a) % mod;
// }
// b >>= 1;
// a = (a << 1) % mod;
// }
// return r;
}
static int pow(long a, long n) {
long ans = 1;
while (n > 0) {
if ((n & 1) == 1) {
ans = (ans * a) % MOD;
}
a = (a * a) % MOD;
n >>= 1;
}
return (int) ans;
}
static int pow(long a, long n, long mod) {
long ans = 1;
while (n > 0) {
if ((n & 1) == 1) {
ans = llMod(ans, a, mod);
}
a = llMod(a, a, mod);
n >>= 1;
}
return (int) ans;
}
private static long[][] initC(int n) {
long c[][] = new long[n][n];
for (int i = 0; i < n; i++) {
c[i][0] = 1;
}
for (int i = 1; i < n; i++) {
for (int j = 1; j <= i; j++) {
c[i][j] = c[i - 1][j - 1] + c[i - 1][j];
}
}
return c;
}
/**
* ps: n >= m, choose m from n;
*/
private static int c(long n, long m) {
if (m > n) {
n ^= m;
m ^= n;
n ^= m;
}
m = Math.min(m, n - m);
long top = 1;
long bot = 1;
for (long i = n - m + 1; i <= n; i++) {
top = (top * i) % MOD;
}
for (int i = 1; i <= m; i++) {
bot = (bot * i) % MOD;
}
return (int) ((top * pow(bot, MOD - 2)) % MOD);
}
static int gcd(int a, int b) {
if (a < b) {
a ^= b;
b ^= a;
a ^= b;
}
while (b != 0) {
int tmp = a % b;
a = b;
b = tmp;
}
return a;
}
static boolean even(long n) {
return (n & 1) == 0;
}
public static void main(String args[]) throws IOException {
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
if (!oj) {
System.setIn(new FileInputStream("in.txt"));
// System.setOut(new PrintStream("out.txt"));
}
br = new BufferedReader(new InputStreamReader(System.in));
st = new StreamTokenizer(br);
pw = new PrintWriter(new OutputStreamWriter(System.out));
st.ordinaryChar('\''); //指定单引号、双引号和注释符号是普通字符
st.ordinaryChar('\"');
st.ordinaryChar('/');
long t = System.currentTimeMillis();
solve();
if (!oj) {
pw.println("[" + (System.currentTimeMillis() - t) + "ms]");
}
pw.flush();
}
private static long[] anLong(int n) throws IOException {
long a[] = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
private static String next(int len) throws IOException {
st.nextToken();
return st.sval;
}
private static int nextInt() throws IOException {
st.nextToken();
return (int) st.nval;
}
private static long nextLong() throws IOException {
return Long.parseLong(nextLine());
}
private static double nextDouble() throws IOException {
st.nextToken();
return st.nval;
}
private static String[] nextSS(String reg) throws IOException {
return br.readLine().split(reg);
}
private static String nextLine() throws IOException {
return br.readLine();
}
}
| JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import java.io.*;
import java.util.*;
public class Main {
private final static long mod = 1000000007;
private static void printArr(char arr[][]) {
int i, j, n = arr.length, m = arr[0].length;
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
System.out.print(arr[i][j]);
}
System.out.println();
}
}
private static long power(long x, long y, long m) {
long temp;
if (y == 0)
return 1;
temp = power(x, y / 2, m);
temp = (temp * temp) % m;
if (y % 2 == 0)
return temp;
else
return ((x % m) * temp) % m;
}
private static long power(long x, long y) {
return power(x, y, mod);
}
private static int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
private static int cmp(Pair p, Pair q) {
return (int) (p.a == q.a ? p.b - q.b : q.a - p.a);
}
static int nextPowerOf2(int a) {
return 1<<nextLog2(a);
}
static int nextLog2(int a) {
return (a == 0 ? 0 : 32 - Integer.numberOfLeadingZeros(a - 1));
}
private static long modInverse(long a, long m) {
long m0 = m;
long y = 0, x = 1;
if (m == 1)
return 0;
while (a > 1) {
long q = a / m;
long t = m;
m = a % m;
a = t;
t = y;
y = x - q * y;
x = t;
}
if (x < 0)
x += m0;
return x;
}
static class Point {
int x, y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return String.format("(%d,%d)",x,y);
}
}
public static Map<Integer, Integer> primeFactors(int numbers) {
int n = numbers;
Map<Integer, Integer> factors = new HashMap<>();
for (int i = 2; i <= n / i; i++) {
while (n % i == 0) {
int cnt = factors.getOrDefault(i,0);
factors.put(i,cnt+1);
n /= i;
}
}
if (n > 1) {
int cnt = factors.getOrDefault(n,0);
factors.put(n,cnt+1);
}
return factors;
}
public static void main(String[] args) throws IOException {
FastReader in = new FastReader();
FastWriter out = new FastWriter();
int t, i, j, n, k, m, l, r, x,y, q, ti, tidx;
//for (t = in.nextInt(), tidx = 1; tidx <= t; tidx++)
{
//out.print(String.format("Case #%d: ", tidx));
n=in.nextInt();
q=in.nextInt();
String s=in.next();
int a[]=new int[n+1];
for(i=0;i<n;i++){
a[i+1]=a[i]+(s.charAt(i)-'0');
}
while (q-->0){
l=in.nextInt();
r=in.nextInt();
k=r-l+1-(a[r]-a[l-1]);
long ans=(power(2,r-l+1)-power(2,k)+mod)%mod;
out.println(ans);
}
}
in.close();
out.close();
}
private static class Pair {
long a;
long b;
public Pair(long a, long b) {
this.a = a;
this.b = b;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pair = (Pair) o;
return a == pair.a &&
b == pair.b;
}
@Override
public int hashCode() {
return Objects.hash(a, b);
}
@Override
public String toString() {
return "Pair{" +
"a=" + a +
", b=" + b +
'}';
}
}
static class FastReader implements Closeable {
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private StringTokenizer st;
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] nextIntArr(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
long[] nextLongArr(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
String[] nextStrArr(int n) {
String[] arr = new String[n];
for (int i = 0; i < n; i++) {
arr[i] = next();
}
return arr;
}
int[][] nextIntArr2(int n, int m) {
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++) {
arr[i] = nextIntArr(m);
}
return arr;
}
long[][] nextLongArr2(int n, int m) {
long[][] arr = new long[n][m];
for (int i = 0; i < n; i++) {
arr[i] = nextLongArr(m);
}
return arr;
}
@Override
public void close() throws IOException {
br.close();
}
}
static class FastWriter implements Closeable {
BufferedWriter bw;
List<String> list = new ArrayList<>();
Set<String> set = new HashSet<>();
FastWriter() {
bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
<T> void print(T obj) throws IOException {
bw.write(obj.toString());
bw.flush();
}
void println() throws IOException {
print("\n");
}
<T> void println(T obj) throws IOException {
print(obj.toString() + "\n");
}
<T> void printArrLn(T[] arr) throws IOException {
for (int i = 0; i < arr.length - 1; i++) {
print(arr[i] + " ");
}
println(arr[arr.length - 1]);
}
<T> void printArr2(T[][] arr) throws IOException {
for (int j = 0; j < arr.length; j++) {
for (int i = 0; i < arr[j].length - 1; i++) {
print(arr[j][i] + " ");
}
println(arr[j][arr.length - 1]);
}
}
<T> void printColl(Collection<T> coll) throws IOException {
for (T e : coll) {
print(e + " ");
}
println();
}
void printCharN(char c, int n) throws IOException {
for (int i = 0; i < n; i++) {
print(c);
}
}
@Override
public void close() throws IOException {
bw.close();
}
}
}
| JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
const int maxn = 100100;
const int MOD = 1e9 + 7;
char s[maxn];
int c[maxn], f[maxn];
int main() {
int n, q;
scanf("%d%d", &n, &q);
scanf("%s", s + 1);
f[0] = 1;
for (int i = 1; i <= n; i++) {
c[i] = c[i - 1] + (s[i] == '1');
f[i] = f[i - 1] * 2ll % MOD;
}
for (int k = 1; k <= q; k++) {
int l, r;
scanf("%d%d", &l, &r);
int o = c[r] - c[l - 1];
int ans = (f[o] + MOD - 1ll) % MOD * f[r - l + 1 - o] % MOD;
printf("%d\n", ans);
}
return 0;
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
int N, Q;
string s;
int s0[100005];
long long qpow(long long x, int n) {
long long res = 1;
while (n) {
if (n & 1) res = res * x % int(1e9 + 7);
x = x * x % int(1e9 + 7);
n /= 2;
}
return res;
}
int main() {
cin >> N >> Q;
cin >> s;
for (int i = 0; i < N; i++) {
s0[i + 1] = s0[i] + (s[i] == '0');
}
int l, r;
while (Q--) {
cin >> l >> r;
long long ans =
(qpow(2, r - l + 1) - qpow(2, s0[r] - s0[l - 1]) + int(1e9 + 7)) %
int(1e9 + 7);
cout << ans << endl;
}
return 0;
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | out = []
n,q = map(int, raw_input().split())
s = raw_input()
pref = [0]
for i in s:
if i == '0':
pref.append(pref[-1])
else:
pref.append(pref[-1]+1)
MOD = pow(10,9)+7
pow2 = [1]*(1+n)
for i in range(n):
pow2[i+1] = (pow2[i] *2)%MOD
for i in range(q):
l,r = map(int, raw_input().split())
n = pref[r] - pref[l-1]
k = r - l + 1 - n
out.append(str((pow2[n]-1 + (pow2[n]-1)*(pow2[k]-1))%MOD))
print('\n'.join(out))
| PYTHON |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
long long int M1 = 1000000007;
const int M2 = 998244353;
const int N = 100005;
int ones[N];
template <typename T>
T modpow(T base, T exp, T modulus) {
base %= modulus;
T result = 1;
while (exp > 0) {
if (exp & 1) result = (result * base) % modulus;
base = (base * base) % modulus;
exp >>= 1;
}
return result;
}
long long int GPmodM(long long int a, long long int r, long long int n) {
return (a * (modpow(r, n, M1) - 1) * modpow(r - 1, M1 - 2, M1)) % M1;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
;
int n, m, q, a, b, temp;
cin >> n >> q;
string s;
cin >> s;
for (int i = 0; i < n; i++) {
if (s[i] == '1') {
ones[i + 1] = ones[i] + 1;
} else {
ones[i + 1] = ones[i];
}
}
for (int i = 0; i < q; i++) {
cin >> a >> b;
int length = b - a + 1;
int one = ones[b] - ones[a - 1];
int zero = length - one;
if (zero == length) {
cout << 0 << "\n";
} else {
long long int ans = modpow(2 * 1LL, 1LL * one, M1) - 1;
ans += GPmodM(ans, 1LL * 2, zero);
cout << ans % M1 << "\n";
}
}
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | init = 1
mod = 10 ** 9 + 7
_2a = []
for i in xrange(100001):
_2a.append(init)
init = init * 2
if init > mod:
init -= mod
#sum_2a = [1]
#for i in xrange(1, 100001):
# sum_2a.append((sum_2a[-1] + _2a[i]) % mod)
n, q = map(int, raw_input().split(" "))
s = raw_input()
sum_s = [1 if s[0] == "1" else 0]
for i in s[1:]:
sum_s.append(sum_s[-1] + int(i))
for _ in xrange(q):
l, r = map(int, raw_input().split(" "))
l -= 1
r -= 1
len1 = sum_s[r] - sum_s[l] + int(s[l])
count1 = len1
count0 = r - l + 1 - len1
#print count1, count0
if count1 == 0:
print 0
else:
print (_2a[count1] - 1) * _2a[count0] % mod
| PYTHON |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main implements Runnable {
public static void main (String args[]){
new Thread(null, new Main(), "Main", 1 << 26).start();
// new Main().run();
}
static final int BASE = (int)1e9 + 7;
static int[] cul;
static int[] f;
public void run() {
MyScanner sc = new MyScanner();
int n = sc.nextInt();
int q = sc.nextInt();
String s = sc.nextLine();
int[] count = new int[n + 1];
for (int i = 1; i <= n; i++) {
count[i] = count[i - 1];
if (s.charAt(i - 1) == '1') count[i]++;
}
init(n);
for (int i = 0; i < q; i++) {
int l = sc.nextInt();
int r = sc.nextInt();
int c1 = count[r] - count[l - 1];
int c0 = r - l + 1 - c1;
long huy = ((long)cul[c1 + c0] - cul[c1] - cul[c0]) % BASE;
if (huy < 0) huy += BASE;
System.out.println((cul[c1] + huy) % BASE);
}
}
void init(int n) {
n++;
f = new int[n + 1];
cul = new int[n + 1];
f[1] = 1;
for (int i = 2; i <= n; i++) {
f[i] = (f[i - 1] * 2) % BASE;
}
for (int i = 1; i <= n; i++) {
cul[i] = (cul[i - 1] + f[i]) % BASE;
}
}
}
class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
| JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 |
import java.util.Scanner;
public class C {
static long m(int n) {
if (n == 0) {
return 1;
}
if (n % 2 == 1) {
long t = m(n / 2);
return 2 * t * t % 1000000007;
} else {
long t = m(n / 2);
return t * t % 1000000007;
}
}
static long work(int sum) {
return m(sum) - 1;
}
public static void main(String[] aaaa) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int q = scanner.nextInt();
byte[] a = scanner.next().getBytes();
//int[] data = new int[100005];
int[] tree = new int[100005];
for (int i = 0; i < a.length; i++) {
if (a[i] == '1') {
//data[i + 1] = i;
int j = i + 1;
while (j <= n) {
tree[j]++;
j += (j & (-j));
}
}
}
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < q; i++) {
int l = scanner.nextInt();
int r = scanner.nextInt();
//for (int iii = 0; iii < 100000; iii++) {
int j = r;
int sum = 0;
while (j > 0) {
sum += tree[j];
j -= (j & (-j));
}
j = l - 1;
while (j > 0) {
sum -= tree[j];
j -= (j & (-j));
}
//System.out.println(sum);
long ans = 0;
int len = (r - l + 1);
//ans += (sum * (sum + 1)) / 2;
long tmp = work(sum);
ans += tmp;
ans += tmp * work(len - sum);
//System.out.println(ans % 1000000007);
stringBuilder.append(ans % 1000000007);
stringBuilder.append("\n");
//}
}
System.out.println(stringBuilder.toString());
}
}
| JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
long long a1[200009];
long long a0[200009];
long long mod = 1e9 + 7;
long long bigmod(long long base, long long pow) {
long long r1, r2;
if (pow <= 0) return 1;
if (pow % 2 != 0) {
r1 = bigmod(2, pow - 1);
r2 = (r1 * 2) % mod;
return r2;
} else if (pow % 2 == 0) {
r1 = bigmod(2, pow / 2);
r2 = (r1 * r1) % mod;
return r2;
}
}
int main() {
long long n, q, i, j, ans1, one, zero, p, q2, q1, l, r;
string s, s1;
cin >> n >> q;
cin >> s1;
s += '#';
s += s1;
for (i = 1; i <= n; i++) {
a1[i] = a1[i - 1];
a0[i] = a0[i - 1];
if (s[i] == '1')
a1[i]++;
else
a0[i]++;
}
for (i = 1; i <= q; i++) {
cin >> l >> r;
one = a1[r] - a1[l - 1];
zero = a0[r] - a0[l - 1];
if (one >= 1) {
p = bigmod(2, one);
p--;
q1 = bigmod(2, zero);
q1--;
ans1 = (q1 * p) % mod;
cout << ((ans1 + p) % mod) << endl;
} else
cout << 0 << endl;
}
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(1, in, out);
out.close();
}
static class SegmentTree {
private class SegmentNode {
int val;
int left;
int right;
SegmentNode leftChild;
SegmentNode rightChild;
public SegmentNode(int val, int left, int right) {
super();
this.val = val;
this.left = left;
this.right = right;
this.leftChild = null;
this.rightChild = null;
}
@Override
public String toString() {
return "SegmentNode [val=" + val + ", left=" + left + ", right=" + right + ", leftChild=" + leftChild
+ ", rightChild=" + rightChild + "]";
}
}
private SegmentNode root;
public SegmentNode getRoot() {
return root;
}
public void setRoot(SegmentNode root) {
this.root = root;
}
public void createSegmentTree(char A[]) {
root = createSegmentTree(0, A.length - 1, A);
}
private SegmentNode createSegmentTree(int left, int right, char A[]) {
if(left > right) return null;
int val = 0;
if(A[left] == '1') val =1;
SegmentNode root = new SegmentNode(val, left, right);
if(left == right) {
return root;
}
int mid = (left+right)/2;
root.leftChild = createSegmentTree(left, mid, A);
root.rightChild = createSegmentTree(mid + 1, right, A);
root.val = root.leftChild.val + root.rightChild.val;
return root;
}
public void updateSingleNode(int pos, int val) {
updateSingleNode(pos, val, root);
}
// single node add
private void updateSingleNode(int pos, int val, SegmentNode root) {
if(root.left == root.right) {
root.val += val;
return;
}
int mid = (root.left + root.right) / 2;
if(pos <= mid) updateSingleNode(pos, val, root.leftChild);
else updateSingleNode(pos, val, root.rightChild);
root.val = root.leftChild.val + root.rightChild.val;
}
public int queryInterval(int l, int r) {
return queryInterval(l, r, root);
}
// query interval sum
private int queryInterval(int l, int r, SegmentNode root) {
int sum = 0;
if(root.left >= l && root.right <= r) {
sum += root.val;
return sum;
}
int mid = (root.left + root.right) / 2;
if(l > mid) sum += queryInterval(l, r, root.rightChild);
else if(r <= mid) sum += queryInterval(l, r, root.leftChild);
else sum += (queryInterval(l, r, root.rightChild) + queryInterval(l, r, root.leftChild));
return sum;
}
@Override
public String toString() {
return "SegmentTree [root=" + root + "]";
}
}
static class Task {
private static final int maxl = 1000000007;
long powerMod(long a, long b, long c)
{
long ans = 1;
a = a % c;
while(b>0) {
if(b % 2 == 1)
ans = (ans * a) % c;
b = b/2;
a = (a * a) % c;
}
return ans;
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int a[] = new int[m];
int b[] = new int[m];
String string = in.next();
int one, zero;
for(int i=0;i<m;i++) {
a[i] = in.nextInt();
b[i] = in.nextInt();
}
char[] nodeArray = new char[n];
for(int i=0;i<n;i++) {
nodeArray[i] = string.charAt(i);
}
SegmentTree segmentTree = new SegmentTree();
segmentTree.createSegmentTree(nodeArray);
for(int i=0;i<m;i++) {
a[i] --;b[i]--;
zero = 0;one = 0;
one = segmentTree.queryInterval(a[i], b[i]);
zero = b[i] - a[i] + 1 - one;
long z = powerMod(2, zero, maxl);
long o = powerMod(2, one, maxl);
long ans = z*(o-1);
ans%=maxl;
out.println(ans);
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import sys
r = sys.stdin.readlines()
M = 10 ** 9 + 7
n, q = r[0].split()
n = int(n)
q = int(q)
s = r[1]
p = [0]
k = 0
for v in range(n):
d = int(s[v])
k += (1 - d)
p.append(k)
ans = []
for k in range(q):
a, b = r[k + 2].split()
a = int(a)
b = int(b)
l = b - a + 1
zero = p[b] - p[a - 1]
ans.append(str((pow(2, l, M) - pow(2, zero, M) + M) % M))
sys.stdout.write("\n".join(ans)) | PYTHON3 |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | from sys import stdin
n,q = map(int,stdin.readline().split())
a = stdin.readline().strip()
pre = [0] * (n+1)
mod = 10**9 + 7
po = [1] * (n+1)
for i in xrange(1,n+1):
po[i] = 2 * po[i-1]
if po[i] >=mod:
po[i]-=mod
for i in xrange(1,n+1):
pre[i] = pre[i-1]
if a[i-1]=='1':
pre[i]+=1
for i in xrange(q):
l,r = map(int,stdin.readline().split())
one = pre[r] - pre[l-1]
zero = (r - l + 1) - one
fir = po[one]-1
sec = po[zero]
print (fir * sec)%mod | PYTHON |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class Main {
static final long MOD = 1_000_000_007, INF = 1_000_000_000_000_000_000L;
static final int INf = 1_000_000_000;
static FastReader reader;
static PrintWriter writer;
public static void main(String[] args) {
Thread t = new Thread(null, new O(), "Integer.MAX_VALUE", 100000000);
t.start();
}
static class O implements Runnable {
public void run() {
try {
magic();
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
public static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//variables here
static void magic() {
reader = new FastReader();
writer = new PrintWriter(System.out, true);
long two[] = new long[100001];
two[0]++;
for(int i=1;i<=100000;++i) {
two[i] = two[i-1] + two[i-1];
if(two[i]>=MOD) {
two[i]-=MOD;
}
}
int n = reader.nextInt(), q = reader.nextInt();
int cum[] = new int[n];
String s = reader.next();
for(int i=0;i<n;++i) {
cum[i] = s.charAt(i)-'0';
if(i>0) {
cum[i]+=cum[i-1];
}
}
StringBuilder fast = new StringBuilder();
while(q-->0) {
int l = reader.nextInt()-1, r = reader.nextInt()-1;
int n1 = cum[r];
if(l>0) {
n1-=cum[l-1];
}
int n2 = (r-l+1) - n1;
long ans = (two[n1] - 1 + MOD) * two[n2];
ans%=MOD;
fast.append(ans);
fast.append("\n");
}
writer.println(fast);
}
} | JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
const long long MOD = (long long)1e9 + 7;
long long mod_pow(long long x, long long n) {
long long res = 1;
while (n > 0) {
if (n & 1) res = res * x % MOD;
x = x * x % MOD;
n >>= 1;
}
return res;
}
signed main() {
long long n, q;
cin >> n >> q;
string s;
cin >> s;
vector<long long> csum1(n + 1, 0), csum0(n + 1, 0);
for (long long i = 0; i < n; i++) {
csum0[i + 1] = csum0[i];
csum1[i + 1] = csum1[i];
if (s[i] == '0') csum0[i + 1]++;
if (s[i] == '1') csum1[i + 1]++;
}
for (long long i = 0; i < q; i++) {
long long l, r;
cin >> l >> r;
long long ans = 0;
long long cnt1 = csum1[r] - csum1[l - 1];
long long cnt0 = csum0[r] - csum0[l - 1];
ans += mod_pow(2, cnt1) - 1;
ans %= MOD;
ans += (mod_pow(2, cnt0) - 1) * (mod_pow(2, cnt1) - 1);
ans %= MOD;
cout << ans << endl;
}
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
long long mod = 1e9 + 7;
long long solve(long long good, long long len, vector<long long> &pow) {
long long rest = len - good;
long long ans = pow[good] - 1;
long long help = (ans * (pow[rest] - 1)) % mod;
ans += help;
ans %= mod;
return ans;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
vector<long long> pow(100005);
pow[0] = 1;
for (int i = 1; i < 1e5 + 5; i++) {
pow[i] = (pow[i - 1] * 2) % mod;
}
int n, q;
cin >> n >> q;
string s;
cin >> s;
int x;
vector<int> pref(n + 1);
pref[0] = 0;
for (int i = 0; i < n; i++) {
if (s[i] == '0')
x = 0;
else
x = 1;
pref[i + 1] = pref[i] + x;
}
int L, R;
for (int i = 0; i < q; i++) {
cin >> L >> R;
int len = (R - L + 1);
int good = pref[R] - pref[L - 1];
cout << solve(good, len, pow) << endl;
}
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Bahnmi {
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static long m=(long) (Math.pow(10,9)+7);
public static void main(String[] args) {
// TODO Auto-generated method stub
FastReader sc=new FastReader();
//Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int q=sc.nextInt();
String s=sc.next();
List<Integer> list=new ArrayList<>();
list.add(0);
char[] ch=s.toCharArray();
int one=0;
for(int i=0;i<ch.length;++i) {
if(ch[i]=='1')
one+=1;
list.add(one);
}
while(q-->0) {
int l=sc.nextInt();
int r=sc.nextInt();
int o=list.get(r)-list.get(l-1);
int z=r-l+1-o;
long ans=(pow(2,z,m)*(pow(2,o,m)-1))%m;
System.out.println(ans);
}
}
static long pow(long x, long y, long p){
long res = 1;
x = x % p;
while (y > 0)
{
if ((y & 1)==1)
res = (res*x) % p;
y = y>>1;
x = (x*x) % p;
}
return res;
}
}
| JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
long long fenwick[100005];
void update(long long value, long long where, long long n) {
while (where <= n) {
fenwick[where] += value;
where += (where & -where);
}
}
long long query(long long where) {
long long res = 0;
while (where) {
res += fenwick[where];
where -= (where & -where);
}
return res;
}
void fastio() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
}
long long p[100007];
long long exp(long long a, long long b) {
if (b == 0) return 1;
if (b == 1) return a;
long long half = exp(a, b / 2) % 1000000007;
if (b % 2 == 1)
return ((half * half) % 1000000007 * a % 1000000007) % 1000000007;
return (half * half) % 1000000007;
}
int main() {
fastio();
long long n, q;
cin >> n >> q;
vector<long long> arr;
memset(fenwick, 0, sizeof fenwick);
memset(p, 0, sizeof p);
p[0] = 0;
for (int i = 1; i < 100007; i++) {
if (i == 1) {
p[i] = 2;
continue;
}
long long lo = exp(2, i);
p[i] = ((p[i - 1] % 1000000007) + lo % 1000000007) % 1000000007;
p[i] %= 1000000007;
}
string s;
cin >> s;
for (long long i = 0; i < n; i++) update((long long)s[i] - '0', i + 1, n);
while (q--) {
long long l, r;
cin >> l >> r;
long long x = query(r) - query(l - 1);
long long ans = 0;
if (r - l + 1 == x)
cout << ((((p[(r - l)] % 1000000007 -
p[(r - l + 1 - x) - 1] % 1000000007) +
1000000007) %
1000000007) +
1) %
1000000007
<< "\n";
else
cout << (((p[(r - l)] % 1000000007 -
p[(r - l + 1 - x) - 1] % 1000000007) +
1000000007) %
1000000007)
<< "\n";
}
return 0;
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import sys
input = sys.stdin.readline
n, q = map(int, input().split())
arr = [int(z) for z in input().rstrip()]
prefsums = [0, arr[0]]
for i in range(1, n):
prefsums.append(prefsums[i] + arr[i])
for query in range(q):
l, r = map(int, input().split())
num1 = prefsums[r] - prefsums[l-1]
num0 = (r - l + 1) - num1
p1 = pow(2, num1, 10**9 + 7) - 1
#p1 = (2 ** num1 - 1) % (10 ** 9 + 7)
#p2 = (((2 ** num0 - 1) % (10 ** 9 + 7)) * p1) % (10 ** 9 + 7)
p2 = ((pow(2, num0, 10**9 + 7) - 1) * p1) % (10**9 + 7)
sys.stdout.write(str((p1 + p2) % (10 ** 9 + 7)) + '\n')
| PYTHON3 |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
const int MAXN = 100005;
int q, n, l, r, ans;
char c;
long long sum[MAXN], sumPow[MAXN];
void init() {
sumPow[0] = 1;
long long temp = 1;
for (int i = 1; i <= MAXN; i++) {
temp = temp * 2 % MOD;
sumPow[i] = (sumPow[i - 1] % MOD + temp % MOD) % MOD;
}
}
int main() {
ios::sync_with_stdio(false);
init();
cin >> n >> q;
sum[0] = 0;
for (int i = 1; i <= n; i++) {
cin >> c;
sum[i] = sum[i - 1] + (c == '0' ? 1 : 0);
}
for (int i = 0; i < q; i++) {
cin >> l >> r;
int x = sum[r] - sum[l - 1];
int size = r - l + 1;
ans = (sumPow[size - 1] - (x == 0 ? 0 : sumPow[x - 1]) + MOD) % MOD;
printf("%d\n", ans);
}
return 0;
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
int m = (int)1e9 + 7;
int mult(int a, int b) { return (long long)a * b % m; }
void add(int& a, int b) {
a += b;
if (a >= m) {
a -= m;
}
}
int mpow(int a, int b) {
int ret = 1;
while (b) {
if (b & 1) {
ret = mult(ret, a);
}
a = mult(a, a);
b >>= 1;
}
return ret;
}
int main() {
int n, q;
cin >> n >> q;
string s;
cin >> s;
vector<int> arr;
vector<int> ones = {0};
for (int i = 0; i < n; ++i) {
arr.push_back(s[i] - '0');
ones.push_back(ones.back() + arr.back());
}
for (int i = 0; i < q; ++i) {
int l, r;
cin >> l >> r;
int length = r - l + 1;
int sums = ones[r] - ones[l - 1];
int a = mpow(2, sums);
int ans = 0;
ans = (ans + a - 1) % m;
int mul = a - 1;
int b = mpow(2, length - sums);
int c = 0;
if (b <= 1)
c = 0;
else {
c = (mult((b - 1), mul)) % m;
}
add(ans, c);
ans = ans % m;
cout << ans << endl;
}
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | n,q=map(int,raw_input().split())
s=raw_input()
mod=10**9+7
pre=[0,int(s[0])]
for i in range(1,len(s)):
pre.append(pre[i]+int(s[i]))
#print pre
pow2=[1]
for i in range(1,10**5+15):
pow2.append((pow2[i-1]*2)%mod)
while(q!=0):
q=q-1
l,r=map(int,raw_input().split())
x=pre[r]-pre[l-1]
print (pow2[r-l+1]-pow2[r-l+1-x])%mod
#print (pow(2,r-l+1,10**9+7)-pow(2,r-l+1-x,mod))%mod
| PYTHON |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import java.io.*;
import java.util.*;
public class A {
public static void main(String[] args) throws Exception{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int q=sc.nextInt();
String s=sc.next();
int arr[]=new int [n];
for(int i=0;i<n;i++) {
arr[i]=s.charAt(i)-'0';
}
int one[]=new int [n+1];
int zero[]=new int [n+1];
if(arr[0]==1)one[1]++;
else zero[1]++;
for (int i=1;i<n;i++) {
one[i+1]+=arr[i]+one[i];
if(arr[i]==0) {
zero[i+1]=zero[i]+1;
}else
zero[i+1]=zero[i];
}
//System.out.println(Arrays.toString(zero));
while(q-->0) {
int l=sc.nextInt();
int r=sc.nextInt();
int o=one[r]-one[l-1];
int z=zero[r]-zero[l-1];
// System.out.println(o+" "+z);
long ans=modPow(2,o, (int)1e9+7)-1;
// System.out.println(ans);
long p=1l*modPow(2, o, (int)1e9+7)-1;
//System.out.println(p+" "+z);
// System.out.println((((p%mod)*modPow(2, z, (int)1e9+7))%mod)%mod -7+"**");
if(z>=1)ans=((((ans%mod)+((p%mod)*(modPow(2, z, (int)1e9+7)-1))%mod)%mod))%mod;
System.out.println((ans+mod)%mod);
}
}
static int mod=(int)1e9+7;
static long modPow(int a, int e, int mod) // O(log e)
{
a %= mod;
long res = 1;
while(e > 0)
{
if((e & 1) == 1)
res =(1l*res * a) % mod;
a = (int)((1l*a * a) % mod);
e >>= 1;
}
return res;
}
}
class Scanner{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system));}
public Scanner(String file) throws Exception{br = new BufferedReader(new FileReader (file));}
public String next() throws IOException{
while (st==null|| !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException{
return Integer.parseInt(next());
}
public long nextLong() throws IOException{
return Long.parseLong(next());
}
public String nextLine() throws IOException{
return br.readLine();
}
public Double nextDouble() throws IOException{
return Double.parseDouble(next());
}
}
| JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #########################################################################################################\
#########################################################################################################
###################################The_Apurv_Rathore#####################################################
#########################################################################################################
#########################################################################################################
import sys,os,io
from sys import stdin
from math import log, gcd, ceil
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop
from bisect import bisect_left , bisect_right
import math
alphabets = list('abcdefghijklmnopqrstuvwxyz')
def ncr(n, r, p):
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den,
p - 2, p)) % p
def primeFactors(n):
l = []
while n % 2 == 0:
l.append(2)
n = n / 2
for i in range(3,int(math.sqrt(n))+1,2):
while n % i== 0:
l.append(int(i))
n = n / i
if n > 2:
l.append(n)
return l
# return list(set(l))
def power(x, y, p) :
res = 1
x = x % p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) :
res = (res * x) % p
y = y >> 1 # y = y/2
x = (x * x) % p
return res
def SieveOfEratosthenes(n):
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
return prime
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def si():
return input()
def prefix_sum(arr):
r = [0] * (len(arr)+1)
for i, el in enumerate(arr):
r[i+1] = r[i] + el
return r
def divideCeil(n,x):
if (n%x==0):
return n//x
return n//x+1
def ii():
return int(input())
def li():
return list(map(int,input().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(''.join([str(x) for x in a]) + '\n')
#__________________________TEMPLATE__________________OVER_______________________________________________________
if(os.path.exists('input.txt')):
sys.stdin = open("input.txt","r") ; sys.stdout = open("output.txt","w")
# else:
# input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = 1
# t = int(input())
for _ in range(t):
n,q = li()
s = si()
# s = s[:-2]
# s = s[1:]
s = list(s)
# print(s)
zeros = [0]*n
ones = [0]*n
if (s[0]=='1'):
ones[0]=1
else:
zeros[0]=1
for i in range(1,n):
ones[i]+=ones[i-1]
zeros[i]+=zeros[i-1]
if (s[i]=='1'):
ones[i]+=1
else:
zeros[i]+=1
zeros = [0]+zeros
ones = [0]+ones
mod = 1000000007
a= []
for i in range(q):
l,r = li()
x = ones[r]-ones[l-1]
y = zeros[r]-zeros[l-1]
# print(x,y)
ans = (pow(2,x,mod)-1)%mod
ans = (ans*pow(2,y,mod))%mod
# print(ans)
a.append(str(ans))
print('\n'.join(map(str,a)))
| PYTHON3 |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 |
import sys
if __name__ == '__main__':
n, q = map(int, sys.stdin.readline().split())
arr = sys.stdin.readline()
total = [0]*n
if arr[0] == '1':
total[0] = 1
else:
total[0] = 0
for i in range(1, n):
if arr[i] == '1':
total[i] = total[i-1]+1
else:
total[i] = total[i-1]
mod = 10**9+7
for i in range(q):
l, r = map(int, sys.stdin.readline().split())
l -= 1
r -= 1
length = r-l+1
ans = pow(2, length, mod)
ans = (ans-1+mod) % mod
if l == 0:
zeroes = length-total[r]
else:
zeroes = length-(total[r]-total[l-1])
sub = pow(2, zeroes, mod)
sub = (sub-1+mod) % mod
ans = (ans-sub+mod) % mod
print(ans)
| PYTHON3 |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
long long n, q, a[100005], b[100005], l, r, _2[100005];
char s[100005];
int main() {
_2[0] = 1;
cin >> n >> q;
for (int i = 1; i <= n; i++) _2[i] = _2[i - 1] * 2 % 1000000007;
scanf("%s", s);
a[0] = b[0] = 0;
for (int i = 1; i <= n; i++) {
a[i] = a[i - 1] + (s[i - 1] == '1');
b[i] = b[i - 1] + (s[i - 1] == '0');
}
while (q--) {
scanf("%lld%lld", &l, &r);
int x = a[r] - a[l - 1], y = b[r] - b[l - 1];
printf("%lld\n", (_2[x] - 1 + 1000000007) * _2[y] % 1000000007);
}
return 0;
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import sys
r = sys.stdin.readlines()
M = 10 ** 9 + 7
n, q = map(int, r[0].strip().split())
s = list(map(int, r[1].strip()))
p = [0]
for i in range(n):
p.append(p[i] + int(s[i]))
ans = []
for k in range(q):
a, b = map(int, r[k + 2].strip().split())
l = b - a + 1
one = p[b] - p[a - 1]
zero = l - one
ans.append(str(((pow(2, one, M) - 1) * pow(2, zero, M)) % M))
sys.stdout.write("\n".join(ans)) | PYTHON3 |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll N = 1e5 + 10;
const ll inf = 1e18 + 10;
const ll MOD = 1e9 + 7;
ll n, q, cum[N];
ll add(ll x, ll y) { return (x + y) % MOD; }
ll mult(ll a, ll b) {
ll res = a * b;
res = res % MOD;
return res;
}
ll binpow(ll a, ll b, ll m) {
a %= m;
ll res = 1;
while (b > 0) {
if (b & 1) res = res * a % m;
a = a * a % m;
b >>= 1;
}
return res;
}
ll d(ll x, ll y) { return mult(x, binpow(y, MOD - 2, MOD)); }
ll subtract(ll x, ll y) {
ll res = x - y;
if (res < 0) res += MOD;
return res;
}
int main() {
cin >> n >> q;
string s;
cin >> s;
for (ll i = 1; i <= n; i++) {
cum[i] = cum[i - 1] + s[i - 1] - '0';
}
while (q--) {
ll l, r;
cin >> l >> r;
ll one = cum[r] - cum[l - 1];
ll zero = r - l + 1 - one;
ll ans = mult(subtract(binpow(2, one, MOD), 1), binpow(2, zero, MOD));
printf("%d\n", ans);
}
return 0;
}
| CPP |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.*;
public class BanhMi {
public static final long MOD = 1000000007;
public static void main(String[] args) {
FastScanner scanner = new FastScanner();
int N = scanner.nextInt();
StringBuilder stringBuilder = new StringBuilder();
int Q = scanner.nextInt();
BIT bit = new BIT(N+1);
char[] vals = scanner.next().toCharArray();
for(int i = 1; i <= N; i++) {
bit.update(i, vals[i-1]-'0');
}
for(int i = 0; i < Q; i++) {
int l = scanner.nextInt();
int r = scanner.nextInt();
stringBuilder.append(calcVal((int)bit.rangeSum(l, r), r-l+1)).append("\n");
}
System.out.print(stringBuilder.toString());
}
public static long calcVal(int val, int sz) {
if (val == 0) return 0;
int nZeroes = sz - val;
long ret = (modPow(2, val-1)*2-1)%MOD;
ret = (ret*modPow(2, nZeroes))%MOD;
return ret;
}
public static long modPow(long x, long y) {
if (y == 0) return 1;
long p = modPow(x, y / 2) %MOD;
p = (p * p) % MOD;
if (y % 2 == 0) return p;
else return (x * p) % MOD;
}
public static class BIT {
long[] table;
int sz;
public BIT(int ss){
table = new long[ss];
sz = ss;
}
public void update(int loc, long amt) {
while(loc < sz) {
table[loc]+=amt;
loc += Integer.lowestOneBit(loc);
}
}
public long prefixSum(int loc) {
long ret = 0L;
while(loc > 0) {
ret+=table[loc];
loc-=Integer.lowestOneBit(loc);
}
return ret;
}
public long rangeSum(int l, int r) {
return prefixSum(r) - prefixSum(l-1);
}
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(Reader in) {
br = new BufferedReader(in);
}
public FastScanner() {
this(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String readNextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readIntArray(int n) {
int[] a = new int[n];
for (int idx = 0; idx < n; idx++) {
a[idx] = nextInt();
}
return a;
}
}
}
| JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | # use this as the main template for python problems
import sys
from collections import Counter
NUM = int(1e9+7)
def compute1(size, tots):
val = 0
ans = 0
for i in range(tots):
delic = val + 1
ans += delic
val = ((val % NUM) + (delic % NUM)) % NUM
print('=--')
for i in range(size - tots):
delic = val
ans += delic
val = ((val % NUM) + (delic % NUM)) % NUM
print(delic)
print('=--')
return ans % int(1e9+7)
def compute2(size, tots):
# ans = 2 ** tots - 1
ans = power(2, tots, NUM) - 1
ans = ((ans % NUM) * (power(2, (size - tots), NUM))) % NUM
#ans = ((ans % NUM) * (2 ** (size - tots)) % NUM) % NUM
return ans
def power(x, y, p) :
res = 1 # Initialize result
# Update x if it is more
# than or equal to p
x = x % p
while (y > 0) :
# If y is odd, multiply
# x with result
if ((y & 1) == 1) :
res = (res * x) % p
# y must be even now
y = y >> 1 # y = y/2
x = (x * x) % p
return res
def solution(n, q, arr):
st = SegmentTree(arr, '+')
for x in range(q):
l, r = [int(val) for val in sys.stdin.readline().split()]
l -= 1
r -= 1
size = r - l + 1
#tots = sum(arr[l:r+1])
tots = st.query(l, r)
print(compute2(size, tots))
def validate():
from random import randint
for i in range(1, 20000):
tots = randint(0, i)
val1 = compute1(i, tots)
val2 = compute2(i, tots)
if(val1 != val2):
print(val1, val2)
raise Exception()
#print(compute(1000000, 1000000))
def random_query(n):
from random import randint
l = randint(0, n-1)
r = randint(0, n-1)
while(r < l):
r = randint(0, n-1)
return l, r
def random_sequence(n):
from random import randint
return [randint(0, 1) for val in range(n)]
class SegmentTree(object):
# this class was constructed with inspiration and guidance from:
# https://leetcode.com/articles/a-recursive-approach-to-segment-trees-range-sum-queries-lazy-propagation/
# O(n) leaves, O(n-1) internal nodes.
# build: O(n) :D
# update: O(k), where k = height of tree :D
# query: O(k), where k = height of tree :D
def __init__(self, data, op):
from math import log
from math import ceil
# The node of the tree is at index 0, thus tree[0] is the root
# The children of three[i] are tored at tree[2*i+1] and tree[2*i+2]
# The internal nodes in
self.n = len(data)
self.tree = [0] * self.n*4 #int(2 * 2 ** (ceil(log(n, 2))) - 1) * 2
self.merge_op = op
self._build_tree(data, 0, 0, self.n-1)
def _build_tree(self, data, ind, lo, hi):
# call as build_tree(data, 0, 0, n-1)
# leaf node, store value
if (lo == hi):
self.tree[ind] = data[lo]
return
# recurse
mid = lo + (hi - lo) // 2
self._build_tree(data, 2 * ind + 1, lo, mid)
self._build_tree(data, 2 * ind + 2, mid + 1, hi)
# merge
self.tree[ind] = self._merge(self.tree[2 * ind + 1], self.tree[2 * ind + 2])
def _merge(self, val1, val2):
if(self.merge_op == '+'):
return val1 + val2
elif(self.merge_op == "OR"):
return val1 | val2
elif(self.merge_op == "XOR"):
return val1 ^ val2
elif(self.merge_op == "*"):
return val1 * val2
def query(self, i, j, ind=0, lo=0, hi=None):
#def query(self, ind, lo, hi, i, j):
# call as query(0, 0, n-1, i, j)
# where i:j is the slice being queried
if(hi == None):
hi = self.n-1
if (lo > j or hi < i):
raise Exception()
return 0 # represents null node completely outside segment
if (i <= lo and j >= hi):
return self.tree[ind]
mid = lo + (hi - lo) // 2
if (i > mid):
return self.query(i, j, 2 * ind + 2, mid + 1, hi)
elif (j <= mid):
return self.query(i, j, 2 * ind + 1, lo, mid)
lq = self.query(i, mid, 2 * ind + 1, lo, mid)
rq = self.query(mid + 1, j, 2 * ind + 2, mid + 1, hi)
return self._merge(lq, rq)
if __name__ == "__main__":
# single variables
n, q = [int(val) for val in sys.stdin.readline().split()]
# vectors
arr = [int(val) for val in sys.stdin.readline().split()[0]]
#validate()
# solve it!
solution(n, q, arr)
| PYTHON3 |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import java.text.*;
import java.util.*;
import java.io.*;
public class Main {
static final int mod = 1000000007;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer stk = new StringTokenizer(br.readLine());
int n = Integer.parseInt(stk.nextToken());
int q = Integer.parseInt(stk.nextToken());
String input = br.readLine();
ArrayList<Integer> d = new ArrayList<>();
for(int i=0;i<n;i++){
d.add(input.charAt(i)-'0');
}
SegmentTree st = new SegmentTree(n);
st.insert(d);
StringBuilder sb = new StringBuilder();
for(int i=0;i<q;i++){
stk = new StringTokenizer(br.readLine());
int l = Integer.parseInt(stk.nextToken());
int r = Integer.parseInt(stk.nextToken());
int sum = st.getSum(l,r);
sb.append(getBinaryToDecimal(r-l+1,sum)).append('\n');
}
System.out.print(sb);
}
public static long getBinaryToDecimal(int len,int one){
int zero = len-one;
return (getPow(2,len)-getPow(2,zero)+mod)%mod;
}
public static long getPow(long n,long exp){
if(exp == 0 ) return 1;
if(exp == 1) return n%mod;
if(exp %2 ==0){
long v = getPow(n,exp/2);
return v*v%mod;
}
else{
long v = getPow(n,exp-1);
return v*n%mod;
}
}
}
class SegmentTree {
ArrayList<Integer> tree;
int s;
public SegmentTree(int n) {
for (s = 1; s < n; s *= 2);
tree = new ArrayList<Integer>(s * 2);
tree.add(0);
for (int i = 1; i < s + s; i++)
tree.add(0);
}
void insert(ArrayList<Integer> d) {
for (int i = s; i < s + d.size(); i++)
tree.set(i, d.get(i - s));
for (int i = s - 1; i >= 1; i--)
tree.set(i, (tree.get(i * 2) + tree.get(i * 2 + 1)));
}
int getSum(int Left, int Right) {
int l = Left + s - 1, r = Right + s - 1;
int rval = 0;
while (l <= r) {
if (l % 2 == 0) l /= 2;
else {
rval += tree.get(l);
l = (l / 2) + 1;
}
if (r % 2 == 1) r /= 2;
else {
rval += tree.get(r);
r = (r / 2) - 1;
}
}
return rval;
}
} | JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | /* Rajkin Hossain */
import java.io.*;
import java.util.*;
public class C {
//static FastInput k = new FastInput("/home/rajkin/Desktop/input.txt");
static FastInput k = new FastInput(System.in);
static FastOutput z = new FastOutput();
static int n, q;
static char [] y;
static Pair [] data;
static long mod = (long) 1e9 + 7l;
static long pow(long a, long b){
if(b == 0) return 1l % mod;
long x = pow(a, b / 2);
x = (x * x) % mod;
if(b % 2 == 1) x = (x * a) % mod;
return x;
}
static void startAlgorithm(){
while(q-->0){
int left = k.nextInt();
int right = k.nextInt();
Pair p2 = data[right];
Pair p1 = data[left-1];
long one = p2.one - p1.one;
long zero = p2.zero - p1.zero;
long oneSum = 0l, zeroSum = 0l;
if(one % 2l == 0){
oneSum = pow(4l, one/2) - 1l;
}
else{
oneSum = (1l % mod) + ((2l % mod) * (pow(4l, (one-1)/2) - 1l)) % mod;
oneSum %= mod;
}
if(zero % 2 == 0){
zeroSum = pow(4l, zero/2) - 1l;
}
else{
zeroSum = (1l % mod) + ((2l % mod) * (pow(4l, (zero-1)/2) - 1l)) % mod;
zeroSum %= mod;
}
zeroSum = ((oneSum % mod) * (zeroSum % mod)) % mod;
long ans = ((oneSum % mod) + (zeroSum % mod)) % mod;
z.println(ans);
}
}
public static void main(String[] args) throws Exception {
while(k.hasNext()){
n = k.nextInt();
q = k.nextInt();
y = k.next().toCharArray();
data = new Pair[n+1];
data[0] = new Pair(0,0);
for(int i = 1; i<=n; i++){
if(y[i-1] == '0'){
data[i] = new Pair(data[i-1].zero + 1, data[i-1].one);
}
else{
data[i] = new Pair(data[i-1].zero, data[i-1].one + 1);
}
}
startAlgorithm();
}
z.flush();
System.exit(0);
}
static class Pair {
int zero, one;
public Pair(int zero, int one) {
this.zero = zero;
this.one = one;
}
}
public static class FastInput {
BufferedReader reader;
StringTokenizer tokenizer;
public FastInput(InputStream stream){
reader = new BufferedReader(new InputStreamReader(stream));
}
public FastInput(String path){
try {
reader = new BufferedReader(new FileReader(path));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tokenizer = null;
}
public String next() {
return nextToken();
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public boolean hasNext(){
try {
return reader.ready();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
public String nextToken() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
String line = null;
try {
line = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (line == null) {
return null;
}
tokenizer = new StringTokenizer(line);
}
return tokenizer.nextToken();
}
public Integer nextInt() {
return Integer.parseInt(nextToken());
}
public Long nextLong() {
return Long.valueOf(nextToken());
}
}
public static class FastOutput extends PrintWriter {
public FastOutput() {
super(new BufferedOutputStream(System.out));
}
}
} | JAVA |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer. | 2 | 9 | import sys
r = sys.stdin.readlines()
M = 10 ** 9 + 7
n, q = r[0].strip().split()
n = int(n)
q = int(q)
s = r[1]
p = [0]
for v in range(n):
p.append(p[v] + int(s[v]))
ans = []
for k in range(q):
a, b = r[k + 2].strip().split()
a = int(a)
b = int(b)
l = b - a + 1
one = p[b] - p[a - 1]
ans.append((pow(2, l, M) - pow(2, l - one, M) + M) % M)
sys.stdout.write("\n".join(map(str, ans))) | PYTHON3 |
Subsets and Splits