src
stringlengths 95
64.6k
| complexity
stringclasses 7
values | problem
stringlengths 6
50
| from
stringclasses 1
value |
---|---|---|---|
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
public class CFFF {
static PrintWriter out;
static final int oo = 987654321;
static final long mod = (long)(1e9)+9;
public static void main(String[] args) {
MScanner sc = new MScanner();
out = new PrintWriter(System.out);
long N = sc.nextLong();
long M = sc.nextLong();
long K = sc.nextLong();
if(M<=N-N/K)
out.println(M);
else{
long ans = (fastModExpo(2,M-(N-N%K)/K*(K-1)-N%K+1,mod)-2)*K+M-(M-(N-N%K)/K*(K-1)-N%K)*K;
out.println((mod+ans)%mod);
}
out.close();
}
static long fastModExpo(int base, long pow, long mod) {
if (pow == 0)
return 1L;
if ((pow & 1) == 1)
return (base*fastModExpo(base, pow - 1,mod))%mod;
long temp = fastModExpo(base, pow / 2, mod);
return (temp*temp)%mod;
}
static class MScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public MScanner() {
stream = System.in;
// stream = new FileInputStream(new File("dec.in"));
}
int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
boolean isEndline(int c) {
return c == '\n' || c == '\r' || c == -1;
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextInt(int N) {
int[] ret = new int[N];
for (int a = 0; a < N; a++)
ret[a] = nextInt();
return ret;
}
int[][] nextInt(int N, int M) {
int[][] ret = new int[N][M];
for (int a = 0; a < N; a++)
ret[a] = nextInt(M);
return ret;
}
long nextLong() {
return Long.parseLong(next());
}
long[] nextLong(int N) {
long[] ret = new long[N];
for (int a = 0; a < N; a++)
ret[a] = nextLong();
return ret;
}
double nextDouble() {
return Double.parseDouble(next());
}
double[] nextDouble(int N) {
double[] ret = new double[N];
for (int a = 0; a < N; a++)
ret[a] = nextDouble();
return ret;
}
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();
}
String[] next(int N) {
String[] ret = new String[N];
for (int a = 0; a < N; a++)
ret[a] = next();
return ret;
}
String nextLine() {
int c = read();
while (isEndline(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndline(c));
return res.toString();
}
String[] nextLine(int N) {
String[] ret = new String[N];
for (int a = 0; a < N; a++)
ret[a] = nextLine();
return ret;
}
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.io.*;
import java.util.Scanner;
/**
* @author pvasilyev
* @since 8/16/13
*/
public class ProblemC {
public static final String FILE_IN = "std.in";
public static final String FILE_OUT = "std.out";
private static boolean debugMode = true;
private static final long MOD = 1000 * 1000 * 1000 + 9;
public static void main(String[] args) throws IOException {
final Scanner reader = new Scanner(new InputStreamReader(debugMode ? System.in : new FileInputStream(FILE_IN)));
final PrintWriter writer = new PrintWriter(debugMode ? System.out : new FileOutputStream(FILE_OUT));
// final long start = System.currentTimeMillis();
solveTheProblem(reader, writer);
// System.out.println(System.currentTimeMillis() - start);
reader.close();
writer.close();
}
private static void solveTheProblem(final Scanner reader, final PrintWriter writer) {
final long n = reader.nextLong();
final long m = reader.nextLong();
final long k = reader.nextLong();
if (n - n/k >= m) {
writer.println(m);
return;
} else {
long sum = 1;
long maxK = m - n + n/k;
sum = fastPow(2, maxK);
sum = 2 * (sum - 1);
sum = sum % MOD;
sum *= k;
sum += m - maxK * k;
writer.println(sum % MOD);
}
}
private static long fastPow(final int exp, final long deg) {
if (deg == 0) {
return 1;
} else if (deg == 1) {
return exp;
} else if (deg % 2 == 0) {
long temp = fastPow(exp, deg / 2);
temp = (temp * temp) % MOD;
return temp;
} else {
long temp = fastPow(exp, deg / 2);
temp = (temp * temp) % MOD;
return (temp * exp) % MOD;
}
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.io.*;
import java.util.*;
public class Quiz {
public static int mod = 1000000009;
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(f.readLine());
long n = Long.parseLong(st.nextToken());
long m = Long.parseLong(st.nextToken());
long k = Long.parseLong(st.nextToken());
long d = n-m;
n -= d*k;
if (n <= 0)
{
System.out.println(m);
return;
}
long sum = (n%k) + d*(k-1);
sum += 2*k*(pow(2,n/k)-1);
sum %= mod;
System.out.println(sum);
}
public static long pow(long a, long n)
{
if (n == 0)
return 1;
long pow = pow(a,n/2);
pow = pow*pow % mod;
if (n % 2 == 1)
pow = pow*a % mod;
return pow;
}
} | logn | 338_A. Quiz | CODEFORCES |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import static java.util.Arrays.*;
public class A {
private static final int mod = (int)1e9+9;
final IOFast io = new IOFast();
long k;
boolean ok(long n, long m, long x) {
long u = k * x;
long val = u;
val += (m - u) / (k - 1) * k;
if((m - u) % (k - 1) == 0) val -= 1;
else val += (m - u) % (k - 1);
return val <= n;
}
long rec(long n, long m, long cur) {
long pow = 1;
long p = 1000;
for(int i = 0; i < p; i++) pow = pow * 2 % mod;
while(true) {
if(ok(n, m, 0)) { return (m + cur) % mod; }
if(!ok(n - p * k, m - p * k, p)) {
n -= p * k;
m -= p * k;
cur = cur * pow % mod;
cur += (pow - 1) * 2 * k % mod;
cur %= mod;
continue;
}
n -= k;
m -= k;
cur += k;
cur = cur * 2 % mod;
// System.err.println(cur);
}
}
public void run() throws IOException {
long n = io.nextLong();
long m = io.nextLong();
k = io.nextLong();
io.out.println(rec(n, m, 0));
if(true) return;
long low = -1, high = m / k + 1;
while(high - low > 1) {
long mid = (low + high) / 2;
if(!ok(n, m, mid)) {
low = mid;
}
else {
high = mid;
}
// System.err.println(mid + " " + (u + (m - u - k) / (k - 1) * k + k - 1 + (m - u) % (k - 1)) + " " + n);
}
long pow = powmod(2, high, mod);
long score = m - high * k;
score = (score + (pow - 1) * 2 * k) % mod;
io.out.println(score);
}
static long powmod(long n, long r, int m) {
long res = 1;
for(; r != 0; r >>>= 1, n = n * n % m) {
if((r&1) == 1) {
res = res * n;
if(res >= m) {
res %= m;
}
}
}
return res;
}
void main() throws IOException {
// IOFast.setFileIO("rle-size.in", "rle-size.out");
try {
run();
}
catch (EndOfFileRuntimeException e) { }
io.out.flush();
}
public static void main(String[] args) throws IOException {
new A().main();
}
static class EndOfFileRuntimeException extends RuntimeException {
private static final long serialVersionUID = -8565341110209207657L; }
static
public class IOFast {
private BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
private PrintWriter out = new PrintWriter(System.out);
void setFileIO(String ins, String outs) throws IOException {
in = new BufferedReader(new FileReader(ins));
out = new PrintWriter(new FileWriter(outs));
}
// private static final int BUFFER_SIZE = 50 * 200000;
private static int pos, readLen;
private static final char[] buffer = new char[1024 * 8];
private static final char[] str = new char[500000*8*2];
private static boolean[] isDigit = new boolean[256];
private static boolean[] isSpace = new boolean[256];
private static boolean[] isLineSep = new boolean[256];
static {
for(int i = 0; i < 10; i++) { isDigit['0' + i] = true; }
isDigit['-'] = true;
isSpace[' '] = isSpace['\r'] = isSpace['\n'] = isSpace['\t'] = true;
isLineSep['\r'] = isLineSep['\n'] = true;
}
public int read() throws IOException {
if(pos >= readLen) {
pos = 0;
readLen = in.read(buffer);
if(readLen <= 0) { throw new EndOfFileRuntimeException(); }
}
return buffer[pos++];
}
public int nextInt() throws IOException {
return Integer.parseInt(nextString());
}
public long nextLong() throws IOException {
return Long.parseLong(nextString());
}
public char nextChar() throws IOException {
while(true) {
final int c = read();
if(!isSpace[c]) { return (char)c; }
}
}
int reads(char[] cs, int len, boolean[] accept) throws IOException {
try {
while(true) {
final int c = read();
if(accept[c]) { break; }
str[len++] = (char)c;
}
}
catch(EndOfFileRuntimeException e) { ; }
return len;
}
public char[] nextLine() throws IOException {
int len = 0;
str[len++] = nextChar();
len = reads(str, len, isLineSep);
try {
if(str[len-1] == '\r') { len--; read(); }
}
catch(EndOfFileRuntimeException e) { ; }
return Arrays.copyOf(str, len);
}
public String nextString() throws IOException {
return new String(next());
}
public char[] next() throws IOException {
int len = 0;
str[len++] = nextChar();
len = reads(str, len, isSpace);
return Arrays.copyOf(str, len);
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextString());
}
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class A {
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter out;
long MOD = 1000000009;
public long mod_add(long n1, long n2){
return (n1 + n2) % MOD;
}
public long mod_time(long n1, long n2){
return (n1 * n2) % MOD;
}
public long mod_power(long a, int k) {
if (k == 0) return 1;
if (k % 2 == 0) return mod_power(a * a % MOD, k / 2);
return a * mod_power(a, k - 1) % MOD;
}
public void solve() throws IOException {
int N = nextInt();
int M = N - nextInt(); //wrong
int K = nextInt();
int full = N/K - M;
if( full < 0){
out.println( N - M );return;
}
long ans = mod_time( K * 2, mod_power(2, full) - 1 );
// out.println( full + ", " + ans );
ans = mod_add(ans, N-M-full*K );
out.println( ans );
}
/**
* @param args
*/
public static void main(String[] args) {
new A().run();
}
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
out = new PrintWriter(System.out);
solve();
reader.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class A {
public static void main(String[] args) throws Exception {
int n=nextInt();
int m=nextInt();
int k=nextInt();
int wa=n-m;
if(n/k<=wa){
System.out.println(m);
}else{
int notFull=wa;
int full=n/k-wa;
long res=1;
int power=full+1;
int mod=1000000009;
long powTwo=2;
while(power>0){
if((power&1)==1){
res=(res*powTwo)%mod;
}
power>>=1;
powTwo=(powTwo*powTwo)%mod;
}
res=(((res-2+mod)%mod)*k)%mod;
res=((res+notFull*(k-1))%mod+n%k)%mod;
System.out.println(res);
}
}
static BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
static StringTokenizer tokenizer = new StringTokenizer("");
static int nextInt() throws Exception {
return Integer.parseInt(next());
}
static double nextDouble() throws Exception {
return Double.parseDouble(next());
}
static String next() throws Exception {
while (true) {
if (tokenizer.hasMoreTokens()) {
return tokenizer.nextToken();
}
String s = br.readLine();
if (s == null) {
return null;
}
tokenizer = new StringTokenizer(s);
}
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.io.*;
import java.util.*;
import java.math.*;
public class A implements Runnable {
static BufferedReader in;
static PrintWriter out;
static StringTokenizer st;
static Random rnd;
final long MODULO = 1000000009;
private void solve() throws IOException {
int moves = nextInt(), rightMoves = nextInt(), sequence = nextInt();
long answer = solveSmart(moves, rightMoves, sequence);
out.println(answer);
// for (int moves = 2; moves <= 50; moves++) {
// for (int rightMoves = 2; rightMoves <= moves; rightMoves++) {
// for (int sequence = 2; sequence <= moves; sequence++) {
// if (solveDumb(moves, rightMoves, sequence) != solveSmart(
// moves, rightMoves, sequence)) {
// out.println(moves + " " + rightMoves + " " + sequence);
// out.flush();
// }
// }
// }
// }
}
// private long solveDumb(int moves, int rightMoves, int sequence) {
// long[][][] d = new long[moves + 1][rightMoves + 1][sequence];
// long inf = Integer.MAX_VALUE;
// for (int i = 0; i <= moves; i++)
// for (int j = 0; j <= rightMoves; j++)
// Arrays.fill(d[i][j], inf);
// d[0][0][0] = 0;
//
// for (int i = 0; i < moves; i++) {
// for (int j = 0; j <= rightMoves; j++) {
// for (int k = 0; k < sequence; k++) {
// // right move
// if (j < rightMoves) {
// // last move
// if (k + 1 == sequence) {
// d[i + 1][j + 1][0] = Math.min(d[i + 1][j + 1][0],
// (d[i][j][k] + 1) * 2);
// } else {
// d[i + 1][j + 1][k + 1] = Math.min(
// d[i + 1][j + 1][k + 1], d[i][j][k] + 1);
// }
// }
//
// // bad move
// d[i + 1][j][0] = Math.min(d[i + 1][j][0], d[i][j][k]);
// }
//
// }
// }
//
// long result = inf;
// for (int i = 0; i < sequence; i++)
// result = Math.min(result, d[moves][rightMoves][i]);
// return result;
// }
private long solveSmart(long moves, long rightMoves, long sequence) {
long fullSequences = moves / sequence;
long canReset = Math.min(fullSequences, moves - rightMoves);
long remainSequences = fullSequences - canReset;
long answer = (rightMoves - remainSequences * sequence)
+ getAnswerSequences(remainSequences, sequence);
answer %= MODULO;
return answer;
}
private long getAnswerSequences(long count, long length) {
long first = (getPow(2, count + 1) - 2) % MODULO;
long result = first * length;
result %= MODULO;
result += MODULO;
result %= MODULO;
return result;
}
private int getPow(int n, long p) {
return BigInteger.valueOf(2)
.modPow(BigInteger.valueOf(p), BigInteger.valueOf(MODULO))
.intValue();
}
public static void main(String[] args) {
new A().run();
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
rnd = new Random();
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
private String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = in.readLine();
if (line == null)
return null;
st = new StringTokenizer(line);
}
return st.nextToken();
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
} | logn | 338_A. Quiz | CODEFORCES |
import java.util.*;
import java.io.*;
public class Quiz
{
public static final int MOD = 1000000009;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
long n = in.nextInt();
long m = in.nextInt();
long k = in.nextInt();
long low = Math.min(n - (k * (n - m)), m);
if(low < 0)
{
low = 0;
}
long result = 0;
if(low >= k)
{
long b = low / k;
result += fastExp(2, b + 1);
result -= 2;
if(result < 0)
{
result += MOD;
}
result *= k;
result %= MOD;
}
result += low % k;
result %= MOD;
result += m - low;
result %= MOD;
// System.out.println(low);
System.out.println(result);
}
public static long fastExp(int x, long pow)
{
if(pow == 0)
{
return 1;
}
long result = fastExp(x, pow / 2);
result *= result;
result %= MOD;
if(pow % 2 == 1)
{
result *= x;
result %= MOD;
}
return result;
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 29);
thread.start();
thread.join();
}
static class TaskAdapter implements Runnable {
@Override
public void run() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastInput in = new FastInput(inputStream);
FastOutput out = new FastOutput(outputStream);
AQuiz solver = new AQuiz();
solver.solve(1, in, out);
out.close();
}
}
static class AQuiz {
int mod = (int) 1e9 + 9;
Power pow = new Power(mod);
public void solve(int testNumber, FastInput in, FastOutput out) {
int n = in.ri();
int m = in.ri();
int k = in.ri();
long mayPut = (long) (n - m) * (k - 1);
if (mayPut >= m) {
out.println(m);
return;
}
long ans = dup(m - mayPut, k);
ans += mayPut;
ans %= mod;
out.println(ans);
}
public long dup(long n, long k) {
long r = n % k;
n -= r;
long m = n / k;
long ans = k * (pow.pow(2, m + 1) - 2);
ans += r;
ans = DigitUtils.mod(ans, mod);
return ans;
}
}
static class FastOutput implements AutoCloseable, Closeable, Appendable {
private static final int THRESHOLD = 32 << 10;
private final Writer os;
private StringBuilder cache = new StringBuilder(THRESHOLD * 2);
public FastOutput append(CharSequence csq) {
cache.append(csq);
return this;
}
public FastOutput append(CharSequence csq, int start, int end) {
cache.append(csq, start, end);
return this;
}
private void afterWrite() {
if (cache.length() < THRESHOLD) {
return;
}
flush();
}
public FastOutput(Writer os) {
this.os = os;
}
public FastOutput(OutputStream os) {
this(new OutputStreamWriter(os));
}
public FastOutput append(char c) {
cache.append(c);
afterWrite();
return this;
}
public FastOutput append(int c) {
cache.append(c);
afterWrite();
return this;
}
public FastOutput append(long c) {
cache.append(c);
afterWrite();
return this;
}
public FastOutput println(int c) {
return append(c).println();
}
public FastOutput println(long c) {
return append(c).println();
}
public FastOutput println() {
return append('\n');
}
public FastOutput flush() {
try {
// boolean success = false;
// if (stringBuilderValueField != null) {
// try {
// char[] value = (char[]) stringBuilderValueField.get(cache);
// os.write(value, 0, cache.length());
// success = true;
// } catch (Exception e) {
// }
// }
// if (!success) {
os.append(cache);
// }
os.flush();
cache.setLength(0);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return this;
}
public void close() {
flush();
try {
os.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public String toString() {
return cache.toString();
}
}
static class FastInput {
private final InputStream is;
private byte[] buf = new byte[1 << 13];
private int bufLen;
private int bufOffset;
private int next;
public FastInput(InputStream is) {
this.is = is;
}
private int read() {
while (bufLen == bufOffset) {
bufOffset = 0;
try {
bufLen = is.read(buf);
} catch (IOException e) {
bufLen = -1;
}
if (bufLen == -1) {
return -1;
}
}
return buf[bufOffset++];
}
public void skipBlank() {
while (next >= 0 && next <= 32) {
next = read();
}
}
public int ri() {
return readInt();
}
public int readInt() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
int val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
}
static interface InverseNumber {
}
static class DigitUtils {
private DigitUtils() {
}
public static int mod(long x, int mod) {
if (x < -mod || x >= mod) {
x %= mod;
}
if (x < 0) {
x += mod;
}
return (int) x;
}
}
static class Power implements InverseNumber {
int mod;
public Power(int mod) {
this.mod = mod;
}
public int pow(int x, long n) {
if (n == 0) {
return 1 % mod;
}
long r = pow(x, n >> 1);
r = r * r % mod;
if ((n & 1) == 1) {
r = r * x % mod;
}
return (int) r;
}
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author coderbd
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public static long MOD = 1000000009L;
public long pow(long n, long p) {
if (p == 0)
return 1L;
if (p == 1)
return n;
long ret = 1L;
if (p % 2L != 0)
ret = n;
long tmp = pow(n, p / 2L);
ret = (ret * tmp) % MOD;
ret = (ret * tmp) % MOD;
return ret;
}
public long func(long n, long k) {
long times = n / k;
long ret = n - times * k;
ret += ((pow(2L, times + 1L) + MOD - 2L) % MOD) * k % MOD;
return ret;
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
long n = in.readLong();
long m = in.readLong();
long k = in.readLong();
long wrong = n - m;
long wow = n / k;
long ans;
if (wrong >= wow)
ans = m;
else
ans = (func(n - wrong * k, k) + (k - 1L) * wrong % MOD) % MOD;
out.printLine(ans);
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
}
catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0L;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.awt.Point;
public class CodeForces {
static boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
private final long MOD = 1000000009;
long power(long a, long b)
{
long res = 1;
while (b > 0) {
if ((b & 1) == 1) {
res *= a;
if (res >= MOD)
res %= MOD;
}
a *= a;
if (a >= MOD)
a %= MOD;
b >>= 1;
}
return res;
}
void runCase(int caseNum) throws IOException {
long n = nextLong();
long m = nextLong();
long k = nextLong();
if (n - m >= n / k) {
System.out.println(m);
return;
}
long res = 0;
long rem = (k - 1) * (n - m);
m -= rem;
long bound = m / k;
res = (power(2, bound + 1) + MOD - 2) % MOD;
res *= k;
res %= MOD;
// for (long i = 0; i < bound; ++i) {
// res += k;
// res <<= 1;
// if (res >= MOD)
// res %= MOD;
// }
res += rem;
res += m % k;
res %= MOD;
System.out.println(res);
}
public static void main(String[] args) throws IOException {
if (ONLINE_JUDGE){
System.out.println();
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}else{
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter(System.out);
//out = new PrintWriter("output.txt");
}
new CodeForces().runIt();
out.flush();
out.close();
return;
}
static BufferedReader in;
private StringTokenizer st;
static PrintWriter out;
static int pos;
static String curInput = "";
String next() throws IOException {
while (!st.hasMoreTokens()) {
String line = in.readLine();
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
void runIt() throws IOException {
st = new StringTokenizer("");
// int N = nextInt();
// for (int i = 0; i < N; i++) {
// runCase(i + 1);
// }
runCase(0);
out.flush();
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
InputReader in = new InputReader(System.in);
int n = in.readInt();
int m = in.readInt();
int k = in.readInt();
long wrong = n - m;
long c = wrong * (k) + k - 1;
long xk = n - c;
if (xk <= 0)
System.out.println((n - wrong) % 1000000009);
else {
long x = (long) Math.ceil(xk / (k * 1.0));
long power = Long.parseLong((BigInteger.valueOf(2).modPow(
BigInteger.valueOf(x + 1), BigInteger.valueOf(1000000009))
.subtract(BigInteger.valueOf(2))) + "");
power += 1000000009;
power %= 1000000009;
long first = (power * k) % 1000000009;
// System.out.println(first);
first += (n - x * k - wrong);
System.out.println(first % 1000000009);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1000];
private int curChar, numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
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 long readLong() {
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 String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuffer buf = new StringBuffer();
int c = read();
while (c != '\n' && c != -1) {
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines)
return readLine();
else
return readLine0();
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import static java.util.Arrays.*;
public class A {
private static final int mod = (int)1e9+9;
final IOFast io = new IOFast();
long k;
long rec(long n, long m, long cur) {
long pow = 1;
long margin = 10;
long p = 1000;
for(int i = 0; i < p; i++) pow = pow * 2 % mod;
while(true) {
if(n + 1 >= (m / (k - 1) * k + m % (k - 1)) || m < k) { return (m + cur) % mod; }
long q = (p + margin) * k;
if(n - q + 1 < ((m - q) / (k - 1) * k + (m - q) % (k - 1)) && m >= q) {
n -= p * k;
m -= p * k;
cur = cur * pow % mod;
cur += (pow - 1) * 2 * k % mod;
cur %= mod;
continue;
}
n -= k;
m -= k;
cur += k;
cur = cur * 2 % mod;
// System.err.println(cur);
}
}
public void run() throws IOException {
long n = io.nextLong();
long m = io.nextLong();
k = io.nextLong();
// io.out.println(rec(n, m, 0));
// if(true) return;
long low = -1, high = m / k + 1;
while(high - low > 1) {
long mid = (low + high) / 2;
long u = mid * k;
if(m < u) { high = mid; continue; }
long val = u;
val += (m - u) / (k - 1) * k;
if((m - u) % (k - 1) == 0) val -= 1;
else val += (m - u) % (k - 1);
if(val > n) {
low = mid;
}
else {
high = mid;
}
// System.err.println(mid + " " + (u + (m - u - k) / (k - 1) * k + k - 1 + (m - u) % (k - 1)) + " " + n);
}
long pow = powmod(2, high, mod);
long score = m - high * k;
score = (score + (pow - 1) * 2 * k) % mod;
io.out.println(score);
}
static long powmod(long n, long r, int m) {
long res = 1;
for(; r != 0; r >>>= 1, n = n * n % m) {
if((r&1) == 1) {
res = res * n;
if(res >= m) {
res %= m;
}
}
}
return res;
}
void main() throws IOException {
// IOFast.setFileIO("rle-size.in", "rle-size.out");
try {
run();
}
catch (EndOfFileRuntimeException e) { }
io.out.flush();
}
public static void main(String[] args) throws IOException {
new A().main();
}
static class EndOfFileRuntimeException extends RuntimeException {
private static final long serialVersionUID = -8565341110209207657L; }
static
public class IOFast {
private BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
private PrintWriter out = new PrintWriter(System.out);
void setFileIO(String ins, String outs) throws IOException {
in = new BufferedReader(new FileReader(ins));
out = new PrintWriter(new FileWriter(outs));
}
// private static final int BUFFER_SIZE = 50 * 200000;
private static int pos, readLen;
private static final char[] buffer = new char[1024 * 8];
private static final char[] str = new char[500000*8*2];
private static boolean[] isDigit = new boolean[256];
private static boolean[] isSpace = new boolean[256];
private static boolean[] isLineSep = new boolean[256];
static {
for(int i = 0; i < 10; i++) { isDigit['0' + i] = true; }
isDigit['-'] = true;
isSpace[' '] = isSpace['\r'] = isSpace['\n'] = isSpace['\t'] = true;
isLineSep['\r'] = isLineSep['\n'] = true;
}
public int read() throws IOException {
if(pos >= readLen) {
pos = 0;
readLen = in.read(buffer);
if(readLen <= 0) { throw new EndOfFileRuntimeException(); }
}
return buffer[pos++];
}
public int nextInt() throws IOException {
return Integer.parseInt(nextString());
}
public long nextLong() throws IOException {
return Long.parseLong(nextString());
}
public char nextChar() throws IOException {
while(true) {
final int c = read();
if(!isSpace[c]) { return (char)c; }
}
}
int reads(char[] cs, int len, boolean[] accept) throws IOException {
try {
while(true) {
final int c = read();
if(accept[c]) { break; }
str[len++] = (char)c;
}
}
catch(EndOfFileRuntimeException e) { ; }
return len;
}
public char[] nextLine() throws IOException {
int len = 0;
str[len++] = nextChar();
len = reads(str, len, isLineSep);
try {
if(str[len-1] == '\r') { len--; read(); }
}
catch(EndOfFileRuntimeException e) { ; }
return Arrays.copyOf(str, len);
}
public String nextString() throws IOException {
return new String(next());
}
public char[] next() throws IOException {
int len = 0;
str[len++] = nextChar();
len = reads(str, len, isSpace);
return Arrays.copyOf(str, len);
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextString());
}
}
}
| logn | 338_A. Quiz | CODEFORCES |
//package cf196;
import java.util.*;
import java.io.*;
public class A {
FastScanner in;
PrintWriter out;
final long mod = (long) 1e9 + 9 ;
public void solve() throws IOException {
long n = in.nextInt();
long m = in.nextInt();
long k = in.nextInt();
long l = n / k;
long c = n - m;
long mul2 = Math.max(0, l - c);
if (mul2 == 0) {
out.println(m);
return;
}
long ans = power(2, mul2 + 1, mod);
ans = (ans + mod - 2) % mod;
ans = (ans * k) % mod;
long z = mul2 * k;
long r = m - z;
ans = (ans + r) % mod;
out.print(ans);
}
public long power(long x, long pow, long mod) {
if (pow == 0) {
return 1;
}
if ((pow % 2) == 0) {
return power(((x * x) % mod), pow / 2, mod);
} else {
return (power(x, pow - 1, mod) * x) % mod;
}
}
public void run() {
try {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
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());
}
}
public static void main(String[] arg) {
new A().run();
}
} | logn | 338_A. Quiz | CODEFORCES |
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputStreamReader in = new InputStreamReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
int MOD = 1000000009;
public void solve(int testNumber, InputStreamReader inSt, PrintWriter out) {
InputReader in = new InputReader(inSt);
long n = in.nextInt();
long m = in.nextInt();
long k = in.nextInt();
long t = find(n, m, k);
long twoPow = binPow(2, (int) t);
twoPow--;
long result = (2 * (k * twoPow % MOD)) % MOD;
result += (m - t * k);
result = result % MOD;
out.println(result);
}
int binPow(int a, int n) {
if (n == 0) {
return 1;
}
if (n % 2 == 1) {
return (int) ((binPow(a, n - 1) * (a+ 0l)) % MOD);
} else {
int b = (binPow(a, n / 2)) % MOD;
return (int) (((b+0l) * b) % MOD);
}
}
long find(long n, long m, long k) {
long l = 0;
long r = m / k;
while (l < r) {
long mid = (l + r) / 2;
long m1 = m - mid * k;
long n1 = n - mid * k;
if (isPossible(n1, m1, k)) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
boolean isPossible(long n, long m, long k) {
long r = m / (k - 1);
long q = m - (k - 1) * r;
if (q == 0) {
return r * (k - 1) + r - 1 <= n;
}
return r * (k - 1) + q + r <= n;
}
class InputReader {
public BufferedReader reader;
private String[] currentArray;
int curPointer;
public InputReader(InputStreamReader inputStreamReader) {
reader = new BufferedReader(inputStreamReader);
}
public String next() {
try {
currentArray = null;
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void nextChars(char[] t) {
try {
currentArray = null;
reader.read(t);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public char nextChar() {
try {
currentArray = null;
return (char) reader.read();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
if ((currentArray == null) || (curPointer >= currentArray.length)) {
try {
currentArray = reader.readLine().split(" ");
} catch (IOException e) {
throw new RuntimeException(e);
}
curPointer = 0;
}
return Integer.parseInt(currentArray[curPointer++]);
}
public long nextLong() {
if ((currentArray == null) || (curPointer >= currentArray.length)) {
try {
currentArray = reader.readLine().split(" ");
} catch (IOException e) {
throw new RuntimeException(e);
}
curPointer = 0;
}
return Long.parseLong(currentArray[curPointer++]);
}
}
}
| logn | 338_A. Quiz | CODEFORCES |
// practice with rainboy
import java.io.*;
import java.util.*;
public class CF338A extends PrintWriter {
CF338A() { super(System.out, true); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF338A o = new CF338A(); o.main(); o.flush();
}
static final int MD = 1000000009;
long power(int a, int k) {
if (k == 0)
return 1;
long p = power(a, k / 2);
p = p * p % MD;
if (k % 2 == 1)
p = p * a % MD;
return p;
}
void main() {
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
int z = n - m;
if (z >= (n + k - 1) / k) {
println(m);
return;
}
int d = (n - z * k) / k;
println(((power(2, d + 1) - 2 + MD) * k + m - d * k) % MD);
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.util.*;
import java.io.*;
public class Template {
public static void main(String[] args) throws IOException {
st = new StringTokenizer(rd.readLine());
n = Long.parseLong(st.nextToken());
m = Long.parseLong(st.nextToken());
k = Long.parseLong(st.nextToken());
long s = n - m;
s = Math.min(s, m / (k - 1));
s = Math.min(s, n / k);
long score = 0;
score = (s * (k - 1))%P;
long n1 = n - k * s, m1 = m - (k - 1) * s;
sc = 0;
// rec(n, m);
// System.out.println(sc);
if (m1 == n1) {
score = (score + full(m1)) % P;
System.out.println(score);
return;
}
score = (score + m1) % P;
System.out.println(score);
}
static long full(long N) {
long x = N / k, r = N - x * k;
long powTwo = powMod(2, x + 1) - 2 + 2*P;
powTwo %= P;
powTwo = (powTwo * k) % P;
powTwo = (powTwo + r) % P;
return powTwo;
}
static long sc = 0;
static void rec(long N, long M){
if(N==M){ sc = (sc + full(N))%P; return; }
if(N>=k && M>=k-1){
sc = (sc + (k-1))%P;
rec(N-k, M-(k-1));
return;
}
sc = (sc + M)%P;
}
static long powMod(long a, long p) {
if (p == 0)
return 1L;
long h = powMod(a, (p >> 1));
h = (h * h) % P;
return p % 2 == 0 ? h : (a * h) % P;
}
static long n, m, k;
static long P = 1000000009;
static StringTokenizer st;
static BufferedReader rd = new BufferedReader(new InputStreamReader(
System.in));
static PrintWriter pw = new PrintWriter(System.out);
}
| logn | 338_A. Quiz | CODEFORCES |
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.StringTokenizer;
public class Quiz {
public static long pow(long base, long power) {
if (power == 0)
return 1;
long half = pow(base, power / 2) % mod;
half *= half;
half %= mod;
if (power % 2 == 1)
half *= base;
return half % mod;
}
static long mod = (long) (1e9 + 9);
public static void main(String[] args) {
InputReader r = new InputReader(System.in);
int n = r.nextInt();
int m = r.nextInt();
int k = r.nextInt();
int buckets = n / k;
int rem = n - buckets * k;
long low = 0, high = buckets, itr = 30;
while (itr-- > 0) {
long mid = (low + high) / 2;
long correct = mid * k + rem + (buckets - mid) * (k - 1);
if (correct < m)
low = mid;
else
high = mid;
}
long pow = (pow(2, high + 1) - 2 + mod) % mod;
pow *= k;
pow %= mod;
long res = m - (high * k) + pow + 10 * mod;
res %= mod;
System.out.println(res);
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public InputReader(FileReader stream) {
reader = new BufferedReader(stream);
tokenizer = null;
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 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 int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.util.*;
import java.io.*;
public class a {
static long mod = 1000000009;
static ArrayList<Integer>[] g;
public static void main(String[] args) throws IOException
{
//Scanner input = new Scanner(new File("input.txt"));
//PrintWriter out = new PrintWriter(new File("output.txt"));
input.init(System.in);
PrintWriter out = new PrintWriter((System.out));
int n = input.nextInt(), m = input.nextInt(), k = input.nextInt();
long border = n-n/k;
if(m<=border) out.println(m);
else
{
long count = m- border;
long first = ((pow(2, count+1) + mod - 2)*k)%mod;
first += m - k*count;
out.println(first%mod);
}
out.close();
}
static long pow(long x, long p)
{
if(p==0) return 1;
if((p&1) > 0)
{
return (x*pow(x, p-1))%mod;
}
long sqrt = pow(x, p/2);
return (sqrt*sqrt)%mod;
}
static long gcd(long a, long b)
{
if(b==0) return a;
return gcd(b, a%b);
}
static class input {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
static long nextLong() throws IOException {
return Long.parseLong( next() );
}
static String nextLine() throws IOException {
return reader.readLine();
}
}
} | logn | 338_A. Quiz | CODEFORCES |
import java.util.List;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author RiaD
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Reader in = new Reader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
private static final long MOD = 1000000009;
public void solve(int testNumber, Reader in, OutputWriter out) {
long answer = 0;
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
long l = -1;
long r = n + 1;
while (l + 1 < r) {
long c = (l + r) / 2;
if(n < c * k || canAchieve(n - c * k, k) >= m - c * k) {
r = c;
}
else
l = c;
}
//out.println(r);
long c = r;
answer = ((IntegerUtils.power(2, c + 1, MOD) - 2 + MOD) % MOD) * k % MOD;
n -= k * c;
m -= k * c;
answer += m;
answer %= MOD;
out.println(answer);
}
private long canAchieve(long n, long k) {
return n - n / k;
}
}
class Reader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public Reader(BufferedReader reader) {
this.reader = reader;
}
public Reader(InputStream stream) {
this(new BufferedReader(new InputStreamReader(stream)));
}
public String nextString() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(readLine());
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextString());
}
private String readLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
class OutputWriter extends PrintWriter {
public OutputWriter(OutputStream out) {
super(out);
}
public OutputWriter(java.io.Writer writer){
super(writer);
}
}
class IntegerUtils {
public static long power(long base, long power, long mod) {
long result = 1 % mod;
base %= mod;
while (power > 0) {
if (power % 2 == 1) {
result *= base;
result %= mod;
}
base *= base;
base %= mod;
power >>= 1;
}
return result;
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
* Date: 23.06.13 at 15:29
*
* @author Nickolay Polyarniy aka PolarNick
*/
public class ProblemA {
private static long MOD = 1000000009;
public void solve() throws Exception {
long n = nextInt();
long m = nextInt();
long k = nextInt();
long tmp = 1024 * 1024;
long res = 0;
long nTmp = n;
long mTmp = m;
while (tmp > 0) {
while (mTmp >= (k - 1) * tmp && nTmp - k * tmp >= mTmp - (k - 1) * tmp) {
nTmp -= k * tmp;
mTmp -= (k - 1) * tmp;
// res = (res + (k - 1) * tmp) % MOD;
}
tmp /= 2;
}
long fullC = mTmp / k;
// out.println("mTmp=" + mTmp + "Full: " + fullC);
long pow2 = getPow(2, fullC + 1, MOD);
res = (((res + pow2 + MOD - 2) % MOD) * k) % MOD;
// out.println("After full: " + res);
mTmp = mTmp % k;
res = (res + mTmp) % MOD;
nTmp = n;
mTmp = m - fullC * k - mTmp;
tmp = 1024 * 1024;
while (tmp > 0) {
while (mTmp >= (k - 1) * tmp && nTmp - k * tmp >= mTmp - (k - 1) * tmp) {
nTmp -= k * tmp;
mTmp -= (k - 1) * tmp;
res = (res + (k - 1) * tmp) % MOD;
}
tmp /= 2;
}
out.println(res);
}
static long[] pows = new long[1000000];
public static long getPow(long base, long pow, long mod) {
if (pow < pows.length && pows[(int) pow] != 0) {
return pows[(int) pow];
}
if (pow == 0) {
pows[0] = 1;
return 1;
}
if (pow == 1) {
pows[1] = base;
return base;
}
long res = getPow(base, pow / 2, mod);
res = (res * res) % mod;
res = (res * getPow(base, pow % 2, mod)) % mod;
if (pow < pows.length) {
pows[(int) pow] = res;
}
return res;
}
public static void main(String[] args) throws Exception {
ProblemA problem = new ProblemA();
problem.solve();
problem.close();
}
BufferedReader in;
PrintWriter out;
String curLine;
StringTokenizer tok;
final String delimeter = " ";
final String endOfFile = "";
public ProblemA(BufferedReader in, PrintWriter out) throws Exception {
this.in = in;
this.out = out;
curLine = in.readLine();
if (curLine == null || curLine == endOfFile) {
tok = null;
} else {
tok = new StringTokenizer(curLine, delimeter);
}
}
public ProblemA() throws Exception {
this(new BufferedReader(new InputStreamReader(System.in)),
new PrintWriter(System.out));
}
public ProblemA(String filename) throws Exception {
this(new BufferedReader(new FileReader(filename + ".in")),
new PrintWriter(filename + ".out"));
}
public boolean hasMore() throws Exception {
if (tok == null || curLine == null) {
return false;
} else {
while (!tok.hasMoreTokens()) {
curLine = in.readLine();
if (curLine == null || curLine.equalsIgnoreCase(endOfFile)) {
tok = null;
return false;
} else {
tok = new StringTokenizer(curLine);
}
}
return true;
}
}
public String nextWord() throws Exception {
if (!hasMore()) {
return null;
} else {
return tok.nextToken();
}
}
public int nextInt() throws Exception {
return Integer.parseInt(nextWord());
}
public long nextLong() throws Exception {
return Long.parseLong(nextWord());
}
public int[] readIntArray(int n) throws Exception {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = nextInt();
}
return res;
}
public void close() throws Exception {
in.close();
out.close();
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class A
{
private static final long MOD = 1000000009L;
public static void main(String [] args) throws IOException
{
Scanner in = new Scanner(System.in);
long n = in.nextInt();
long m = in.nextInt();
long k = in.nextInt();
long w = n-m;
long c = w*k;
if(c >= n)
{
System.out.println(m);
return;
}
long rem = n-c;
long h = rem/k;
long p = power(2, h+1);
p -= 2;
p += MOD;
p %= MOD;
p *= k;
p %= MOD;
long point = p + m - (h*k) % MOD;
point += MOD;
point %= MOD;
System.out.println(point);
}
private static long power(int num, long power)
{
if(power == 0)
return 1;
long res = power(num, power/2);
res = (res*res)%MOD;
if(power % 2 != 0)
res *= num;
res%=MOD;
return res;
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.StringTokenizer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author ffao
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Parser in = new Parser(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
int mod = 1000000009;
public void solve(int testNumber, Parser in, OutputWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int o = m;
m -= n - (n/k);
if (m < 0) m = 0;
long temp = n/k;
long ans;
if (m == 0) ans = 0;
else {
ans = (MathUtils.modpow(2, m+1, mod) + mod - 2) % mod;
ans = (ans * k) % mod;
}
out.println((ans + (o - m*k)) % mod);
}
}
class Parser
{
private BufferedReader din;
private StringTokenizer tokenizer;
public Parser(InputStream in)
{
din = new BufferedReader(new InputStreamReader(in));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(din.readLine());
} catch (Exception e) {
throw new UnknownError();
}
}
return tokenizer.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
}
class OutputWriter extends PrintWriter {
public OutputWriter(Writer out) {
super(out);
}
public OutputWriter(OutputStream out) {
super(out);
}
}
class MathUtils {
public static long modpow(int b, int e, int m) {
if (e == 0) return 1%m;
else if (e == 1) return b%m;
long temp = modpow(b, e/2, m);
temp = (temp * temp) % m;
if (e % 2 == 1) temp = (temp * b) % m;
return temp;
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.util.Scanner;
public class A338 {
public static void main (String args[]){
Scanner in= new Scanner(System.in);
long n = in.nextInt();
long m=in.nextInt();
long k=in.nextInt();
long x = n-m;
long y=n/k;
if(x>=y)
System.out.println(m);
else
{
long t= y-x;
long ans=0;
ans+=k*(pow(t+1)-2);
ans%=1000000009;
ans+=m-t*k;
ans%=1000000009;
if(ans<0)
ans+=1000000009;
System.out.println(ans);
}
}
public static long pow(long m ){
if(m==1)
return 2;
long x = pow(m/2);
x%=1000000009;
x*=x;
if(m%2!=0)
x*=2;
x%=1000000009;
return (x);
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.io.*;
import java.util.*;
public class A {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
void solve() throws IOException {
int tot = nextInt();
int ok = nextInt();
int k = nextInt();
int maxBad = tot / k;
if (tot - maxBad >= ok) {
out.println(ok);
return;
}
int dbl = ok + tot / k - tot;
int dblPoints = pow(2, dbl + 1) - 2;
while (dblPoints < 0)
dblPoints += MOD;
dblPoints = (int)((long)dblPoints * k % MOD);
int rest = ok - dbl * k;
int ans = dblPoints + rest;
if (ans >= MOD)
ans -= MOD;
out.println(ans);
}
static int pow(int a, int b) {
int ret = 1;
while (b != 0) {
if ((b & 1) == 1)
ret = (int)((long)ret * a % MOD);
a = (int)((long)a * a % MOD);
b >>= 1;
}
return ret;
}
static final int MOD = 1000000009;
A() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
public static void main(String[] args) throws IOException {
new A();
}
String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return null;
}
}
return st.nextToken();
}
String nextString() {
try {
return br.readLine();
} catch (IOException e) {
eof = true;
return null;
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
} | logn | 338_A. Quiz | CODEFORCES |
import java.io.*;
import java.util.*;
public class A {
long mod = (long)(1e+9+9);
long pow(long a,long b) {
long mul = a;
long res = 1;
while (b > 0) {
if (b %2 == 1) {
res = (res*mul)%mod;
}
mul = (mul*mul)%mod;
b/=2;
}
return res;
}
void solve() throws IOException {
long n = nextLong();
long m = nextLong();
long k = nextLong();
long l = -1;
long r = m / k;
while (l < r - 1) {
long mid = (l+r)/2;
long leftOk = m - mid*k;
long leftPos = n - mid*k;
long cgroups = (leftOk + (k-2)) / (k-1);
long positions = leftOk+cgroups-1;
if (positions <= leftPos) {
r = mid;
} else {
l = mid;
}
}
long res = pow(2,r+1);
res = (res - 2 + mod) %mod;
res = (res*k) % mod;
res = (res+m-r*k) %mod;
out.println(res);
}
void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
public static void main(String[] args) throws IOException {
new A().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st;
String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String temp = in.readLine();
if (temp == null) {
return null;
}
st = new StringTokenizer(temp);
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.io.*;
import java.util.*;
public class ProblemA {
InputReader in; PrintWriter out;
long power(long a, long b, long mod) {
long ret = 1;
long mul = a;
while (b > 0) {
if (b % 2 == 1) {
ret = (ret * mul % mod);
}
mul = (mul * mul) % mod;
b = b / 2;
}
return ret;
}
void solve() {
long n = in.nextLong();
long m = in.nextLong();
long k = in.nextLong();
long mod = 1000000009;
long x = m - (n - n / k);
if (x <= 0) {
out.println(m);
}
else {
long score = 1;
score = power(2, x + 1, mod);
score = (score + mod - 2) % mod;
// out.println(score);
long ans = ((score * k) + m - x * k + mod) % mod;
out.println(ans);
}
}
ProblemA(){
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
try {
if (oj) {
in = new InputReader(System.in);
out = new PrintWriter(System.out);
}
else {
Writer w = new FileWriter("output.txt");
in = new InputReader(new FileReader("input.txt"));
out = new PrintWriter(w);
}
} catch(Exception e) {
throw new RuntimeException(e);
}
solve();
out.close();
}
public static void main(String[] args){
new ProblemA();
}
}
class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public InputReader(FileReader fr) {
reader = new BufferedReader(fr);
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 int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
} | logn | 338_A. Quiz | CODEFORCES |
import java.util.*;
import java.io.*;
public class A2 {
/*
*/
public static void main(String[] args) throws Exception {
uu.s1();
uu.out.close();
}
public static class uu {
public static BR in = new BR();
public static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
public static boolean bg = true;
public static MOD m1 = new MOD(1000000000+9);
public static long mod = 1000000000+9;
public static void s1() throws Exception {
long n = in.ni();
long m = in.ni();
long k = in.ni();
long lose = n - m;
long aval = m / (k - 1l);
long times1 = Math.min(lose, aval);
long notused = times1 * (k - 1l);
long used = m - notused;
long blocks = used / k;
long left = used % k;
long k1 = 0;
if (blocks != 0){
k1 = m1.pow(2, blocks+1);
k1 = m1.s(k1, 2);
}
long ans = (m1.t(k, k1)+left + notused)%mod;
pn(ans);
}
public static void geom(long f1){
}
public static void s2() throws Exception {
}
public static void s3() throws Exception {
}
private static void pn(Object... o1) {
for (int i = 0; i < o1.length; i++){
if (i!= 0) out.print(" ");
out.print(o1[i]);
}
out.println();
}
public static boolean allTrue(boolean ... l1){
for (boolean e: l1) if (!e) return false;
return true;
}
public static boolean allFalse(boolean ... l1){
for (boolean e: l1) if (e) return false;
return true;
}
}
private static class MOD {
public long mod = -1;
public MOD(long k1) {
mod = k1;
}
public long cl(long n1){
long fin = n1%mod;
if (fin<0) fin+= mod;
return fin;
}
public long s(long n1, long n2) {
long k1 = (n1 - n2) % mod;
if (k1 < 0)
k1 += mod;
return k1;
}
public long t(long n1, long n2) {
long k1 = (n1 * n2) % mod;
if (k1 < 0)
k1 += mod;
return k1;
}
public static long xgcd(long n1, long n2) {
long k1 = n1;
long k2 = n2;
long[] l1 = { 1, 0 };
long[] l2 = { 0, 1 };
for (;;) {
long f1 = k1 / k2;
long f2 = k1 % k2;
if (f2 == 0)
break;
long[] l3 = { 0, 0 };
l3[0] = l1[0] - f1 * l2[0];
l3[1] = l1[1] - f1 * l2[1];
l1 = l2;
l2 = l3;
k1 = k2;
k2 = f2;
}
long fin = l2[1] % n1;
if (fin < 0) {
fin += n1;
}
return fin;
}
public long pow(long n1, long pow) {
if (pow == 0)
return 1;
else if (pow == 1)
return t(1l, n1);
else if ((pow & 1) == 0) {
long half = pow(n1, pow >> 1);
return t(half, half);
} else {
long half = pow(n1, pow >> 1);
return t(half, t(half, n1));
}
}
public long factorial(long k1, long n1) {
long fin = 1;
long q1 = k1;
for (int i = 0; i < n1; i++) {
fin = t(fin, q1);
q1--;
if (q1 <= 0)
break;
}
return cl(fin);
}
}
private static class BR {
BufferedReader k1 = null;
StringTokenizer k2 = null;
public BR() {
k1 = new BufferedReader(new InputStreamReader(System.in));
}
public String nx() throws Exception {
for (;;) {
if (k2 == null || !k2.hasMoreTokens()) {
String temp = k1.readLine();
if (temp == null)
return null;
k2 = new StringTokenizer(temp);
}
else
break;
}
return k2.nextToken();
}
public int ni() throws Exception {
return Integer.parseInt(nx());
}
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class C
{
String line;
StringTokenizer inputParser;
BufferedReader is;
FileInputStream fstream;
DataInputStream in;
String FInput="";
void openInput(String file)
{
if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin
else
{
try{
fstream = new FileInputStream(file);
in = new DataInputStream(fstream);
is = new BufferedReader(new InputStreamReader(in));
}catch(Exception e)
{
System.err.println(e);
}
}
}
void readNextLine()
{
try {
line = is.readLine();
inputParser = new StringTokenizer(line, " ");
//System.err.println("Input: " + line);
} catch (IOException e) {
System.err.println("Unexpected IO ERROR: " + e);
}
}
int NextInt()
{
String n = inputParser.nextToken();
int val = Integer.parseInt(n);
//System.out.println("I read this number: " + val);
return val;
}
String NextString()
{
String n = inputParser.nextToken();
return n;
}
void closeInput()
{
try {
is.close();
} catch (IOException e) {
System.err.println("Unexpected IO ERROR: " + e);
}
}
public void readFInput()
{
for(;;)
{
try
{
readNextLine();
FInput+=line+" ";
}
catch(Exception e)
{
break;
}
}
inputParser = new StringTokenizer(FInput, " ");
}
long NextLong()
{
String n = inputParser.nextToken();
long val = Long.parseLong(n);
return val;
}
public static void main(String [] argv)
{
//String filePath="input.txt";
String filePath=null;
if(argv.length>0)filePath=argv[0];
new C(filePath);
}
final int MOD = 1000000009;
public C(String inputFile)
{
openInput(inputFile);
StringBuilder sb = new StringBuilder();
readNextLine();
int N=NextInt(), M=NextInt(), K=NextInt();
if((N/K)<=(N-M))
{
sb.append(M);
}
else
{
int x=(N/K)-(N-M);
long ret=(pow(2, x) -1 );
ret *=K;
ret%=MOD;
ret *= 2;
ret%=MOD;
/*
ret+=pow(K, x+1);
ret%=MOD;*/
ret+=(M-x*K);
ret%=MOD;
sb.append(ret+"\n");
}
System.out.println(sb);
closeInput();
}
long pow(long b, long exponent)
{
long ret = 1;
while(exponent > 0)
{
if (exponent%2 == 1)
ret = (ret * b) % MOD;
exponent = exponent >> 1;
b = (b * b) % MOD;
}
return ret;
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.math.MathContext;
import java.io.PrintWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public static final long mod = 1000L * 1000L * 1000L + 9L;
public void solve(int testNumber, InputReader in, OutputWriter out) {
long n = in.nextLong();
long m = in.nextLong();
long k = in.nextLong();
long z = n - m;
long left = m - z * (k - 1L);
if (left < 0) left = 0;
long res = IntegerUtlis.pow(2L, left / k, mod) - 1L;
res *= 2L * k;
res %= mod;
res += left % k;
res %= mod;
res += m - left;
res %= mod;
res += mod;
res %= mod;
out.printLine(res);
}
}
class InputReader {
private InputStream stream;
private byte[] buffer = new byte[10000];
private int cur;
private int count;
public InputReader(InputStream stream) {
this.stream = stream;
}
public static boolean isSpace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int read() {
if (count == -1) {
throw new InputMismatchException();
}
try {
if (cur >= count) {
cur = 0;
count = stream.read(buffer);
if (count <= 0)
return -1;
}
} catch (IOException e) {
throw new InputMismatchException();
}
return buffer[cur++];
}
public int readSkipSpace() {
int c;
do {
c = read();
} while (isSpace(c));
return c;
}
public long nextLong() {
long sgn = 1;
int c = readSkipSpace();
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res = res * 10L + (long)(c - '0');
c = read();
} while (!isSpace(c));
res *= sgn;
return res;
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
class IntegerUtlis {
public static long pow(long x, long y, long mod) {
x %= mod;
long res = 1;
while (y > 0) {
if (y % 2 == 1) {
--y;
res = BigInteger.valueOf(res).multiply(BigInteger.valueOf(x)).mod(BigInteger.valueOf(mod)).longValue();
} else {
y /= 2;
x = BigInteger.valueOf(x).multiply(BigInteger.valueOf(x)).mod(BigInteger.valueOf(mod)).longValue();
}
}
return res % mod;
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.io.*;
import java.util.*;
public class Main implements Runnable {
public void _main() throws IOException {
long n = nextLong();
long m = nextLong();
long k = nextLong();
long numBlocks = Math.min(Math.min(n / k, n - m), m / (k - 1));
n -= numBlocks * k;
m -= numBlocks * (k - 1);
long numFullBlocks = m / k;
long rem = m % k;
long res = 0;
res = (res + ((p2(numFullBlocks + 1) + MOD - 2) % MOD) * k) % MOD;
res = (res + rem) % MOD;
res = (res + numBlocks * (k - 1)) % MOD;
out.println(res);
}
final int MOD = 1000000009;
private long p2(long s) {
long res = 1;
long x = 2;
while (s > 0) {
if (s % 2 == 1) {
res = res * x % MOD;
}
x = x * x % MOD;
s /= 2;
}
return res;
}
private BufferedReader in;
private PrintWriter out;
private StringTokenizer st;
private String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String rl = in.readLine();
if (rl == null)
return null;
st = new StringTokenizer(rl);
}
return st.nextToken();
}
private int nextInt() throws IOException {
return Integer.parseInt(next());
}
private long nextLong() throws IOException {
return Long.parseLong(next());
}
private double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public static void main(String[] args) {
Locale.setDefault(Locale.UK);
new Thread(new Main()).start();
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
//in = new BufferedReader(new FileReader("a.in"));
//out = new PrintWriter(new FileWriter("a.out"));
_main();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(202);
}
}
}
| logn | 338_A. Quiz | CODEFORCES |
import static java.lang.Math.*;
import static java.util.Arrays.*;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
new Main().run();
}
StreamTokenizer in;
PrintWriter out;
//deb////////////////////////////////////////////////
public static void deb(String n, Object n1) {
System.out.println(n + " is : " + n1);
}
public static void deb(int[] A) {
for (Object oo : A) {
System.out.print(oo + " ");
}
System.out.println("");
}
public static void deb(long[] A) {
for (Object oo : A) {
System.out.print(oo + " ");
}
System.out.println("");
}
public static void deb(BigInteger[] A) {
for (Object oo : A) {
System.out.print(oo + " ");
}
System.out.println("");
}
public static void deb(int[][] A) {
for (int i = 0; i < A.length; i++) {
for (Object oo : A[i]) {
System.out.print(oo + " ");
}
System.out.println("");
}
}
public static void deb(long[][] A) {
for (int i = 0; i < A.length; i++) {
for (Object oo : A[i]) {
System.out.print(oo + " ");
}
System.out.println("");
}
}
public static void deb(String[][] A) {
for (int i = 0; i < A.length; i++) {
for (Object oo : A[i]) {
System.out.print(oo + " ");
}
System.out.println("");
}
}
/////////////////////////////////////////////////////////////
int nextInt() throws IOException {
in.nextToken();
return (int) in.nval;
}
long nextLong() throws IOException {
in.nextToken();
return (long) in.nval;
}
class Pair<X, Y> {
public X x;
public Y y;
public Pair(X x, Y y) {
this.x = x;
this.y = y;
}
public void setX(X x) {
this.x = x;
}
public void setY(Y y) {
this.y = y;
}
}
boolean inR(int x, int y) {
return (x >= 0) && (x < nn) && (y >= 0) && (y < nn);
}
static int nn;
void run() throws IOException {
// in = new StreamTokenizer(new BufferedReader(new FileReader("circles.in")));
// out = new PrintWriter(new FileWriter("circles.out"));
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(new OutputStreamWriter(System.out));
solve();
out.flush();
}
static long MOD=1000000009;
static long modPow(long a, int pow) {
long res = 1;
while (pow > 0) {
if ((pow & 1) != 0) {
res = res * a % MOD;
}
pow >>= 1;
a = a * a % MOD;
}
return res;
}
void solve() throws IOException {
// BufferedReader re= new BufferedReader(new FileReader("C:\\Users\\ASELA\\Desktop\\A.in"));
// BufferedReader re = new BufferedReader(new InputStreamReader(System.in));
int n=nextInt(),m=nextInt(),k=nextInt();
int an=(n/k)*(k-1)+n%k;
long ans=0;
if(an>=m){
System.out.println(m);
return;
}
int rem=m-an;
ans=modPow(2, rem+1)-2;
ans*=k;
ans+=m-rem*k;
ans%=MOD;
// System.out.println("sjkd"+rem);
if(ans<0)ans+=MOD;
System.out.println(ans);
}
} | logn | 338_A. Quiz | CODEFORCES |
import java.util.Scanner;
import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author BSRK Aditya
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, Scanner in, PrintWriter out) {
long numQuestions = in.nextInt();
long numCorrectlyAnsweredQuestions = in.nextInt();
long sizeForDoublingScore = in.nextInt();
long score = 0;
long numIncorrectlyAnsweredQuestions = numQuestions - numCorrectlyAnsweredQuestions;
long numDoublings = Math.max(numQuestions / sizeForDoublingScore - numIncorrectlyAnsweredQuestions, 0);
score += 2*sizeForDoublingScore*Long.parseLong(new BigInteger("2").modPow(new BigInteger(String.valueOf(numDoublings)), new BigInteger("1000000009")).subtract(BigInteger.ONE).toString());
score += numCorrectlyAnsweredQuestions - sizeForDoublingScore*numDoublings;
score %= 1000000009;
out.println(score);
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
public class A {
private long pow(long num, long pow, long mod) {
if (pow <= 0) {
return 1;
}
if ((pow & 1) != 0) {
return (num * pow(num, pow-1, mod)) % mod;
}
else {
long tmp = pow(num, pow>>1, mod) % mod;
return (tmp*tmp)%mod;
}
}
public void run() {
long MOD = 1000000009;
long n = nextInt();
long m = nextInt();
long k = nextInt();
long critical = n/k;
if (n-critical >= m) {
out.println(m);
}
else {
long doubles = m - (n-critical);
long ans = (pow(2, doubles + 1, MOD) - 2 + MOD)%MOD;
ans = (ans * k)%MOD;
ans = (ans + (m-(doubles*k)))%MOD;
out.println(ans);
}
out.flush();
}
private static BufferedReader br = null;
private static StringTokenizer stk = null;
private static PrintWriter out = null;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
(new A()).run();
}
private void loadLine() {
try {
stk = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
private int nextInt() {
while (stk==null || !stk.hasMoreElements()) loadLine();
return Integer.parseInt(stk.nextToken());
}
private long nextLong() {
while (stk==null || !stk.hasMoreElements()) loadLine();
return Long.parseLong(stk.nextToken());
}
private double nextDouble() {
while (stk==null || !stk.hasMoreElements()) loadLine();
return Double.parseDouble(stk.nextToken());
}
private String nextWord() {
while (stk==null || !stk.hasMoreElements()) loadLine();
return (stk.nextToken());
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.util.*;
public class Quiz{
static int MOD = (int)1e9 + 9;
public static void main(String[] args){
Scanner reader = new Scanner(System.in);
long n = reader.nextInt();
long m = reader.nextInt();
long k = reader.nextInt();
long r = (n + k - 1)/k;
long longDrops = n%k;
if(longDrops == 0){
long d = m - (r * (k-1));
if(d <= 0){
System.out.println(m);
return;
}
long sum = (fastExpo(2,d+1)-2) * k + (m - d*k);
System.out.println((sum+MOD)%MOD);
}else{
long d = (m-longDrops*r) - (r-1)*(k-longDrops-1);
if(d <= 0){
System.out.println(m);
return;
}
long sum = (fastExpo(2,d+1)-2) * k + (m - d*k);
System.out.println((sum+MOD)%MOD);
}
}
public static long fastExpo(long b, long p){
if(p == 0)
return 1;
if(p % 2 == 1)
return (b * fastExpo(b, p-1))%MOD;
long x = fastExpo(b, p/2);
return (x * x)%MOD;
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class cf337c {
static long mod,n,m,k;
public static void main(String[] args) {
FastIO in = new FastIO(), out = in;
n = in.nextLong();
m = in.nextLong();
k = in.nextLong();
mod = (long)1e9 + 9;
long x = m - (n-n%k)/k * (k-1) - n%k;
if(x < 0) x = 0;
long ans = (pow(2,x+1)-2)*k + m-x*k;
ans = ((ans%mod)+mod)%mod;
out.println(ans);
out.close();
}
static long pow(long x, long p) {
if(p == 0) return 1%mod;
long ans = pow(x,p/2);
ans = (ans*ans)%mod;
if(p%2 == 1) ans = (ans*x)%mod;
return ans;
}
static class FastIO extends PrintWriter {
BufferedReader br;
StringTokenizer st;
public FastIO() {
this(System.in,System.out);
}
public FastIO(InputStream in, OutputStream out) {
super(new BufferedWriter(new OutputStreamWriter(out)));
br = new BufferedReader(new InputStreamReader(in));
scanLine();
}
public void scanLine() {
try {
st = new StringTokenizer(br.readLine().trim());
} catch(Exception e) {
throw new RuntimeException(e.getMessage());
}
}
public int numTokens() {
if(!st.hasMoreTokens()) {
scanLine();
return numTokens();
}
return st.countTokens();
}
public String next() {
if(!st.hasMoreTokens()) {
scanLine();
return next();
}
return st.nextToken();
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.math.BigInteger;
import java.util.*;
public class A {
private static Scanner in;
final int M = 1000000009;
public void run() {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int z = n - m;
if (z >= n / k) {
System.out.println(m);
return;
}
int f = n - k * z;
int ans = BigInteger.ONE.shiftLeft(f / k + 1).remainder(BigInteger.valueOf(M)).intValue();
System.out.println(((ans + M - 2L) * k + (f % k + (k - 1) * z)) % M);
}
public static void main(String[] args) {
Locale.setDefault(Locale.US);
in = new Scanner(System.in);
new A().run();
in.close();
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.io.*;
import java.util.*;
public class CF {
long mod = (long) 1e9 + 9;
class Pair {
long a, b;
public Pair(long a, long b) {
super();
this.a = a % mod;
this.b = b % mod;
}
}
int k;
long pow(long n, long k) {
if (k == 0)
return 1;
long m1 = pow(n, k / 2);
m1 = (m1 * m1) % mod;
if (k % 2 != 0)
m1 = (m1 * n) % mod;
return m1;
}
long st(int n, int m, int k) {
int parts = n / k;
int used = n - m;
if (parts > n - m) {
long cur = 0;
int counter = 0;
int need = parts - (n - m);
for (int i = 1; i <= n; i++) {
if (counter + 1 == k && need <= 0) {
counter = 0;
used--;
} else {
counter++;
cur++;
if (counter == k) {
counter = 0;
cur = (cur * 2) % mod;
need--;
}
}
}
if (used < 0)
throw new AssertionError();
return cur;
} else {
return m;
}
}
long mysol(int n, int m, int k) {
this.k = k;
int parts = n / k;
if (parts > n - m) {
long ost = n - (n - m) * k;
long power = ost / k;
long res = pow(2, power + 1);
long cur = ((res - 2 + mod) % mod) * k;
cur %= mod;
cur += Math.max(0, m - power * k);
cur %= mod;
return cur;
} else {
return m;
}
}
void realSolve() throws IOException {
int n = in.nextInt();
int m = in.nextInt();
k = in.nextInt();
out.println(mysol(n, m, k));
/*Random rnd = new Random(123);
for (int t = 0; t < 10000; t++) {
System.err.println(t);
int n = rnd.nextInt(100) + 2;
int m = rnd.nextInt(n + 1);
int k = rnd.nextInt(n - 1) + 2;
if (t == 16) {
System.err.println("!");
}
long r1 = mysol(n, m, k);
long r2 = st(n, m, k);
if (r1 != r2)
throw new AssertionError(r1 + " " + r2);
}*/
}
private class InputReader {
StringTokenizer st;
BufferedReader br;
public InputReader(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public InputReader(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String next() {
while (st == null || !st.hasMoreElements()) {
String s;
try {
s = br.readLine();
} catch (IOException e) {
return null;
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
boolean hasMoreElements() {
while (st == null || !st.hasMoreElements()) {
String s;
try {
s = br.readLine();
} catch (IOException e) {
return false;
}
st = new StringTokenizer(s);
}
return st.hasMoreElements();
}
long nextLong() {
return Long.parseLong(next());
}
}
InputReader in;
PrintWriter out;
void solveIO() throws IOException {
in = new InputReader(System.in);
out = new PrintWriter(System.out);
realSolve();
out.close();
}
void solve() throws IOException {
in = new InputReader(new File("input.txt"));
out = new PrintWriter(new File("output.txt"));
realSolve();
out.close();
}
public static void main(String[] args) throws IOException {
new CF().solveIO();
}
} | logn | 338_A. Quiz | CODEFORCES |
import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
public class A{
Scanner sc=new Scanner(System.in);
int INF=1<<28;
double EPS=1e-9;
int mod=(int)1e9+9;
long n, m, k;
void run(){
n=sc.nextLong();
m=sc.nextLong();
k=sc.nextLong();
solve();
}
void solve(){
long ans=0;
long s=n-m;
long remain=max(n-s*k, 0);
// debug("remain", remain);
ans=m-remain;
// debug("ans", ans);
long r=remain%k;
ans=(ans+r)%mod;
remain-=r;
// debug("remain2", remain);
long a=remain/k;
long add=(powMod(2, a, mod)-1)*k%mod*2%mod;
// debug("add", add);
ans=(ans+add)%mod;
// debug(ans);
println(ans+"");
}
long powMod(long x, long k, long mod){
if(k==0){
return 1%mod;
}else if(k%2==0){
return powMod(x*x%mod, k/2, mod);
}else{
return x*powMod(x, k-1, mod)%mod;
}
}
void println(String s){
System.out.println(s);
}
void print(String s){
System.out.print(s);
}
void debug(Object... os){
System.err.println(Arrays.deepToString(os));
}
public static void main(String[] args){
Locale.setDefault(Locale.US);
new A().run();
}
}
| logn | 338_A. Quiz | CODEFORCES |
//package round196;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class A {
InputStream is;
PrintWriter out;
String INPUT = "";
public static long pow(long a, long n, long mod)
{
// a %= mod;
long ret = 1;
int x = 63-Long.numberOfLeadingZeros(n);
for(;x >= 0;x--){
ret = ret * ret % mod;
if(n<<63-x<0)ret = ret * a % mod;
}
return ret;
}
void solve()
{
int n = ni(), m = ni(), K = ni();
if(m <= n/K*(K-1)+n%K){
out.println(m);
}else{
int mod = 1000000009;
int f = m - (n/K*(K-1)+n%K);
out.println(((pow(2, f+1, mod) + mod - 2) * K + (m - f*K)) % mod);
}
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new A().run(); }
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| logn | 338_A. Quiz | CODEFORCES |
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.StringTokenizer;
public class C {
private static BufferedReader in;
private static StringTokenizer st;
private static PrintWriter out;
public static void main(String[] args) throws NumberFormatException, IOException {
in = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer("");
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n = nextInt();
int m = nextInt();
int k = nextInt();
int mod = (int) (1e9+9);
int correct = n - n / k;
int carry = n % k;
long ans;
if(correct >= m){
ans = m;
}else{
m -= correct;
int block = n / k;
BigInteger pow = BigInteger.valueOf(2).modPow(BigInteger.valueOf(m + 1), BigInteger.valueOf(mod));
ans = (pow.longValue() - 2 + mod) % mod;
ans = (ans * (long) k) % mod;
ans = (ans + (long)(block - m)* (long)(k-1) + carry) % mod;
}
System.out.println(ans);
}
static String next() throws IOException{
while(!st.hasMoreTokens()){
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
static int nextInt() throws NumberFormatException, IOException{
return Integer.parseInt(next());
}
static long nextLong() throws NumberFormatException, IOException{
return Long.parseLong(next());
}
static double nextDouble() throws NumberFormatException, IOException{
return Double.parseDouble(next());
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.io.*;
import java.util.*;
public class History {
static final int INF = (int)1E9;
static final double EPS = 1E-9;
static final long MOD = INF + 9;
static long powmod(long p) {
long res = 1;
long d = 2;
while (p > 0) {
if (p % 2 == 1) {
res = (res * d) % MOD;
p--;
}
else {
d = (d * d) % MOD;
p /= 2;
}
}
return res % MOD;
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
long n = in.nextLong();
long m = in.nextLong();
long k = in.nextLong();
long ans = 0;
long t = (k - 1) * (n - m);
if (t <= m) {
n -= k * (n - m);
long g = n / k;
ans = 2 * k * (powmod(g) - 1) + n % k;
ans = (ans + t) % MOD;
}
else {
ans = m;
}
System.out.println(ans % MOD);
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
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 int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
};
} | logn | 338_A. Quiz | CODEFORCES |
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
/**
* Created by hama_du on 15/09/10.
*/
public class A {
private static final long MOD = 1000000009;
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
long n = in.nextInt();
long correct = in.nextInt();
long k = in.nextInt();
long wrong = n - correct;
long set = wrong * k + k - 1;
if (set >= n) {
out.println(correct);
} else {
long needExtraCorrect = n - (wrong * k + k - 1);
long firstSet = needExtraCorrect + k - 1;
long otherSet = correct - firstSet;
long firstDouble = firstSet / k;
otherSet += firstSet % k;
long[][] mat = new long[][]{ {2, 2*k}, {0, 1}};
long[][] A = pow(mat, firstDouble, MOD);
long score = (A[0][1] + otherSet) % MOD;
out.println(score);
}
out.flush();
}
public static long[][] pow(long[][] a, long n, long mod) {
long i = 1;
long[][] res = E(a.length);
long[][] ap = mul(E(a.length), a, mod);
while (i <= n) {
if ((n & i) >= 1) {
res = mul(res, ap, mod);
}
i *= 2;
ap = mul(ap, ap, mod);
}
return res;
}
public static long[][] E(int n) {
long[][] a = new long[n][n];
for (int i = 0 ; i < n ; i++) {
a[i][i] = 1;
}
return a;
}
public static long[][] mul(long[][] a, long[][] b, long mod) {
long[][] c = new long[a.length][b[0].length];
if (a[0].length != b.length) {
System.err.print("err");
}
for (int i = 0 ; i < a.length ; i++) {
for (int j = 0 ; j < b[0].length ; j++) {
long sum = 0;
for (int k = 0 ; k < a[0].length ; k++) {
sum = (sum + a[i][k] * b[k][j]) % mod;
}
c[i][j] = sum;
}
}
return c;
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int next() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public char nextChar() {
int c = next();
while (isSpaceChar(c))
c = next();
if ('a' <= c && c <= 'z') {
return (char) c;
}
if ('A' <= c && c <= 'Z') {
return (char) c;
}
throw new InputMismatchException();
}
public String nextToken() {
int c = next();
while (isSpaceChar(c))
c = next();
StringBuilder res = new StringBuilder();
do {
res.append((char) c);
c = next();
} while (!isSpaceChar(c));
return res.toString();
}
public int nextInt() {
int c = next();
while (isSpaceChar(c))
c = next();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = next();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c-'0';
c = next();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = next();
while (isSpaceChar(c))
c = next();
long sgn = 1;
if (c == '-') {
sgn = -1;
c = next();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c-'0';
c = next();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static void debug(Object... o) {
System.err.println(Arrays.deepToString(o));
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.io.*;
import java.util.StringTokenizer;
public class A {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void solve() throws IOException {
final int mod = 1000*1000*1000+9;
long n = readInt();
long m = readInt();
long k = readInt();
long fail = n-m;
long posl = n / k ;
if(n % k != 0) {
posl++;
}
if(posl <= fail) {
out.println(m);
} else {
long d = fail - posl;
long res = (k-1) * fail;
m -= (k-1) * fail;
long z = m / k;
res += m % k;
res %= mod;
long x = binpow(2, z+1, mod);
x -= 2;
x += mod;
x %= mod;
x *= k;
res += x;
res %= mod;
out.println(res);
}
}
long binpow (long a, long n, long mod) {
long res = 1;
while (n != 0)
if ((n & 1) != 0) {
res *= a;
res = res % mod;
--n;
}
else {
a *= a;
a = a % mod;
n >>= 1;
}
return res;
}
void init() throws FileNotFoundException {
if (ONLINE_JUDGE) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
int[] readArr(int n) throws IOException {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = readInt();
}
return res;
}
long[] readArrL(int n) throws IOException {
long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = readLong();
}
return res;
}
public static void main(String[] args) {
new A().run();
}
public void run() {
try {
long t1 = System.currentTimeMillis();
init();
solve();
out.close();
long t2 = System.currentTimeMillis();
System.err.println("Time = " + (t2 - t1));
} catch (Exception e) {
e.printStackTrace(System.err);
System.exit(-1);
}
}
} | logn | 338_A. Quiz | CODEFORCES |
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.StringTokenizer;
public class A {
static StringTokenizer st;
static BufferedReader in;
static PrintWriter pw;
public static void main(String[] args) throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
// long a = 2;
// int q = nextInt();
// long sum = a;
// int s = q;
// for (int i = 2; i <= s; i++) {
// a = a*2+2;
// sum += a;
// }
// System.out.println(sum);
// System.out.println((4*((long)Math.pow(2, s)-1)-2*s));
int n = nextInt();
int m = nextInt();
int k = nextInt();
long t = (long)(n-m) * k;
int mod = (int) (1e9+9);
long ans = 0;
int x = m / (k-1);
if (m % (k-1) != 0)
x++;
if (n-m < x-1) {
int s = (int) (n - t);
int cnt = s / k;
ans = BigInteger.valueOf(2).modPow(BigInteger.valueOf(cnt+1), BigInteger.valueOf(mod)).longValue();
ans = (ans-2+mod) % mod;
// ans = ans * 4 % mod;
// ans = (ans-2*cnt+2*mod) % mod;
ans = ans * k % mod;
ans = (ans+(long)(k-1) * (n-m) % mod) % mod;
ans = (ans+s % k) % mod;
}
else
ans = m;
System.out.println(ans);
pw.close();
}
private static int nextInt() throws IOException{
return Integer.parseInt(next());
}
private static long nextLong() throws IOException{
return Long.parseLong(next());
}
private static double nextDouble() throws IOException{
return Double.parseDouble(next());
}
private static String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.util.*;
import java.io.*;
import java.awt.Point;
import java.math.BigDecimal;
import java.math.BigInteger;
import static java.lang.Math.*;
// Solution is at the bottom of code
public class _____A implements Runnable{
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
OutputWriter out;
StringTokenizer tok = new StringTokenizer("");
public static void main(String[] args){
new Thread(null, new _____A(), "", 128 * (1L << 20)).start();
}
/////////////////////////////////////////////////////////////////////
void init() throws FileNotFoundException{
Locale.setDefault(Locale.US);
if (ONLINE_JUDGE){
in = new BufferedReader(new InputStreamReader(System.in));
out = new OutputWriter(System.out);
}else{
in = new BufferedReader(new FileReader("input.txt"));
out = new OutputWriter("output.txt");
}
}
////////////////////////////////////////////////////////////////
long timeBegin, timeEnd;
void time(){
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
void debug(Object... objects){
if (ONLINE_JUDGE){
for (Object o: objects){
System.err.println(o.toString());
}
}
}
/////////////////////////////////////////////////////////////////////
public void run(){
try{
timeBegin = System.currentTimeMillis();
Locale.setDefault(Locale.US);
init();
solve();
out.close();
time();
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
/////////////////////////////////////////////////////////////////////
String delim = " ";
String readString() throws IOException{
while(!tok.hasMoreTokens()){
try{
tok = new StringTokenizer(in.readLine());
}catch (Exception e){
return null;
}
}
return tok.nextToken(delim);
}
String readLine() throws IOException{
return in.readLine();
}
/////////////////////////////////////////////////////////////////
final char NOT_A_SYMBOL = '\0';
char readChar() throws IOException{
int intValue = in.read();
if (intValue == -1){
return NOT_A_SYMBOL;
}
return (char) intValue;
}
char[] readCharArray() throws IOException{
return readLine().toCharArray();
}
/////////////////////////////////////////////////////////////////
int readInt() throws IOException{
return Integer.parseInt(readString());
}
int[] readIntArray(int size) throws IOException{
int[] array = new int[size];
for (int index = 0; index < size; ++index){
array[index] = readInt();
}
return array;
}
///////////////////////////////////////////////////////////////////
long readLong() throws IOException{
return Long.parseLong(readString());
}
long[] readLongArray(int size) throws IOException{
long[] array = new long[size];
for (int index = 0; index < size; ++index){
array[index] = readLong();
}
return array;
}
////////////////////////////////////////////////////////////////////
double readDouble() throws IOException{
return Double.parseDouble(readString());
}
double[] readDoubleArray(int size) throws IOException{
double[] array = new double[size];
for (int index = 0; index < size; ++index){
array[index] = readDouble();
}
return array;
}
/////////////////////////////////////////////////////////////////////
Point readPoint() throws IOException{
int x = readInt();
int y = readInt();
return new Point(x, y);
}
Point[] readPointArray(int size) throws IOException{
Point[] array = new Point[size];
for (int index = 0; index < size; ++index){
array[index] = readPoint();
}
return array;
}
/////////////////////////////////////////////////////////////////////
List<Integer>[] readGraph(int vertexNumber, int edgeNumber)
throws IOException{
List<Integer>[] graph = new List[vertexNumber];
for (int index = 0; index < vertexNumber; ++index){
graph[index] = new ArrayList<Integer>();
}
while (edgeNumber-- > 0){
int from = readInt() - 1;
int to = readInt() - 1;
graph[from].add(to);
graph[to].add(from);
}
return graph;
}
/////////////////////////////////////////////////////////////////////
class OutputWriter extends PrintWriter{
final int DEFAULT_PRECISION = 12;
int precision;
String format, formatWithSpace;
{
precision = DEFAULT_PRECISION;
format = createFormat(precision);
formatWithSpace = format + " ";
}
public OutputWriter(OutputStream out) {
super(out);
}
public OutputWriter(String fileName) throws FileNotFoundException {
super(fileName);
}
public int getPrecision() {
return precision;
}
public void setPrecision(int precision) {
this.precision = precision;
format = createFormat(precision);
formatWithSpace = format + " ";
}
private String createFormat(int precision){
return "%." + precision + "f";
}
@Override
public void print(double d){
printf(format, d);
}
public void printWithSpace(double d){
printf(formatWithSpace, d);
}
public void printAll(double...d){
for (int i = 0; i < d.length - 1; ++i){
printWithSpace(d[i]);
}
print(d[d.length - 1]);
}
@Override
public void println(double d){
printlnAll(d);
}
public void printlnAll(double... d){
printAll(d);
println();
}
}
/////////////////////////////////////////////////////////////////////
int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int[][] steps8 = {
{-1, 0}, {1, 0}, {0, -1}, {0, 1},
{-1, -1}, {1, 1}, {1, -1}, {-1, 1}
};
boolean check(int index, int lim){
return (0 <= index && index < lim);
}
/////////////////////////////////////////////////////////////////////
boolean checkBit(int mask, int bitNumber){
return (mask & (1 << bitNumber)) != 0;
}
/////////////////////////////////////////////////////////////////////
long md = (1000 * 1000 * 1000 + 9);
void solve() throws IOException{
int n = readInt();
int m = readInt();
int k = readInt();
long count = n / k;
long mod = n % k;
long maxM = count * (k - 1) + mod;
if (maxM >= m) {
out.println(m % md);
return;
}
long d = m - maxM;
long mul = (binpow(2, d) - 1 + md) % md * 2 % md;
long ans = (mul * k) % md;
ans = (ans + ((count - d) * (k - 1) % md + md) % md + mod) % md;
out.println(ans);
}
long binpow(long a, long n) {
if (n == 0) return 1;
if ((n & 1) == 0) {
long b = binpow(a, n >> 1);
return (b * b) % md;
} else {
return binpow(a, n - 1) * a % md;
}
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.math.BigInteger;
import java.util.*;
public class A {
private static Scanner in;
final int M = 1000000009;
public void run() {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int z = n - m;
if (z >= n / k) {
System.out.println(m);
return;
}
int f = n - k * z;
int last = f % k + (k - 1) * z;
f /= k;
int ans = BigInteger.ONE.shiftLeft(f + 1).remainder(BigInteger.valueOf(M)).intValue();
System.out.println(((ans + M - 2L) * k + last) % M);
}
public static void main(String[] args) {
Locale.setDefault(Locale.US);
in = new Scanner(System.in);
new A().run();
in.close();
}
}
| logn | 338_A. Quiz | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class CFC {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
private static final long MOD = 1000L * 1000L * 1000L + 7;
private static final int[] dx = {0, -1, 0, 1};
private static final int[] dy = {1, 0, -1, 0};
private static final String yes = "Yes";
private static final String no = "No";
void solve() throws IOException {
long x = nextLong();
long k = nextLong();
if (x == 0) {
outln(0);
return;
}
x %= MOD;
long two = powMod(2, k, MOD);
long res = two;
res *= 2;
res %= MOD;
res *= x;
res %= MOD;
res -= two - 1;
while (res < 0) {
res += MOD;
}
while (res >= MOD) {
res -= MOD;
}
outln(res);
}
public long powMod(long N, long M, long MOD){//N^M % MOD
if(M == 0L)
return 1L;
long[] hp = new long[64];
boolean[] bp = new boolean[64];
hp[0] = N;
for(int i = 1; i < hp.length; i++) {
hp[i] = (hp[i - 1] * hp[i - 1]) % MOD;
}
for(int j = 0; j < hp.length; j++) {
if((M & (1L << j)) != 0)
bp[j] = true;
}
long res = 1;
for(int i = 0;i < bp.length; i++){
if(bp[i]) {
res = (res * hp[i]) % MOD;
}
}
return res;
}
void shuffle(int[] a) {
int n = a.length;
for(int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int tmp = a[i];
a[i] = a[r];
a[r] = tmp;
}
}
long gcd(long a, long b) {
while(a != 0 && b != 0) {
long c = b;
b = a % b;
a = c;
}
return a + b;
}
private void outln(Object o) {
out.println(o);
}
private void out(Object o) {
out.print(o);
}
public CFC() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
public static void main(String[] args) throws IOException {
new CFC();
}
public long[] nextLongArr(int n) throws IOException{
long[] res = new long[n];
for(int i = 0; i < n; i++)
res[i] = nextLong();
return res;
}
public int[] nextIntArr(int n) throws IOException {
int[] res = new int[n];
for(int i = 0; i < n; i++)
res[i] = nextInt();
return res;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return null;
}
}
return st.nextToken();
}
public String nextString() {
try {
return br.readLine();
} catch (IOException e) {
eof = true;
return null;
}
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.util.Scanner;
public class R489C {
static long MOD=(long)1e9+7;
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
long n=scan.nextLong(), k=scan.nextLong();
if(n==0) {
System.out.println(0);
return;
}
long x=2*n-1;
long e=exp(2,k);
System.out.println((x%MOD*e%MOD+1)%MOD);
}
public static long exp(long x, long e) {
long res=1;
while (e>0) {
if(e%2==1) res=(res*x)%MOD;
e/=2;
x=(x*x)%MOD;
}
return res;
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.*;
import java.util.*;
public class Main {
FastReader scn;
PrintWriter out;
String INPUT = "";
void solve() {
long n = scn.nextLong(), k = scn.nextLong(), mod = (int)1e9 + 7;
if(n == 0) {
out.println(0);
return;
}
n %= mod;
long x = (pow(2, k + 1, mod) * n) % mod;
long y = (pow(2, k, mod) + mod - 1) % mod;
long ans = ((x - y) % mod + mod) % mod;
out.println(ans);
}
long pow(long a, long x, long m) {
if(x == 0) {
return 1;
}
long p = pow(a, x / 2, m);
p *= p;
p %= m;
if(x % 2 == 1) {
p *= a;
p %= m;
}
return p;
}
long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
void run() throws Exception {
boolean onlineJudge = System.getProperty("ONLINE_JUDGE") != null;
out = new PrintWriter(System.out);
scn = new FastReader(onlineJudge);
long time = System.currentTimeMillis();
solve();
out.flush();
if (!onlineJudge) {
System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" }));
}
}
public static void main(String[] args) throws Exception {
new Main().run();
}
class FastReader {
InputStream is;
public FastReader(boolean onlineJudge) {
is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes());
}
byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
double nextDouble() {
return Double.parseDouble(next());
}
char nextChar() {
return (char) skip();
}
String next() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
char[] next(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
long nextLong() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
char[][] nextMatrix(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = next(m);
return map;
}
int[] nextArray(int n, boolean isOneInd) {
int k = isOneInd ? 1 : 0;
int[] a = new int[n + k];
for (int i = k; i < n + k; i++)
a[i] = nextInt();
return a;
}
int[] shuffle(int[] arr) {
Random r = new Random();
for (int i = 1, j; i < arr.length; i++) {
j = r.nextInt(i);
arr[i] = arr[i] ^ arr[j];
arr[j] = arr[i] ^ arr[j];
arr[i] = arr[i] ^ arr[j];
}
return arr;
}
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
/**
* Created by aditya on 5/3/17.
*/
public class Main3 {
static long x, k;
static long MOD = (long)1e9 + 7;
public static void main(String args[]) throws Exception{
FastInput fi = new FastInput(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
x = fi.nextLong();
k = fi.nextLong();
if(x == 0) {
System.out.println(0);
return;
}
// System.out.println(pow(2, k+1));
long q1 = (pow(2, k+1) * (x%MOD)) % MOD;
long q2 = pow(2, k);
long q3 = 1;
// System.out.println(q1);
// System.out.println(q2);
// System.out.println(q3);
long exp = (q1-q2 + MOD + MOD)%MOD;
exp = (exp + q3)%MOD;
// exp = (exp*2)%MOD;
pw.println(exp);
pw.close();
}
static long pow(long n, long k) {
if(k == 0)
return 1;
if(k == 1)
return n;
long ret = pow(n, k/2)%MOD;
ret = (ret*ret)%MOD;
if(k%2 == 1)
ret = (ret*n)%MOD;
return ret;
}
static class FastInput {
private Reader in;
private BufferedReader br;
private StringTokenizer st;
public FastInput(Reader in) {
this.in=in;
br = new BufferedReader(in);
}
public String nextString() {
while(st==null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
System.out.println(e.getStackTrace());
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextString());
}
public long nextLong() {
return Long.parseLong(nextString());
}
public double nextDouble() {
return Double.parseDouble(nextString());
}
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.*;
import java.math.BigInteger;
import java.util.StringTokenizer;
public class C {
public static void main(String[] args) throws IOException {
init(System.in);
BigInteger x = new BigInteger(next());
if (x.compareTo(BigInteger.ZERO) == 0) {
System.out.println(0);
return;
}
BigInteger k = new BigInteger(next());
BigInteger mod = new BigInteger("1000000007");
BigInteger two = BigInteger.ONE.add(BigInteger.ONE);
BigInteger ans = two.modPow(k, mod);
ans = ans.multiply(two.multiply(x).subtract(BigInteger.ONE)).add(BigInteger.ONE).mod(mod);
System.out.println(ans);
}
//Input Reader
private static BufferedReader reader;
private static StringTokenizer tokenizer;
private static void init(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
tokenizer = new StringTokenizer("");
}
private static String next() throws IOException {
String read;
while (!tokenizer.hasMoreTokens()) {
read = reader.readLine();
if (read == null || read.equals(""))
return "-1";
tokenizer = new StringTokenizer(read);
}
return tokenizer.nextToken();
}
// private static int nextInt() throws IOException {
// return Integer.parseInt(next());
// }
// private static long nextLong() throws IOException {
// return Long.parseLong(next());
// }
//
// // Get a whole line.
// private static String line() throws IOException {
// return reader.readLine();
// }
//
// private static double nextDouble() throws IOException {
// return Double.parseDouble(next());
// }
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.*;
import java.math.BigInteger;
import java.util.Locale;
import java.util.StringTokenizer;
public class C {
String fileName = "<name>";
public static final int MOD = (int) (1e9 + 7);
public void solve() throws IOException {
long x = nextLong();
if (x == 0) {
out.print(0);
return;
}
long k = nextLong();
BigInteger power = BigInteger.valueOf(2)
.modPow(BigInteger.valueOf(k), BigInteger.valueOf(MOD));
BigInteger r = BigInteger.valueOf(x).multiply(power);
BigInteger l = r.subtract(power).add(BigInteger.ONE);
out.print(l.add(r).mod(BigInteger.valueOf(MOD)));
}
public void run() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
BufferedReader br;
StringTokenizer in;
PrintWriter out;
public String nextToken() throws IOException {
while (in == null || !in.hasMoreTokens()) {
in = new StringTokenizer(br.readLine());
}
return in.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.US);
new C().run();
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.*;
import java.util.*;
public class test {
static boolean DEBUG_FLAG = false;
int INF = (int)1e9;
long MOD = 1000000007;
static void debug(String s) {
if(DEBUG_FLAG) {
System.out.print(s);
}
}
long pow(long a, long n, long mod) {
if (n == 0) {
return 1;
}
long rs = 1;
while (n != 0) {
if (n % 2 == 1) {
rs *= a;
}
rs %= mod;
n >>= 1;
a *= a;
a %= mod;
}
return rs;
}
void solve(InputReader in, PrintWriter out) throws IOException {
long x = in.nextLong();
long k = in.nextLong();
if(x==0) {
out.println(0);
return;
}
long a = (2 * x - 1) % MOD;
long b = pow(2, k, MOD);
a = (a * b) % MOD;
a += 1;
a %= MOD;
out.println(a);
}
public static void main(String[] args) throws IOException {
if(args.length>0 && args[0].equalsIgnoreCase("d")) {
DEBUG_FLAG = true;
}
InputReader in = new InputReader();
PrintWriter out = new PrintWriter(System.out);
int t = 1;//in.nextInt();
long start = System.nanoTime();
while(t-- >0) {
new test().solve(in, out);
}
long end = System.nanoTime();
debug("\nTime: " + (end-start)/1e6 + " \n\n");
out.close();
}
static class InputReader {
static BufferedReader br;
static StringTokenizer st;
public InputReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
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());
}
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Dummy {
private static long mod = 1000000007;
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String[] strs = reader.readLine().split(" ");
long x = Long.parseLong(strs[0]);
long k = Long.parseLong(strs[1]);
long twoPK = modPow(2, k);
long twoPK_1 = (twoPK * 2) % mod;
long res = ((twoPK_1 * (x % mod)) % mod - (twoPK - 1) + mod) % mod;
System.out.println(x == 0? x: res);
}
private static long modPow(long base, long pow) {
long res = 1;
while(pow != 0) {
if((pow & 1) != 0) {
res = (res % mod * base % mod)%mod;
}
base = (base % mod * base % mod) % mod;
pow >>= 1;
}
return res;
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.*;
import java.util.*;
public class A992{
long mod = 1000000007L;
private void solve() throws Exception {
long x = nextLong();
long k = nextLong();
if(x == 0) {
out.println(0);
return;
}
x = x%mod;
long res = (((x*pow(2,k+1))%mod + (mod-pow(2,k))%mod)%mod+1)%mod;
out.println(res);
}
long pow(long m, long n){
long res = 1;
while(n > 0){
if(n % 2 == 1)res = (res*m)%mod;
m = (m*m)%mod;
n = n/2;
}
return res;
}
public static void main(String[] args) {
(new A992()).run();
}
private BufferedReader in;
private PrintWriter out;
private StringTokenizer tokenizer;
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private float nextFloat() throws IOException {
return Float.parseFloat(nextToken());
}
private String nextLine() throws IOException {
return new String(in.readLine());
}
private String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(in.readLine());
}
return tokenizer.nextToken();
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
//package CF489; //comment this line
import java.io.*;
import java.util.*;
import java.math.*;
public class B
{
private static long MOD=1000000007;
private static BigInteger m=new BigInteger(1000000007+"");
private static long pow(long x, long a)
{
if(a==0)
return 1;
long ans=pow(x,a/2);
ans=(ans*ans)%MOD;
if(a%2==1)
ans=(ans*x)%MOD;
return ans%MOD;
}
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
long N,K,ans;
//System.out.println(); //comment this line
String s[]=br.readLine().trim().split(" ");
N=Long.parseLong(s[0]);
K=Long.parseLong(s[1]);
BigInteger bi=new BigInteger(N+"");
BigInteger a=new BigInteger(N+"");
BigInteger two=new BigInteger(2+"");
if(N==0)
{
System.out.println(0);
System.exit(0);
}
if(K==0)
{
a=a.multiply(two);
a=a.mod(m);
System.out.println(a);
System.exit(0);
}
long p=pow(2,K);
BigInteger p2=new BigInteger(p+"");
BigInteger tmp=p2.subtract(BigInteger.ONE);
tmp=tmp.mod(m);
p2=p2.multiply(two);
p2=p2.mod(m);
a=a.multiply(p2);
a=a.mod(m);
a=a.subtract(tmp);
a=a.mod(m);
if(!(a.signum()==1)&&!(a.signum()==0))
a.add(m);
System.out.println(a);
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.util.*;
import java.io.*;
public class C {
FastScanner in;
PrintWriter out;
boolean systemIO = true;
public static void quickSort(int[] a, int from, int to) {
if (to - from <= 1) {
return;
}
int i = from;
int j = to - 1;
int x = a[from + (new Random()).nextInt(to - from)];
while (i <= j) {
while (a[i] < x) {
i++;
}
while (a[j] > x) {
j--;
}
if (i <= j) {
int t = a[i];
a[i] = a[j];
a[j] = t;
i++;
j--;
}
}
quickSort(a, from, j + 1);
quickSort(a, j + 1, to);
}
long mod = 1000000007;
public long pow(long k) {
if (k == 0) {
return 1L;
}
if (k == 1) {
return 2L;
}
if (k % 2 == 1) {
return (2L * pow(k - 1)) % mod;
}
long x = pow(k / 2);
return (x * x) % mod;
}
public void solve() {
long x = in.nextLong();
if (x == 0) {
out.println(0);
return;
}
x %= mod;
long k = in.nextLong();
long pow = pow(k);
long ans = 1;
ans = (ans - pow + mod) % mod;
ans = (ans + (((2 * pow) % mod) * x) % mod) % mod;
out.println(ans);
}
public void run() {
try {
if (systemIO) {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
} else {
in = new FastScanner(new File("input.txt"));
out = new PrintWriter(new File("output.txt"));
}
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
return null;
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
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());
}
}
// AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
public static void main(String[] args) {
new C().run();
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
/*
* Author : joney_000[[email protected]]
* Algorithm : N/A
* Platform : Codeforces
* Ref :
*/
public class A{
private InputStream inputStream ;
private OutputStream outputStream ;
private FastReader in ;
private PrintWriter out ;
private final int BUFFER = 100005;
private final long mod = 1000000000+7;
private final int INF = Integer.MAX_VALUE;
private final long INF_L = Long.MAX_VALUE / 10;
public A(){}
public A(boolean stdIO)throws FileNotFoundException{
// stdIO = false;
if(stdIO){
inputStream = System.in;
outputStream = System.out;
}else{
inputStream = new FileInputStream("input.txt");
outputStream = new FileOutputStream("output.txt");
}
in = new FastReader(inputStream);
out = new PrintWriter(outputStream);
}
void run()throws Exception{
long x = l(); long k = l();
if(x == 0){
out.write("0");
return;
}
x %= mod;
long a = (x * pow(2L, k, mod) + mod)%mod;
long b = (a - pow(2L, k, mod) + 1 + mod)%mod;
long res = (a + b + mod )%mod;
out.write(""+res+"\n");
}
long gcd(long a, long b){
if(b == 0)return a;
return gcd(b, a % b);
}
long lcm(long a, long b){
if(a == 0 || b == 0)return 0;
return (a * b)/gcd(a, b);
}
long mulMod(long a, long b, long mod){
if(a == 0 || b == 0)return 0;
if(b == 1)return a;
long ans = mulMod(a, b/2, mod);
ans = (ans * 2) % mod;
if(b % 2 == 1)ans = (a + ans)% mod;
return ans;
}
long pow(long a, long b, long mod){
if(b == 0)return 1;
if(b == 1)return a;
long ans = pow(a, b/2, mod);
ans = (ans * ans);
if(ans >= mod)ans %= mod;
if(b % 2 == 1)ans = (a * ans);
if(ans >= mod)ans %= mod;
return ans;
}
// 20*20 nCr Pascal Table
long[][] ncrTable(){
long ncr[][] = new long[21][21];
for(int i = 0; i <= 20; i++){
ncr[i][0] = ncr[i][i] = 1L;
}
for(int j = 0; j <= 20; j++){
for(int i = j + 1; i <= 20; i++){
ncr[i][j] = ncr[i-1][j] + ncr[i-1][j-1];
}
}
return ncr;
}
int i()throws Exception{
return in.nextInt();
}
long l()throws Exception{
return in.nextLong();
}
double d()throws Exception{
return in.nextDouble();
}
char c()throws Exception{
return in.nextCharacter();
}
String s()throws Exception{
return in.nextLine();
}
BigInteger bi()throws Exception{
return in.nextBigInteger();
}
private void closeResources(){
out.flush();
out.close();
return;
}
// IMP: roundoff upto 2 digits
// double roundOff = Math.round(a * 100.0) / 100.0;
// or
// System.out.printf("%.2f", val);
// print upto 2 digits after decimal
// val = ((long)(val * 100.0))/100.0;
public static void main(String[] args) throws java.lang.Exception{
A driver = new A(true);
driver.run();
driver.closeResources();
}
}
class FastReader{
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[4 * 1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastReader(InputStream stream){
this.stream = stream;
}
public int read(){
if (numChars == -1){
throw new InputMismatchException ();
}
if (curChar >= numChars){
curChar = 0;
try{
numChars = stream.read (buf);
} catch (IOException e){
throw new InputMismatchException ();
}
if (numChars <= 0){
return -1;
}
}
return buf[curChar++];
}
public int peek(){
if (numChars == -1){
return -1;
}
if (curChar >= numChars){
curChar = 0;
try{
numChars = stream.read (buf);
} catch (IOException e){
return -1;
}
if (numChars <= 0){
return -1;
}
}
return buf[curChar];
}
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==','){
c = read();
}
if (c < '0' || c > '9'){
throw new InputMismatchException ();
}
res *= 10;
res += c - '0';
c = read ();
} while (!isSpaceChar (c));
return res * sgn;
}
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 String nextString(){
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 boolean isSpaceChar(int c){
if (filter != null){
return filter.isSpaceChar (c);
}
return isWhitespace (c);
}
public static boolean isWhitespace(int c){
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0(){
StringBuilder buf = new StringBuilder ();
int c = read ();
while (c != '\n' && c != -1){
if (c != '\r'){
buf.appendCodePoint (c);
}
c = read ();
}
return buf.toString ();
}
public String nextLine(){
String s = readLine0 ();
while (s.trim ().length () == 0)
s = readLine0 ();
return s;
}
public String nextLine(boolean ignoreEmptyLines){
if (ignoreEmptyLines){
return nextLine ();
}else{
return readLine0 ();
}
}
public BigInteger nextBigInteger(){
try{
return new BigInteger (nextString ());
} catch (NumberFormatException e){
throw new InputMismatchException ();
}
}
public char nextCharacter(){
int c = read ();
while (isSpaceChar (c))
c = read ();
return (char) c;
}
public double nextDouble(){
int c = read ();
while (isSpaceChar (c))
c = read ();
int sgn = 1;
if (c == '-'){
sgn = -1;
c = read ();
}
double res = 0;
while (!isSpaceChar (c) && c != '.'){
if (c == 'e' || c == 'E'){
return res * Math.pow (10, nextInt ());
}
if (c < '0' || c > '9'){
throw new InputMismatchException ();
}
res *= 10;
res += c - '0';
c = read ();
}
if (c == '.'){
c = read ();
double m = 1;
while (!isSpaceChar (c)){
if (c == 'e' || c == 'E'){
return res * Math.pow (10, nextInt ());
}
if (c < '0' || c > '9'){
throw new InputMismatchException ();
}
m /= 10;
res += (c - '0') * m;
c = read ();
}
}
return res * sgn;
}
public boolean isExhausted(){
int value;
while (isSpaceChar (value = peek ()) && value != -1)
read ();
return value == -1;
}
public String next(){
return nextString ();
}
public SpaceCharFilter getFilter(){
return filter;
}
public void setFilter(SpaceCharFilter filter){
this.filter = filter;
}
public interface SpaceCharFilter{
public boolean isSpaceChar(int ch);
}
}
class Pair implements Comparable<Pair>{
public int a;
public int b;
public int c;
public Pair(){
this.a = 0;
this.b = 0;
this.c = 0;
}
public Pair(int a,int b, int c){
this.a = a;
this.b = b;
this.c = c;
}
public int compareTo(Pair p){
return this.c - p.c;
}
@Override
public String toString(){
return "a = " + this.a + " b = " + this.b + " c = "+this.c;
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.*;
import java.util.*;
import java.math.*;
public class C
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
BigInteger x = sc.nextBigInteger();
BigInteger k = sc.nextBigInteger();
BigInteger zero = new BigInteger("0");
BigInteger one = new BigInteger("1");
BigInteger two = new BigInteger("2");
BigInteger modulo = new BigInteger("1000000007");
BigInteger ans = two.modPow(k.add(one),modulo);
ans = ans.multiply(x);
ans = ans.subtract(two.modPow(k,modulo));
ans = ans.add(one);
ans = ans.mod(modulo);
if (x.equals(zero))
{
System.out.println(0);
}
else
{
System.out.println(ans);
}
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
//package que_a;
import java.io.*;
import java.util.*;
import java.math.*;
public class utkarsh {
InputStream is;
PrintWriter out;
long mod = (long) (1e9 + 7);
boolean SHOW_TIME;
void solve() {
//Enter code here utkarsh
//SHOW_TIME = true;
long X = nl();
BigInteger x = BigInteger.valueOf(X);
long K = nl();
BigInteger k = BigInteger.valueOf(K);
BigInteger MOD = BigInteger.valueOf(mod);
if(X == 0) {
out.println(0); return;
}
if(k.compareTo(BigInteger.ZERO) == 0) {
out.println((x.add(x)).mod(MOD)); return;
}
BigInteger p = BigInteger.valueOf(modpow(2, K, mod));
BigInteger ans = x.multiply(p);
ans = ans.add(ans);
ans = ans.subtract(p).add(BigInteger.ONE);
ans = ans.add(MOD);
out.println(ans.mod(MOD));
}
long modpow(long b, long e, long mod) {
b %= mod;
long r = 1;
while(e > 0) {
if((e & 1) == 1) {
r *= b; r %= 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);
long start = System.currentTimeMillis();
solve();
long end = System.currentTimeMillis();
if(SHOW_TIME) out.println("\n" + (end - start) + " ms");
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);
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.*;
import java.util.*;
public class C implements Runnable{
public static void main (String[] args) {new Thread(null, new C(), "_cf", 1 << 28).start();}
long MOD = (long)1e9+7;
public void run() {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
System.err.println("Go!");
long x = fs.nextLong();
long k = fs.nextLong();
if(x == 0) {
System.out.println(0);
return;
}
if(k == 0) {
System.out.println(mult(x, 2));
return;
}
long max = mult(x, power(2, k, MOD));
long min = sub(max, power(2, k, MOD));
long total = 0;
if(min <= max) {
total = sub(summ(max), summ(min));
}
else {
total = summ(max);
total = add(total, sub(summ(MOD-1), summ(min)));
}
total = mult(total, 2);
total = div(total, power(2, k, MOD));
out.println(total);
out.close();
}
long summ(long x) {
x *= x+1;
x /= 2;
x %= MOD;
return x;
}
long add(long a, long b) {
a %= MOD;
b %= MOD;
a += b;
a %= MOD;
return a;
}
long sub(long a, long b) {
a %= MOD;
b %= MOD;
a -= b;
while(a < 0) a += MOD;
a %= MOD;
return a;
}
long mult(long a, long b) {
a %= MOD;
b %= MOD;
a *= b;
a %= MOD;
return a;
}
long div(long a, long b) {
a %= MOD;
b %= MOD;
a *= inv(b);
a %= MOD;
return a;
}
long inv(long x) {
long res = power(x, MOD-2, MOD);
while(res < 0) res += MOD;
res %= MOD;
return res;
}
long power (long x, long y, long m) {
long res = 1;
x %= m;
while(y > 0) {
if(y % 2 == 1) {
res = (res * x) % m;
}
y >>= 1L;
x = (x * x) % m;
}
return res;
}
void sort (int[] a) {
int n = a.length;
for(int i = 0; i < 50; i++) {
Random r = new Random();
int x = r.nextInt(n), y = r.nextInt(n);
int temp = a[x];
a[x] = a[y];
a[y] = temp;
}
Arrays.sort(a);
}
class FastScanner {
public int BS = 1<<16;
public char NC = (char)0;
byte[] buf = new byte[BS];
int bId = 0, size = 0;
char c = NC;
double num = 1;
BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) throws FileNotFoundException {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
public char nextChar(){
while(bId==size) {
try {
size = in.read(buf);
}catch(Exception e) {
return NC;
}
if(size==-1)return NC;
bId=0;
}
return (char)buf[bId++];
}
public int nextInt() {
return (int)nextLong();
}
public long nextLong() {
num=1;
boolean neg = false;
if(c==NC)c=nextChar();
for(;(c<'0' || c>'9'); c = nextChar()) {
if(c=='-')neg=true;
}
long res = 0;
for(; c>='0' && c <='9'; c=nextChar()) {
res = (res<<3)+(res<<1)+c-'0';
num*=10;
}
return neg?-res:res;
}
public double nextDouble() {
double cur = nextLong();
return c!='.' ? cur:cur+nextLong()/num;
}
public String next() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c>32) {
res.append(c);
c=nextChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c!='\n') {
res.append(c);
c=nextChar();
}
return res.toString();
}
public boolean hasNext() {
if(c>32)return true;
while(true) {
c=nextChar();
if(c==NC)return false;
else if(c>32)return true;
}
}
public int[] nextIntArray(int n) {
int[] res = new int[n];
for(int i = 0; i < n; i++) res[i] = nextInt();
return res;
}
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.*;
import java.math.BigInteger;
public class C {
private static Solver solver = new Solver();
private static long m = 1000000000L + 7L;
public static void main(String[] args) throws IOException {
solver.withProcedure(() -> {
String[] input = solver.readString().split(" ");
BigInteger x = new BigInteger(input[0]);
BigInteger k = new BigInteger(input[1]);
if (x.compareTo(BigInteger.ZERO) == 0) {
solver.println("" + 0);
return;
}
BigInteger two = BigInteger.valueOf(2);
BigInteger mm = BigInteger.valueOf(m);
BigInteger binpowedK = two.modPow(k, mm);
BigInteger binpowedKPlusOne = two.modPow(k.add(BigInteger.ONE), mm);
BigInteger res = binpowedKPlusOne.multiply(x).subtract(binpowedK.subtract(BigInteger.ONE)).mod(mm);
if (res.compareTo(BigInteger.ZERO) < 0) {
res = BigInteger.ZERO;
}
solver.println("" + res);
}).solve();
}
private static long binpow(long a, long n) {
a = a % m;
long res = 1L;
while (n > 0) {
if ((n & 1L) != 0)
res = (res * a) % m;
a = (a * a) % m;
n >>= 1L;
}
return res;
}
@FunctionalInterface
private interface Procedure {
void run() throws IOException;
}
private static class Solver {
private Procedure procedure;
private StreamTokenizer in;
private PrintWriter out;
private BufferedReader bufferedReader;
Solver() {
try {
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
Reader reader = oj ? new InputStreamReader(System.in) : new FileReader("input.txt");
Writer writer = oj ? new OutputStreamWriter(System.out) : new FileWriter("output.txt");
bufferedReader = new BufferedReader(reader);
in = new StreamTokenizer(bufferedReader);
out = new PrintWriter(writer);
} catch (Exception e) {
throw new RuntimeException("Initialization has failed");
}
}
void solve() throws IOException {
procedure.run();
}
int readInt() throws IOException {
in.nextToken();
return (int) in.nval;
}
long readLong() throws IOException {
in.nextToken();
return (long) in.nval;
}
String readString() throws IOException {
return bufferedReader.readLine();
}
char readChar() throws IOException {
in.nextToken();
return in.sval.charAt(0);
}
void println(String str) {
out.println(str);
out.flush();
}
void print(String str) {
out.print(str);
out.flush();
}
Solver withProcedure(Procedure procedure) {
this.procedure = procedure;
return this;
}
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.util.*;
import java.io.*;
public class R489C {
static long m = (long)(1e9+7);
/*
1000000000000000000
*/
public static void main(String[] args) {
JS scan = new JS();
long n = scan.nextLong();
long k = scan.nextLong();
if(n == 0) {
System.out.println(0);
return;
}
if(k == 0) {
long ans = (n%m)*(2%m)%m;
System.out.println(ans%m);
return;
}
//System.out.println(2+" "+(k+1)+" "+m);
long coeff = power(2L, k+1, m);
//System.out.println(coeff);
long r = (coeff%m)*(n%m)%m;
//System.out.println(r);
long x = power(2L, k, m)%m-1;
if(x < 0) x += m;
long ans = r-x;
if(ans < 0) ans += m;
System.out.println(ans%m);
}
static long power(long x, long y, long p){
// Initialize result
long res = 1;
// 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%p * x%p) % p;
// y must be even now
// y = y / 2
y = y >> 1;
x = (x%p * x%p) % p;
}
return res;
}
/*
1000000000000000000 1000000000000000000
*/
static class JS{
public int BS = 1<<16;
public char NC = (char)0;
byte[] buf = new byte[BS];
int bId = 0, size = 0;
char c = NC;
double num = 1;
BufferedInputStream in;
public JS() {
in = new BufferedInputStream(System.in, BS);
}
public JS(String s) throws FileNotFoundException {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
public char nextChar(){
while(bId==size) {
try {
size = in.read(buf);
}catch(Exception e) {
return NC;
}
if(size==-1)return NC;
bId=0;
}
return (char)buf[bId++];
}
public int nextInt() {
return (int)nextLong();
}
public long nextLong() {
num=1;
boolean neg = false;
if(c==NC)c=nextChar();
for(;(c<'0' || c>'9'); c = nextChar()) {
if(c=='-')neg=true;
}
long res = 0;
for(; c>='0' && c <='9'; c=nextChar()) {
res = (res<<3)+(res<<1)+c-'0';
num*=10;
}
return neg?-res:res;
}
public double nextDouble() {
double cur = nextLong();
return c!='.' ? cur:cur+nextLong()/num;
}
public String next() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c>32) {
res.append(c);
c=nextChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c!='\n') {
res.append(c);
c=nextChar();
}
return res.toString();
}
public boolean hasNext() {
if(c>32)return true;
while(true) {
c=nextChar();
if(c==NC)return false;
else if(c>32)return true;
}
}
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.util.*;
import java.io.*;
public class Solution1 {
private void solve() throws IOException {
long MOD = 1_000_000_007;
long x = in.nextLong();
long k = in.nextLong();
if (x == 0) {
System.out.println(0);
return;
}
long val = binpow(2, k + 1, MOD) % MOD;
long kek = (binpow(2, k, MOD) - 1 + MOD) % MOD;
x = (val % MOD) * (x % MOD) % MOD;
long ans = (x % MOD - kek % MOD + MOD) % MOD;
System.out.println(ans % MOD);
}
private long binpow(long a, long n, long mod) {
long res = 1;
while (n > 0) {
if (n % 2 == 1)
res = (res % mod) * (a % mod) % mod;
a = (a % mod) * (a % mod) % mod;
n >>= 1;
}
return res % mod;
}
private PrintWriter out;
private MyScanner in;
private void run() throws IOException {
in = new MyScanner();
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
}
private class MyScanner {
private BufferedReader br;
private StringTokenizer st;
public MyScanner() throws IOException {
this.br = new BufferedReader(new InputStreamReader(System.in));
}
public MyScanner(String fileTitle) throws IOException {
this.br = new BufferedReader(new FileReader(fileTitle));
}
public String nextLine() throws IOException {
String s = br.readLine();
return s == null ? "-1" : s;
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String s = br.readLine();
if (s == null) {
return "-1";
}
st = new StringTokenizer(s);
}
return st.nextToken();
}
public Integer nextInt() throws IOException {
return Integer.parseInt(this.next());
}
public Long nextLong() throws IOException {
return Long.parseLong(this.next());
}
public Double nextDouble() throws IOException {
return Double.parseDouble(this.next());
}
public void close() throws IOException {
this.br.close();
}
}
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.US);
new Solution1().run();
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
/**
* Created by Baelish on 6/18/2018.
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.InputMismatchException;
public class C_3 {
public static void main(String[] args) throws Exception {
FastReader in = new FastReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
long mod = (long) 1e9 + 7;
long xx = in.nextLong(), kk = in.nextLong();
if(xx == 0){
pw.println(0); pw.close();
return;
}
BigInteger x = BigInteger.valueOf(xx), k = BigInteger.valueOf(kk);
// long a = bigMod(2, k+1, mod );long b = bigMod(2, k, mod);
BigInteger MOD = BigInteger.valueOf(mod);
BigInteger a = BigInteger.valueOf(2).modPow(BigInteger.valueOf(kk+1), MOD);
BigInteger b = BigInteger.valueOf(2).modPow(BigInteger.valueOf(kk), MOD);
BigInteger s = (a.multiply(x)).mod(MOD);
s = s.subtract(b.mod(MOD));
s = s.add(BigInteger.ONE);
s = s.mod(MOD);
s = s.add(MOD);
s = s.mod(MOD);
// debug(a, b, x);
// long s = ((a * x) % mod - b % mod + 1 + mod) % mod;
pw.println(s);
pw.close();
}
static void debug(Object... obj) {
System.err.println(Arrays.deepToString(obj));
}
static class FastReader {
static final int ints[] = new int[128];
InputStream is;
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
public FastReader(InputStream is) {
for (int i = '0'; i <= '9'; i++) ints[i] = i - '0';
this.is = is;
}
public int readByte() {
if (lenbuf == -1) throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0) return -1;
}
return inbuf[ptrbuf++];
}
public boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
public int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b)) ;
return b;
}
public String next() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = (num << 3) + (num << 1) + ints[b];
} else {
return minus ? -num : num;
}
b = readByte();
}
}
public long nextLong() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = (num << 3) + (num << 1) + ints[b];
} else {
return minus ? -num : num;
}
b = readByte();
}
}
public double nextDouble() {
return Double.parseDouble(next());
}
/* public char nextChar() {
return (char)skip();
}*/
public char[] next(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
/*private char buff[] = new char[1005];
public char[] nextCharArray(){
int b = skip(), p = 0;
while(!(isSpaceChar(b))){
buff[p++] = (char)b;
b = readByte();
}
return Arrays.copyOf(buff, p);
}*/
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.util.*;
import java.io.*;
public class A{
static long mod = 1000000000+7;
static int arr[];
static HashMap<Long,Long> map = new HashMap<>();
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
long x = scan.nextLong();
long k = scan.nextLong();
if(x == 0)
{
System.out.println(0);
return;
}
x = x%mod;
long power = pow(2,k + 1)%mod;
power = (power*x)%mod;
long num = (pow(2,k) - 1 + mod)%mod;
long ans = (power - num + mod)%mod;
System.out.println((ans));
}
public static long pow(long a,long b)
{
if(b == 0)
return 1;
if(b == 1)
return a;
long x1,x2;
if(map.containsKey(b - b/2))
x1 = map.get(b - b/2);
else
{
x1 = pow(a,b - b/2)%mod;
map.put(b - b/2,x1);
}
if(map.containsKey(b/2))
x2 = map.get(b/2);
else
{
x2 = pow(a,b/2)%mod;
map.put(b/2,x2);
}
return (x1*x2)%mod;
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
/* spar5h */
public class cf3 implements Runnable{
final static long mod = (long)1e9 + 7;
static long modExp(long x, long pow) {
x = x % mod;
long res = 1;
while (pow > 0) {
if (pow % 2 == 1)
res = res * x % mod;
pow = pow / 2;
x = x * x % mod;
}
return res;
}
public void run() {
InputReader s = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int t = 1;
while(t-- > 0) {
long x = s.nextLong(), k = s.nextLong();
if(x == 0) {
w.println(0); continue;
}
x = x % mod;
long res = (modExp(2, k + 1) * x % mod + 1) % mod;
res = (res + mod - modExp(2, k)) % mod;
w.println(res);
}
w.close();
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
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 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 double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
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 boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception
{
new Thread(null, new cf3(),"cf3",1<<26).start();
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author prakharjain
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
_992C solver = new _992C();
solver.solve(1, in, out);
out.close();
}
static class _992C {
static int mod = (int) 1e9 + 7;
public void solve(int testNumber, InputReader in, OutputWriter out) {
long x = in.nextLong();
long k = in.nextLong();
if (x == 0) {
out.println(0);
return;
}
long[][] base = new long[][]{{2, 0}, {1, 1}};
_992C.Matrix.N = 2;
base = _992C.Matrix.matrixPower(base, base, k);
x %= mod;
long ans = 2 * base[0][0] * x - base[1][0];
ans %= mod;
if (ans < 0)
ans += mod;
out.println(ans);
}
static public class Matrix {
static int N;
static long[][] id = new long[][]{{1, 0}, {0, 1}};
static long[][] matrixPower(long[][] mat, long[][] base, long pow) {
if (pow == 0) {
return id;
}
if (pow == 1) {
return base;
}
long[][] t = matrixPower(mat, base, pow / 2);
t = multiplyMatrix(t, t);
if (pow % 2 == 1) {
t = multiplyMatrix(t, base);
}
return t;
}
static long[][] multiplyMatrix(long[][] m, long[][] m2) {
long[][] ans = new long[N][N];
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++) {
ans[i][j] = 0;
for (int k = 0; k < N; k++) {
ans[i][j] += m[i][k] * m2[k][j];
ans[i][j] %= mod;
}
}
return ans;
}
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(long i) {
writer.println(i);
}
public void println(int i) {
writer.println(i);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
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 boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.*;
import java.util.*;
public class C
{
static long mod=(long)(1e9+7);
public static long powMod(long e,long b)
{
/*e=e%mod;*/
long res=1;
while(e>0)
{
if(e%2==1)
res=res*b%mod;
e/=2;
b=b*b%mod;
}
return res;
}
public static void main(String[] args) throws IOException
{
Scanner sc=new Scanner(System.in);
PrintWriter pw=new PrintWriter(System.out);
long x=sc.nextLong(),k=sc.nextLong();
if(x==0)
{
System.out.println(0);
return;
}
if(k==0)
{
pw.println((2*x)%mod);
pw.close();return;
}
long ans=2*x-1;
ans=ans%mod;
long b=powMod(k,2);
ans=((ans*b)+1)%mod;
pw.println(ans);
pw.close();
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
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 double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public boolean ready() throws IOException {
return br.ready();
}
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.util.*;
import java.lang.*;
import java.io.*;
public class C{
public static void main (String[] args) throws java.lang.Exception{
Scanner scan=new Scanner(System.in);
long x=scan.nextLong(), k=scan.nextLong();
long MOD = 1000000007;
if(x==0){
System.out.println("0");
return;
}
x %= MOD;
long ans= (((new myC()).fastPow(2L, k+1)*x)%MOD - (new myC()).fastPow(2L, k) + MOD + 1)% MOD;
ans %= MOD;
System.out.println(ans);
}
}
class myC{
long MOD = 1000000007;
long fastPow(long x, long k){
long bb=x%MOD, ans=1;
while(k > 0){
if((k&1)==1){
ans=(ans*bb)%MOD;
}
bb=(bb*bb)%MOD;
k>>=1;
}
return ans;
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Div2_489C {
static final long MOD = 1_000_000_007;
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter printer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
StringTokenizer inputData = new StringTokenizer(reader.readLine());
long st = Long.parseLong(inputData.nextToken());
if(st == 0) {
printer.println(0);
printer.close();
return;
}
st %= MOD;
long years = Long.parseLong(inputData.nextToken());
long[][] res = exp(years);
long ans = (res[0][0] * st % MOD * 2 % MOD + res[0][1] * (-1 + MOD) % MOD) % MOD;
printer.println(ans);
printer.close();
}
static long[][] exp(long pow) {
long[][] cBase = base;
long[][] res = { { 1, 0 }, { 0, 1 } };
while (pow != 0) {
if ((pow & 1) != 0) {
res = mult(res, cBase);
}
cBase = mult(cBase, cBase);
pow >>= 1;
}
return res;
}
static long[][] base = { { 2, 1 }, { 0, 1 } };
static long[][] mult(long[][] a, long[][] b) {
long[][] res = new long[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
res[i][j] = (a[i][0] * b[0][j] % MOD + a[i][1] * b[1][j] % MOD) % MOD;
}
}
return res;
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
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);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
int mod = (int) 1e9 + 7;
public void solve(int testNumber, InputReader in, PrintWriter out) {
long x = in.readLong();
long k = in.readLong();
if (x == 0) {
out.println(0);
return;
}
long ans = (BigInteger.valueOf(MathUtil.pow(2, k + 1, mod)).multiply(BigInteger.valueOf(x))).mod(BigInteger.valueOf(mod)).longValue();
long sub = (mod + MathUtil.pow(2, k, mod) - 1) % mod;
out.println((mod + ans - sub) % mod);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public long readLong() {
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 boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class MathUtil {
public static long pow(long a, long b, long mod) {
long ans = 1;
while (b > 0) {
if (b % 2 == 1) ans = (ans * a) % mod;
a = (a * a) % mod;
b /= 2;
}
return ans;
}
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
//package baobab;
import java.io.*;
import java.util.*;
public class C {
public static void main(String[] args) {
Solver solver = new Solver();
}
static class Solver {
IO io;
public Solver() {
this.io = new IO();
try {
solve();
} catch (RuntimeException e) {
if (!e.getMessage().equals("Clean exit")) {
throw e;
}
} finally {
io.close();
}
}
/****************************** START READING HERE ********************************/
void solve() {
long x = io.nextLong();
long k = io.nextLong();
if (x==0) done(0);
long ans = pow(2,k) * ((2*x - 1)%MOD) + 1;
io.println(ans%MOD);
}
long pow(long base, long exp) {
if (exp == 0) return 1L;
long x = pow(base, exp/2);
long ans = x * x;
ans %= MOD;
if (exp % 2 != 0) {
ans *= base;
ans %= MOD;
}
return ans;
}
void solve2() {
long x = io.nextLong();
long k = io.nextLong();
if (x==0) done(0);
// TODO how to exclude from counts cases where dresses are negative?
long checkPointA = min(10000, k);
double count = x;
long i=0;
for (; i<checkPointA; i++) {
count *= 2;
count -= 0.5;
count %= MOD;
}
List<Double> bah = new ArrayList<>();
List<Long> meh = new ArrayList<>();
while (true) {
bah.add(count);
meh.add(i);
long j = 2*i;
if (j > k || j < 0) break;
i = j;
count *= count;
count %= MOD;
}
while (!bah.isEmpty()) {
long muller = meh.get(meh.size()-1);
long cand = i + muller;
if (cand > k || cand < 0) {
meh.remove(meh.size()-1);
bah.remove(bah.size()-1);
continue;
}
i = cand;
count *= meh.get(meh.size()-1);
count %= MOD;
}
for (; i<k; i++) {
count *= 2;
count -= 0.5;
count %= MOD;
}
// last month no eating
count *= 2;
count %= MOD;
io.println(Math.round(count));
}
/************************** UTILITY CODE BELOW THIS LINE **************************/
long MOD = (long)1e9 + 7;
boolean closeToZero(double v) {
// Check if double is close to zero, considering precision issues.
return Math.abs(v) <= 0.0000000000001;
}
class DrawGrid {
void draw(boolean[][] d) {
System.out.print(" ");
for (int x=0; x<d[0].length; x++) {
System.out.print(" " + x + " ");
}
System.out.println("");
for (int y=0; y<d.length; y++) {
System.out.print(y + " ");
for (int x=0; x<d[0].length; x++) {
System.out.print((d[y][x] ? "[x]" : "[ ]"));
}
System.out.println("");
}
}
void draw(int[][] d) {
int max = 1;
for (int y=0; y<d.length; y++) {
for (int x=0; x<d[0].length; x++) {
max = Math.max(max, ("" + d[y][x]).length());
}
}
System.out.print(" ");
String format = "%" + (max+2) + "s";
for (int x=0; x<d[0].length; x++) {
System.out.print(String.format(format, x) + " ");
}
format = "%" + (max) + "s";
System.out.println("");
for (int y=0; y<d.length; y++) {
System.out.print(y + " ");
for (int x=0; x<d[0].length; x++) {
System.out.print(" [" + String.format(format, (d[y][x])) + "]");
}
System.out.println("");
}
}
}
class IDval implements Comparable<IDval> {
int id;
long val;
public IDval(int id, long val) {
this.val = val;
this.id = id;
}
@Override
public int compareTo(IDval o) {
if (this.val < o.val) return -1;
if (this.val > o.val) return 1;
return this.id - o.id;
}
}
private class ElementCounter {
private HashMap<Long, Integer> elements;
public ElementCounter() {
elements = new HashMap<>();
}
public void add(long element) {
int count = 1;
Integer prev = elements.get(element);
if (prev != null) count += prev;
elements.put(element, count);
}
public void remove(long element) {
int count = elements.remove(element);
count--;
if (count > 0) elements.put(element, count);
}
public int get(long element) {
Integer val = elements.get(element);
if (val == null) return 0;
return val;
}
public int size() {
return elements.size();
}
}
class StringCounter {
HashMap<String, Integer> elements;
public StringCounter() {
elements = new HashMap<>();
}
public void add(String identifier) {
int count = 1;
Integer prev = elements.get(identifier);
if (prev != null) count += prev;
elements.put(identifier, count);
}
public void remove(String identifier) {
int count = elements.remove(identifier);
count--;
if (count > 0) elements.put(identifier, count);
}
public long get(String identifier) {
Integer val = elements.get(identifier);
if (val == null) return 0;
return val;
}
public int size() {
return elements.size();
}
}
class DisjointSet {
/** Union Find / Disjoint Set data structure. */
int[] size;
int[] parent;
int componentCount;
public DisjointSet(int n) {
componentCount = n;
size = new int[n];
parent = new int[n];
for (int i=0; i<n; i++) parent[i] = i;
for (int i=0; i<n; i++) size[i] = 1;
}
public void join(int a, int b) {
/* Find roots */
int rootA = parent[a];
int rootB = parent[b];
while (rootA != parent[rootA]) rootA = parent[rootA];
while (rootB != parent[rootB]) rootB = parent[rootB];
if (rootA == rootB) {
/* Already in the same set */
return;
}
/* Merge smaller set into larger set. */
if (size[rootA] > size[rootB]) {
size[rootA] += size[rootB];
parent[rootB] = rootA;
} else {
size[rootB] += size[rootA];
parent[rootA] = rootB;
}
componentCount--;
}
}
class Trie {
int N;
int Z;
int nextFreeId;
int[][] pointers;
boolean[] end;
/** maxLenSum = maximum possible sum of length of words */
public Trie(int maxLenSum, int alphabetSize) {
this.N = maxLenSum;
this.Z = alphabetSize;
this.nextFreeId = 1;
pointers = new int[N+1][alphabetSize];
end = new boolean[N+1];
}
public void addWord(String word) {
int curr = 0;
for (int j=0; j<word.length(); j++) {
int c = word.charAt(j) - 'a';
int next = pointers[curr][c];
if (next == 0) {
next = nextFreeId++;
pointers[curr][c] = next;
}
curr = next;
}
end[curr] = true;
}
public boolean hasWord(String word) {
int curr = 0;
for (int j=0; j<word.length(); j++) {
int c = word.charAt(j) - 'a';
int next = pointers[curr][c];
if (next == 0) return false;
curr = next;
}
return end[curr];
}
}
private static class Prob {
/** For heavy calculations on probabilities, this class
* provides more accuracy & efficiency than doubles.
* Math explained: https://en.wikipedia.org/wiki/Log_probability
* Quick start:
* - Instantiate probabilities, eg. Prob a = new Prob(0.75)
* - add(), multiply() return new objects, can perform on nulls & NaNs.
* - get() returns probability as a readable double */
/** Logarithmized probability. Note: 0% represented by logP NaN. */
private double logP;
/** Construct instance with real probability. */
public Prob(double real) {
if (real > 0) this.logP = Math.log(real);
else this.logP = Double.NaN;
}
/** Construct instance with already logarithmized value. */
static boolean dontLogAgain = true;
public Prob(double logP, boolean anyBooleanHereToChooseThisConstructor) {
this.logP = logP;
}
/** Returns real probability as a double. */
public double get() {
return Math.exp(logP);
}
@Override
public String toString() {
return ""+get();
}
/***************** STATIC METHODS BELOW ********************/
/** Note: returns NaN only when a && b are both NaN/null. */
public static Prob add(Prob a, Prob b) {
if (nullOrNaN(a) && nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain);
if (nullOrNaN(a)) return copy(b);
if (nullOrNaN(b)) return copy(a);
double x = Math.max(a.logP, b.logP);
double y = Math.min(a.logP, b.logP);
double sum = x + Math.log(1 + Math.exp(y - x));
return new Prob(sum, dontLogAgain);
}
/** Note: multiplying by null or NaN produces NaN (repping 0% real prob). */
public static Prob multiply(Prob a, Prob b) {
if (nullOrNaN(a) || nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain);
return new Prob(a.logP + b.logP, dontLogAgain);
}
/** Returns true if p is null or NaN. */
private static boolean nullOrNaN(Prob p) {
return (p == null || Double.isNaN(p.logP));
}
/** Returns a new instance with the same value as original. */
private static Prob copy(Prob original) {
return new Prob(original.logP, dontLogAgain);
}
}
class Binary implements Comparable<Binary> {
/**
* Use example: Binary b = new Binary(Long.toBinaryString(53249834L));
*
* When manipulating small binary strings, instantiate new Binary(string)
* When just reading large binary strings, instantiate new Binary(string,true)
* get(int i) returns a character '1' or '0', not an int.
*/
private boolean[] d;
private int first; // Starting from left, the first (most remarkable) '1'
public int length;
public Binary(String binaryString) {
this(binaryString, false);
}
public Binary(String binaryString, boolean initWithMinArraySize) {
length = binaryString.length();
int size = Math.max(2*length, 1);
first = length/4;
if (initWithMinArraySize) {
first = 0;
size = Math.max(length, 1);
}
d = new boolean[size];
for (int i=0; i<length; i++) {
if (binaryString.charAt(i) == '1') d[i+first] = true;
}
}
public void addFirst(char c) {
if (first-1 < 0) doubleArraySize();
first--;
d[first] = (c == '1' ? true : false);
length++;
}
public void addLast(char c) {
if (first+length >= d.length) doubleArraySize();
d[first+length] = (c == '1' ? true : false);
length++;
}
private void doubleArraySize() {
boolean[] bigArray = new boolean[(d.length+1) * 2];
int newFirst = bigArray.length / 4;
for (int i=0; i<length; i++) {
bigArray[i + newFirst] = d[i + first];
}
first = newFirst;
d = bigArray;
}
public boolean flip(int i) {
boolean value = (this.d[first+i] ? false : true);
this.d[first+i] = value;
return value;
}
public void set(int i, char c) {
boolean value = (c == '1' ? true : false);
this.d[first+i] = value;
}
public char get(int i) {
return (this.d[first+i] ? '1' : '0');
}
@Override
public int compareTo(Binary o) {
if (this.length != o.length) return this.length - o.length;
int len = this.length;
for (int i=0; i<len; i++) {
int diff = this.get(i) - o.get(i);
if (diff != 0) return diff;
}
return 0;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i=0; i<length; i++) {
sb.append(d[i+first] ? '1' : '0');
}
return sb.toString();
}
}
/************************** Range queries **************************/
class FenwickMin {
long n;
long[] original;
long[] bottomUp;
long[] topDown;
public FenwickMin(int n) {
this.n = n;
original = new long[n+2];
bottomUp = new long[n+2];
topDown = new long[n+2];
}
public void set(int modifiedNode, long value) {
long replaced = original[modifiedNode];
original[modifiedNode] = value;
// Update left tree
int i = modifiedNode;
long v = value;
while (i <= n) {
if (v > bottomUp[i]) {
if (replaced == bottomUp[i]) {
v = Math.min(v, original[i]);
for (int r=1 ;; r++) {
int x = (i&-i)>>>r;
if (x == 0) break;
int child = i-x;
v = Math.min(v, bottomUp[child]);
}
} else break;
}
if (v == bottomUp[i]) break;
bottomUp[i] = v;
i += (i&-i);
}
// Update right tree
i = modifiedNode;
v = value;
while (i > 0) {
if (v > topDown[i]) {
if (replaced == topDown[i]) {
v = Math.min(v, original[i]);
for (int r=1 ;; r++) {
int x = (i&-i)>>>r;
if (x == 0) break;
int child = i+x;
if (child > n+1) break;
v = Math.min(v, topDown[child]);
}
} else break;
}
if (v == topDown[i]) break;
topDown[i] = v;
i -= (i&-i);
}
}
public long getMin(int a, int b) {
long min = original[a];
int prev = a;
int curr = prev + (prev&-prev); // parent right hand side
while (curr <= b) {
min = Math.min(min, topDown[prev]); // value from the other tree
prev = curr;
curr = prev + (prev&-prev);;
}
min = Math.min(min, original[prev]);
prev = b;
curr = prev - (prev&-prev); // parent left hand side
while (curr >= a) {
min = Math.min(min,bottomUp[prev]); // value from the other tree
prev = curr;
curr = prev - (prev&-prev);
}
return min;
}
}
class FenwickSum {
public long[] d;
public FenwickSum(int n) {
d=new long[n+1];
}
/** a[0] must be unused. */
public FenwickSum(long[] a) {
d=new long[a.length];
for (int i=1; i<a.length; i++) {
modify(i, a[i]);
}
}
/** Do not modify i=0. */
void modify(int i, long v) {
while (i<d.length) {
d[i] += v;
// Move to next uplink on the RIGHT side of i
i += (i&-i);
}
}
/** Returns sum from a to b, *BOTH* inclusive. */
long getSum(int a, int b) {
return getSum(b) - getSum(a-1);
}
private long getSum(int i) {
long sum = 0;
while (i>0) {
sum += d[i];
// Move to next uplink on the LEFT side of i
i -= (i&-i);
}
return sum;
}
}
class SegmentTree {
/** Query sums with log(n) modifyRange */
int N;
long[] p;
public SegmentTree(int n) {
/* TODO: Test that this works. */
for (N=2; N<n; N++) N *= 2;
p = new long[2*N];
}
public void modifyRange(int a, int b, long change) {
muuta(a, change);
muuta(b+1, -change);
}
void muuta(int k, long muutos) {
k += N;
p[k] += muutos;
for (k /= 2; k >= 1; k /= 2) {
p[k] = p[2*k] + p[2*k+1];
}
}
public long get(int k) {
int a = N;
int b = k+N;
long s = 0;
while (a <= b) {
if (a%2 == 1) s += p[a++];
if (b%2 == 0) s += p[b--];
a /= 2;
b /= 2;
}
return s;
}
}
/***************************** Graphs *****************************/
List<Integer>[] toGraph(IO io, int n) {
List<Integer>[] g = new ArrayList[n+1];
for (int i=1; i<=n; i++) g[i] = new ArrayList<>();
for (int i=1; i<=n-1; i++) {
int a = io.nextInt();
int b = io.nextInt();
g[a].add(b);
g[b].add(a);
}
return g;
}
class Graph {
HashMap<Long, List<Long>> edges;
public Graph() {
edges = new HashMap<>();
}
List<Long> getSetNeighbors(Long node) {
List<Long> neighbors = edges.get(node);
if (neighbors == null) {
neighbors = new ArrayList<>();
edges.put(node, neighbors);
}
return neighbors;
}
void addBiEdge(Long a, Long b) {
addEdge(a, b);
addEdge(b, a);
}
void addEdge(Long from, Long to) {
getSetNeighbors(to); // make sure all have initialized lists
List<Long> neighbors = getSetNeighbors(from);
neighbors.add(to);
}
// topoSort variables
int UNTOUCHED = 0;
int FINISHED = 2;
int INPROGRESS = 1;
HashMap<Long, Integer> vis;
List<Long> topoAns;
List<Long> failDueToCycle = new ArrayList<Long>() {{ add(-1L); }};
List<Long> topoSort() {
topoAns = new ArrayList<>();
vis = new HashMap<>();
for (Long a : edges.keySet()) {
if (!topoDFS(a)) return failDueToCycle;
}
Collections.reverse(topoAns);
return topoAns;
}
boolean topoDFS(long curr) {
Integer status = vis.get(curr);
if (status == null) status = UNTOUCHED;
if (status == FINISHED) return true;
if (status == INPROGRESS) {
return false;
}
vis.put(curr, INPROGRESS);
for (long next : edges.get(curr)) {
if (!topoDFS(next)) return false;
}
vis.put(curr, FINISHED);
topoAns.add(curr);
return true;
}
}
public class StronglyConnectedComponents {
/** Kosaraju's algorithm */
ArrayList<Integer>[] forw;
ArrayList<Integer>[] bacw;
/** Use: getCount(2, new int[] {1,2}, new int[] {2,1}) */
public int getCount(int n, int[] mista, int[] minne) {
forw = new ArrayList[n+1];
bacw = new ArrayList[n+1];
for (int i=1; i<=n; i++) {
forw[i] = new ArrayList<Integer>();
bacw[i] = new ArrayList<Integer>();
}
for (int i=0; i<mista.length; i++) {
int a = mista[i];
int b = minne[i];
forw[a].add(b);
bacw[b].add(a);
}
int count = 0;
List<Integer> list = new ArrayList<Integer>();
boolean[] visited = new boolean[n+1];
for (int i=1; i<=n; i++) {
dfsForward(i, visited, list);
}
visited = new boolean[n+1];
for (int i=n-1; i>=0; i--) {
int node = list.get(i);
if (visited[node]) continue;
count++;
dfsBackward(node, visited);
}
return count;
}
public void dfsForward(int i, boolean[] visited, List<Integer> list) {
if (visited[i]) return;
visited[i] = true;
for (int neighbor : forw[i]) {
dfsForward(neighbor, visited, list);
}
list.add(i);
}
public void dfsBackward(int i, boolean[] visited) {
if (visited[i]) return;
visited[i] = true;
for (int neighbor : bacw[i]) {
dfsBackward(neighbor, visited);
}
}
}
class LCAFinder {
/* O(n log n) Initialize: new LCAFinder(graph)
* O(log n) Queries: find(a,b) returns lowest common ancestor for nodes a and b */
int[] nodes;
int[] depths;
int[] entries;
int pointer;
FenwickMin fenwick;
public LCAFinder(List<Integer>[] graph) {
this.nodes = new int[(int)10e6];
this.depths = new int[(int)10e6];
this.entries = new int[graph.length];
this.pointer = 1;
boolean[] visited = new boolean[graph.length+1];
dfs(1, 0, graph, visited);
fenwick = new FenwickMin(pointer-1);
for (int i=1; i<pointer; i++) {
fenwick.set(i, depths[i] * 1000000L + i);
}
}
private void dfs(int node, int depth, List<Integer>[] graph, boolean[] visited) {
visited[node] = true;
entries[node] = pointer;
nodes[pointer] = node;
depths[pointer] = depth;
pointer++;
for (int neighbor : graph[node]) {
if (visited[neighbor]) continue;
dfs(neighbor, depth+1, graph, visited);
nodes[pointer] = node;
depths[pointer] = depth;
pointer++;
}
}
public int find(int a, int b) {
int left = entries[a];
int right = entries[b];
if (left > right) {
int temp = left;
left = right;
right = temp;
}
long mixedBag = fenwick.getMin(left, right);
int index = (int) (mixedBag % 1000000L);
return nodes[index];
}
}
/**************************** Geometry ****************************/
class Point {
int y;
int x;
public Point(int y, int x) {
this.y = y;
this.x = x;
}
}
boolean segmentsIntersect(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) {
// Returns true if segment 1-2 intersects segment 3-4
if (x1 == x2 && x3 == x4) {
// Both segments are vertical
if (x1 != x3) return false;
if (min(y1,y2) < min(y3,y4)) {
return max(y1,y2) >= min(y3,y4);
} else {
return max(y3,y4) >= min(y1,y2);
}
}
if (x1 == x2) {
// Only segment 1-2 is vertical. Does segment 3-4 cross it? y = a*x + b
double a34 = (y4-y3)/(x4-x3);
double b34 = y3 - a34*x3;
double y = a34 * x1 + b34;
return y >= min(y1,y2) && y <= max(y1,y2) && x1 >= min(x3,x4) && x1 <= max(x3,x4);
}
if (x3 == x4) {
// Only segment 3-4 is vertical. Does segment 1-2 cross it? y = a*x + b
double a12 = (y2-y1)/(x2-x1);
double b12 = y1 - a12*x1;
double y = a12 * x3 + b12;
return y >= min(y3,y4) && y <= max(y3,y4) && x3 >= min(x1,x2) && x3 <= max(x1,x2);
}
double a12 = (y2-y1)/(x2-x1);
double b12 = y1 - a12*x1;
double a34 = (y4-y3)/(x4-x3);
double b34 = y3 - a34*x3;
if (closeToZero(a12 - a34)) {
// Parallel lines
return closeToZero(b12 - b34);
}
// Non parallel non vertical lines intersect at x. Is x part of both segments?
double x = -(b12-b34)/(a12-a34);
return x >= min(x1,x2) && x <= max(x1,x2) && x >= min(x3,x4) && x <= max(x3,x4);
}
boolean pointInsideRectangle(Point p, List<Point> r) {
Point a = r.get(0);
Point b = r.get(1);
Point c = r.get(2);
Point d = r.get(3);
double apd = areaOfTriangle(a, p, d);
double dpc = areaOfTriangle(d, p, c);
double cpb = areaOfTriangle(c, p, b);
double pba = areaOfTriangle(p, b, a);
double sumOfAreas = apd + dpc + cpb + pba;
if (closeToZero(sumOfAreas - areaOfRectangle(r))) {
if (closeToZero(apd) || closeToZero(dpc) || closeToZero(cpb) || closeToZero(pba)) {
return false;
}
return true;
}
return false;
}
double areaOfTriangle(Point a, Point b, Point c) {
return 0.5 * Math.abs((a.x-c.x)*(b.y-a.y)-(a.x-b.x)*(c.y-a.y));
}
double areaOfRectangle(List<Point> r) {
double side1xDiff = r.get(0).x - r.get(1).x;
double side1yDiff = r.get(0).y - r.get(1).y;
double side2xDiff = r.get(1).x - r.get(2).x;
double side2yDiff = r.get(1).y - r.get(2).y;
double side1 = Math.sqrt(side1xDiff * side1xDiff + side1yDiff * side1yDiff);
double side2 = Math.sqrt(side2xDiff * side2xDiff + side2yDiff * side2yDiff);
return side1 * side2;
}
boolean pointsOnSameLine(double x1, double y1, double x2, double y2, double x3, double y3) {
double areaTimes2 = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2);
return (closeToZero(areaTimes2));
}
class PointToLineSegmentDistanceCalculator {
// Just call this
double minDistFromPointToLineSegment(double point_x, double point_y, double x1, double y1, double x2, double y2) {
return Math.sqrt(distToSegmentSquared(point_x, point_y, x1, y1, x2, y2));
}
private double distToSegmentSquared(double point_x, double point_y, double x1, double y1, double x2, double y2) {
double l2 = dist2(x1,y1,x2,y2);
if (l2 == 0) return dist2(point_x, point_y, x1, y1);
double t = ((point_x - x1) * (x2 - x1) + (point_y - y1) * (y2 - y1)) / l2;
if (t < 0) return dist2(point_x, point_y, x1, y1);
if (t > 1) return dist2(point_x, point_y, x2, y2);
double com_x = x1 + t * (x2 - x1);
double com_y = y1 + t * (y2 - y1);
return dist2(point_x, point_y, com_x, com_y);
}
private double dist2(double x1, double y1, double x2, double y2) {
return Math.pow((x1 - x2), 2) + Math.pow((y1 - y2), 2);
}
}
/****************************** Math ******************************/
long gcd(long... v) {
/** Chained calls to Euclidean algorithm. */
if (v.length == 1) return v[0];
long ans = gcd(v[1], v[0]);
for (int i=2; i<v.length; i++) {
ans = gcd(ans, v[i]);
}
return ans;
}
long gcd(long a, long b) {
/** Euclidean algorithm. */
if (b == 0) return a;
return gcd(b, a%b);
}
int[] generatePrimesUpTo(int last) {
/* Sieve of Eratosthenes. Practically O(n). Values of 0 indicate primes. */
int[] div = new int[last+1];
for (int x=2; x<=last; x++) {
if (div[x] > 0) continue;
for (int u=2*x; u<=last; u+=x) {
div[u] = x;
}
}
return div;
}
long lcm(long a, long b) {
/** Least common multiple */
return a * b / gcd(a,b);
}
class BaseConverter {
/* Palauttaa luvun esityksen kannassa base */
public String convert(Long number, int base) {
return Long.toString(number, base);
}
/* Palauttaa luvun esityksen kannassa baseTo, kun annetaan luku Stringinä kannassa baseFrom */
public String convert(String number, int baseFrom, int baseTo) {
return Long.toString(Long.parseLong(number, baseFrom), baseTo);
}
/* Tulkitsee kannassa base esitetyn luvun longiksi (kannassa 10) */
public long longify(String number, int baseFrom) {
return Long.parseLong(number, baseFrom);
}
}
class BinomialCoefficients {
/** Total number of K sized unique combinations from pool of size N (unordered)
N! / ( K! (N - K)! ) */
/** For simple queries where output fits in long. */
public long biCo(long n, long k) {
long r = 1;
if (k > n) return 0;
for (long d = 1; d <= k; d++) {
r *= n--;
r /= d;
}
return r;
}
/** For multiple queries with same n, different k. */
public long[] precalcBinomialCoefficientsK(int n, int maxK) {
long v[] = new long[maxK+1];
v[0] = 1; // nC0 == 1
for (int i=1; i<=n; i++) {
for (int j=Math.min(i,maxK); j>0; j--) {
v[j] = v[j] + v[j-1]; // Pascal's triangle
}
}
return v;
}
/** When output needs % MOD. */
public long[] precalcBinomialCoefficientsK(int n, int k, long M) {
long v[] = new long[k+1];
v[0] = 1; // nC0 == 1
for (int i=1; i<=n; i++) {
for (int j=Math.min(i,k); j>0; j--) {
v[j] = v[j] + v[j-1]; // Pascal's triangle
v[j] %= M;
}
}
return v;
}
}
/**************************** Strings ****************************/
class Zalgo {
public int pisinEsiintyma(String haku, String kohde) {
char[] s = new char[haku.length() + 1 + kohde.length()];
for (int i=0; i<haku.length(); i++) {
s[i] = haku.charAt(i);
}
int j = haku.length();
s[j++] = '#';
for (int i=0; i<kohde.length(); i++) {
s[j++] = kohde.charAt(i);
}
int[] z = toZarray(s);
int max = 0;
for (int i=haku.length(); i<z.length; i++) {
max = Math.max(max, z[i]);
}
return max;
}
public int[] toZarray(char[] s) {
int n = s.length;
int[] z = new int[n];
int a = 0, b = 0;
for (int i = 1; i < n; i++) {
if (i > b) {
for (int j = i; j < n && s[j - i] == s[j]; j++) z[i]++;
}
else {
z[i] = z[i - a];
if (i + z[i - a] > b) {
for (int j = b + 1; j < n && s[j - i] == s[j]; j++) z[i]++;
a = i;
b = i + z[i] - 1;
}
}
}
return z;
}
public List<Integer> getStartIndexesWhereWordIsFound(String haku, String kohde) {
// this is alternative use case
char[] s = new char[haku.length() + 1 + kohde.length()];
for (int i=0; i<haku.length(); i++) {
s[i] = haku.charAt(i);
}
int j = haku.length();
s[j++] = '#';
for (int i=0; i<kohde.length(); i++) {
s[j++] = kohde.charAt(i);
}
int[] z = toZarray(s);
List<Integer> indexes = new ArrayList<>();
for (int i=haku.length(); i<z.length; i++) {
if (z[i] < haku.length()) continue;
indexes.add(i);
}
return indexes;
}
}
class StringHasher {
class HashedString {
long[] hashes;
long[] modifiers;
public HashedString(long[] hashes, long[] modifiers) {
this.hashes = hashes;
this.modifiers = modifiers;
}
}
long P;
long M;
public StringHasher() {
initializePandM();
}
HashedString hashString(String s) {
int n = s.length();
long[] hashes = new long[n];
long[] modifiers = new long[n];
hashes[0] = s.charAt(0);
modifiers[0] = 1;
for (int i=1; i<n; i++) {
hashes[i] = (hashes[i-1] * P + s.charAt(i)) % M;
modifiers[i] = (modifiers[i-1] * P) % M;
}
return new HashedString(hashes, modifiers);
}
/**
* Indices are inclusive.
*/
long getHash(HashedString hashedString, int startIndex, int endIndex) {
long[] hashes = hashedString.hashes;
long[] modifiers = hashedString.modifiers;
long result = hashes[endIndex];
if (startIndex > 0) result -= (hashes[startIndex-1] * modifiers[endIndex-startIndex+1]) % M;
if (result < 0) result += M;
return result;
}
// Less interesting methods below
/**
* Efficient for 2 input parameter strings in particular.
*/
HashedString[] hashString(String first, String second) {
HashedString[] array = new HashedString[2];
int n = first.length();
long[] modifiers = new long[n];
modifiers[0] = 1;
long[] firstHashes = new long[n];
firstHashes[0] = first.charAt(0);
array[0] = new HashedString(firstHashes, modifiers);
long[] secondHashes = new long[n];
secondHashes[0] = second.charAt(0);
array[1] = new HashedString(secondHashes, modifiers);
for (int i=1; i<n; i++) {
modifiers[i] = (modifiers[i-1] * P) % M;
firstHashes[i] = (firstHashes[i-1] * P + first.charAt(i)) % M;
secondHashes[i] = (secondHashes[i-1] * P + second.charAt(i)) % M;
}
return array;
}
/**
* Efficient for 3+ strings
* More efficient than multiple hashString calls IF strings are same length.
*/
HashedString[] hashString(String... strings) {
HashedString[] array = new HashedString[strings.length];
int n = strings[0].length();
long[] modifiers = new long[n];
modifiers[0] = 1;
for (int j=0; j<strings.length; j++) {
// if all strings are not same length, defer work to another method
if (strings[j].length() != n) {
for (int i=0; i<n; i++) {
array[i] = hashString(strings[i]);
}
return array;
}
// otherwise initialize stuff
long[] hashes = new long[n];
hashes[0] = strings[j].charAt(0);
array[j] = new HashedString(hashes, modifiers);
}
for (int i=1; i<n; i++) {
modifiers[i] = (modifiers[i-1] * P) % M;
for (int j=0; j<strings.length; j++) {
String s = strings[j];
long[] hashes = array[j].hashes;
hashes[i] = (hashes[i-1] * P + s.charAt(i)) % M;
}
}
return array;
}
void initializePandM() {
ArrayList<Long> modOptions = new ArrayList<>(20);
modOptions.add(353873237L);
modOptions.add(353875897L);
modOptions.add(353878703L);
modOptions.add(353882671L);
modOptions.add(353885303L);
modOptions.add(353888377L);
modOptions.add(353893457L);
P = modOptions.get(new Random().nextInt(modOptions.size()));
modOptions.clear();
modOptions.add(452940277L);
modOptions.add(452947687L);
modOptions.add(464478431L);
modOptions.add(468098221L);
modOptions.add(470374601L);
modOptions.add(472879717L);
modOptions.add(472881973L);
M = modOptions.get(new Random().nextInt(modOptions.size()));
}
}
/*************************** Technical ***************************/
private class IO extends PrintWriter {
private InputStreamReader r;
private static final int BUFSIZE = 1 << 15;
private char[] buf;
private int bufc;
private int bufi;
private StringBuilder sb;
public IO() {
super(new BufferedOutputStream(System.out));
r = new InputStreamReader(System.in);
buf = new char[BUFSIZE];
bufc = 0;
bufi = 0;
sb = new StringBuilder();
}
/** Print, flush, return nextInt. */
private int queryInt(String s) {
io.println(s);
io.flush();
return nextInt();
}
/** Print, flush, return nextLong. */
private long queryLong(String s) {
io.println(s);
io.flush();
return nextLong();
}
/** Print, flush, return next word. */
private String queryNext(String s) {
io.println(s);
io.flush();
return next();
}
private void fillBuf() throws IOException {
bufi = 0;
bufc = 0;
while(bufc == 0) {
bufc = r.read(buf, 0, BUFSIZE);
if(bufc == -1) {
bufc = 0;
return;
}
}
}
private boolean pumpBuf() throws IOException {
if(bufi == bufc) {
fillBuf();
}
return bufc != 0;
}
private boolean isDelimiter(char c) {
return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
}
private void eatDelimiters() throws IOException {
while(true) {
if(bufi == bufc) {
fillBuf();
if(bufc == 0) throw new RuntimeException("IO: Out of input.");
}
if(!isDelimiter(buf[bufi])) break;
++bufi;
}
}
public String next() {
try {
sb.setLength(0);
eatDelimiters();
int start = bufi;
while(true) {
if(bufi == bufc) {
sb.append(buf, start, bufi - start);
fillBuf();
start = 0;
if(bufc == 0) break;
}
if(isDelimiter(buf[bufi])) break;
++bufi;
}
sb.append(buf, start, bufi - start);
return sb.toString();
} catch(IOException e) {
throw new RuntimeException("IO.next: Caught IOException.");
}
}
public int nextInt() {
try {
int ret = 0;
eatDelimiters();
boolean positive = true;
if(buf[bufi] == '-') {
++bufi;
if(!pumpBuf()) throw new RuntimeException("IO.nextInt: Invalid int.");
positive = false;
}
boolean first = true;
while(true) {
if(!pumpBuf()) break;
if(isDelimiter(buf[bufi])) {
if(first) throw new RuntimeException("IO.nextInt: Invalid int.");
break;
}
first = false;
if(buf[bufi] >= '0' && buf[bufi] <= '9') {
if(ret < -214748364) throw new RuntimeException("IO.nextInt: Invalid int.");
ret *= 10;
ret -= (int)(buf[bufi] - '0');
if(ret > 0) throw new RuntimeException("IO.nextInt: Invalid int.");
} else {
throw new RuntimeException("IO.nextInt: Invalid int.");
}
++bufi;
}
if(positive) {
if(ret == -2147483648) throw new RuntimeException("IO.nextInt: Invalid int.");
ret = -ret;
}
return ret;
} catch(IOException e) {
throw new RuntimeException("IO.nextInt: Caught IOException.");
}
}
public long nextLong() {
try {
long ret = 0;
eatDelimiters();
boolean positive = true;
if(buf[bufi] == '-') {
++bufi;
if(!pumpBuf()) throw new RuntimeException("IO.nextLong: Invalid long.");
positive = false;
}
boolean first = true;
while(true) {
if(!pumpBuf()) break;
if(isDelimiter(buf[bufi])) {
if(first) throw new RuntimeException("IO.nextLong: Invalid long.");
break;
}
first = false;
if(buf[bufi] >= '0' && buf[bufi] <= '9') {
if(ret < -922337203685477580L) throw new RuntimeException("IO.nextLong: Invalid long.");
ret *= 10;
ret -= (long)(buf[bufi] - '0');
if(ret > 0) throw new RuntimeException("IO.nextLong: Invalid long.");
} else {
throw new RuntimeException("IO.nextLong: Invalid long.");
}
++bufi;
}
if(positive) {
if(ret == -9223372036854775808L) throw new RuntimeException("IO.nextLong: Invalid long.");
ret = -ret;
}
return ret;
} catch(IOException e) {
throw new RuntimeException("IO.nextLong: Caught IOException.");
}
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
void print(Object output) {
io.println(output);
}
void done(Object output) {
print(output);
done();
}
void done() {
io.close();
throw new RuntimeException("Clean exit");
}
long min(long... v) {
long ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.min(ans, v[i]);
}
return ans;
}
double min(double... v) {
double ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.min(ans, v[i]);
}
return ans;
}
int min(int... v) {
int ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.min(ans, v[i]);
}
return ans;
}
long max(long... v) {
long ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.max(ans, v[i]);
}
return ans;
}
double max(double... v) {
double ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.max(ans, v[i]);
}
return ans;
}
int max(int... v) {
int ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.max(ans, v[i]);
}
return ans;
}
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class Main implements Runnable {
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
}
catch (IOException e) {
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
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 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 double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString() {
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 boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception {
new Thread(null, new Main(),"Main",1<<26).start();
}
long fast_pow(long a, long b) {
if(b == 0)
return 1L;
long val = fast_pow(a, b / 2);
if(b % 2 == 0)
return val * val % mod;
else
return val * val % mod * a % mod;
}
long mod = (long)1e9 + 7;
public void run() {
InputReader sc = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
long x = sc.nextLong();
long k = sc.nextLong();
if(x == 0) {
w.print("0");
w.close();
return;
}
x = x % mod;
long pkp1 = fast_pow(2, k + 1L);
long pk = fast_pow(2, k);
long sub = (pk - 1 + mod) % mod * pk % mod;
long add = x * pkp1 % mod * pk % mod;
long num = (add - sub + mod) % mod;
long deninv = fast_pow(pk, mod - 2);
long ans = num * deninv % mod;
w.print(ans);
w.close();
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.util.*;
import java.io.*;
import java.math.*;
public class main {
InputStream is;
PrintWriter out;
static long mod=pow(10,9)+7;
int dx[]= {0,0,1,-1},dy[]={+1,-1,0,0};
void solve()
{
long x=nl();
long k=nl();
if(x==0)
{
out.println(0);
return;
}
long term=(pow(2,k,mod))%mod;
long last=((x%mod)*pow(2,k+1,mod))%mod;
long sumdom=((2*last)%mod+(((term-1+mod)%mod)*((-2+mod)%mod))%mod)%mod;
sumdom=(sumdom*term)%mod;
sumdom=(sumdom*pow(2,mod-2,mod))%mod;
sumdom=(sumdom*pow(term,mod-2,mod))%mod;
out.println(sumdom);
}
int bsdown(ArrayList<Integer> al,int l) {
int low=0,high=al.size()-1,ans=-1;
while(low<=high) {
int mid=low+(high-low)/2;
if(al.get(mid)<=l) {
low=mid+1;
ans=mid;
}else
high=mid-1;
}
return ans;
}
ArrayList<Integer>al [];
void take(int n,int m)
{
al=new ArrayList[n];
for(int i=0;i<n;i++)
al[i]=new ArrayList<Integer>();
for(int i=0;i<m;i++)
{
int x=ni()-1;
int y=ni()-1;
al[x].add(y);
al[y].add(x);
}
}
int arr[][];
int small[];
void pre(int n)
{
small=new int[n+1];
for(int i=2;i*i<=n;i++)
{
for(int j=i;j*i<=n;j++)
{
if(small[i*j]==0)
small[i*j]=i;
}
}
for(int i=0;i<=n;i++)
{
if(small[i]==0)
small[i]=i;
}
}
public static int count(long x)
{
int num=0;
while(x!=0)
{
x=x&(x-1);
num++;
}
return num;
}
static long d, x, y;
void extendedEuclid(long A, long B) {
if(B == 0) {
d = A;
x = 1;
y = 0;
}
else {
extendedEuclid(B, A%B);
long temp = x;
x = y;
y = temp - (A/B)*y;
}
}
long modInverse(long A,long M) //A and M are coprime
{
extendedEuclid(A,M);
return (x%M+M)%M; //x may be negative
}
public static void mergeSort(int[] arr, int l ,int r){
if((r-l)>=1){
int mid = (l+r)/2;
mergeSort(arr,l,mid);
mergeSort(arr,mid+1,r);
merge(arr,l,r,mid);
}
}
public static void merge(int arr[], int l, int r, int mid){
int n1 = (mid-l+1), n2 = (r-mid);
int left[] = new int[n1];
int right[] = new int[n2];
for(int i =0 ;i<n1;i++) left[i] = arr[l+i];
for(int i =0 ;i<n2;i++) right[i] = arr[mid+1+i];
int i =0, j =0, k = l;
while(i<n1 && j<n2){
if(left[i]>right[j]){
arr[k++] = right[j++];
}
else{
arr[k++] = left[i++];
}
}
while(i<n1) arr[k++] = left[i++];
while(j<n2) arr[k++] = right[j++];
}
public static void mergeSort(long[] arr, int l ,int r){
if((r-l)>=1){
int mid = (l+r)/2;
mergeSort(arr,l,mid);
mergeSort(arr,mid+1,r);
merge(arr,l,r,mid);
}
}
public static void merge(long arr[], int l, int r, int mid){
int n1 = (mid-l+1), n2 = (r-mid);
long left[] = new long[n1];
long right[] = new long[n2];
for(int i =0 ;i<n1;i++) left[i] = arr[l+i];
for(int i =0 ;i<n2;i++) right[i] = arr[mid+1+i];
int i =0, j =0, k = l;
while(i<n1 && j<n2){
if(left[i]>right[j]){
arr[k++] = right[j++];
}
else{
arr[k++] = left[i++];
}
}
while(i<n1) arr[k++] = left[i++];
while(j<n2) arr[k++] = right[j++];
}
static class Pair implements Comparable<Pair>{
long x;
long y,k;
int i,h;
String s;
Pair (long x,long y,int i){
this.x=x;
this.y=y;
this.i=i;
}
public int compareTo(Pair o) {
if(this.x!=o.x)
return Long.compare(this.x,o.x);
return Long.compare(this.y,o.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() ;
}
@Override
public String toString() {
return "("+x + " " + y +" "+k+" "+i+" )";
}
}
public static boolean isPal(String s){
for(int i=0, j=s.length()-1;i<=j;i++,j--){
if(s.charAt(i)!=s.charAt(j)) return false;
}
return true;
}
public static String rev(String s){
StringBuilder sb=new StringBuilder(s);
sb.reverse();
return sb.toString();
}
public static long gcd(long x,long y){
if(x%y==0)
return y;
else
return gcd(y,x%y);
}
public static int gcd(int x,int y){
if(y==0)
return x;
return gcd(y,x%y);
}
public static long gcdExtended(long a,long b,long[] x){
if(a==0){
x[0]=0;
x[1]=1;
return b;
}
long[] y=new long[2];
long gcd=gcdExtended(b%a, a, y);
x[0]=y[1]-(b/a)*y[0];
x[1]=y[0];
return gcd;
}
public static int abs(int a,int b){
return (int)Math.abs(a-b);
}
public static long abs(long a,long b){
return (long)Math.abs(a-b);
}
public static int max(int a,int b){
if(a>b)
return a;
else
return b;
}
public static int min(int a,int b){
if(a>b)
return b;
else
return a;
}
public static long max(long a,long b){
if(a>b)
return a;
else
return b;
}
public static long min(long a,long b){
if(a>b)
return b;
else
return a;
}
public static long pow(long n,long p,long m){
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
if(result>=m)
result%=m;
p >>=1;
n*=n;
if(n>=m)
n%=m;
}
return result;
}
public static long pow(long n,long p){
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
p >>=1;
n*=n;
}
return result;
}
public static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
void run() throws Exception {
is = System.in;
out = new PrintWriter(System.out);
solve();
out.flush();
}
public static void main(String[] args) throws Exception {
new Thread(null, new Runnable() {
public void run() {
try {
new main().run();
} catch (Exception e) {
e.printStackTrace();
}
}
}, "1", 1 << 26).start();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b));
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private long[] nl(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nl();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
/*
*
* @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 Code3
{
public static void main(String[] args)
{
InputReader in = new InputReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
long x = in.nextLong();
long k = in.nextLong();
if(x==0)
pw.println(0);
else
{
long mul = modularExponentiation(2L, k, mod);
x = (x%mod * 2L%mod)%mod;
x = (x%mod - 1L%mod + mod)%mod;
x = (x%mod * mul%mod)%mod;
x = (x%mod + 1%mod)%mod;
pw.print(x);
}
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 p.x == x && p.y == y ;
}
return false;
}
public int hashCode()
{
return new Long(x).hashCode()*31 + new Long(y).hashCode();
}
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Main {
long mod = (long) (1e9 + 7);
void solve() throws Throwable {
long x = readLong(), k = readLong();
if (x == 0) {
System.out.println(0);
return;
}
long r = solveFast(x, k);
//long r2 = solveSlow(x, k) % mod;
System.out.println(r);
//System.out.println(r2);
}
private long solveSlow(long x, long k) {
List<Long> a = new ArrayList<>();
a.add(x);
for (int i = 0; i < k; i++) {
dodouble(a);
a = eat(a);
}
dodouble(a);
long sum = 0;
for (Long v : a) {
sum = (sum + v) % mod;
}
return sum * rev(a.size(), mod) % mod;
}
private List<Long> eat(List<Long> a) {
List<Long> r = new ArrayList<>();
for (Long v : a) {
r.add(v);
r.add((v - 1 + mod) % mod);
}
return r;
}
private void dodouble(List<Long> a) {
for (int i = 0; i < a.size(); i++) {
a.set(i, a.get(i) * 2 % mod);
}
}
private long solveFast(long x, long k) {
long n = binpow(2, k, mod);
long ma = (binpow(2, k + 1, mod) * (x % mod)) % mod;
long mi = (ma - n * 2 + 2 + mod * 100) % mod;
return ((ma + mi) * rev(2, mod)) % mod;
}
private long rev(long a, long mod) {
return binpow(a, mod - 2, mod);
}
//-------------------------------------------------
final boolean ONLINE_JUDGE = !new File("input.txt").exists();
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
public void run() {
Runnable run = () -> {
try {
long startTime = System.currentTimeMillis();
Locale.setDefault(Locale.US);
if (ONLINE_JUDGE) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
tok = new StringTokenizer("");
solve();
in.close();
out.close();
long endTime = System.currentTimeMillis();
long totalMemory = Runtime.getRuntime().totalMemory();
long freeMemory = Runtime.getRuntime().freeMemory();
System.err.println();
System.err.println("Time = " + (endTime - startTime) + " ms");
//System.err.println("Memory = " + ((totalMemory - freeMemory) / 1024) + " KB");
} catch (Throwable e) {
e.printStackTrace(System.err);
System.exit(-1);
}
};
new Thread(null, run, "run", 256 * 1024 * 1024).start();
min(0, 0);
}
String readString() {
while (!tok.hasMoreTokens()) {
String line;
try {
line = in.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (line == null) return null;
tok = new StringTokenizer(line);
}
return tok.nextToken();
}
int readInt() {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
void debug(Object... o) {
if (!ONLINE_JUDGE) {
System.err.println(Arrays.deepToString(o));
}
}
/*long binpow(long a, long n) {
long r = 1;
while (n > 0) {
if ((n & 1) > 0) {
r *= a;
}
a *= a;
n /= 2;
}
return r;
}/**/
long binpow(long a, long n, long mod) {
long r = 1;
while (n > 0) {
if ((n & 1) > 0) {
r = (r * a) % mod;
}
a = (a * a) % mod;
n /= 2;
}
return r;
}/**/
static long gcd(long x, long y) {
return y == 0 ? x : gcd(y, x % y);
}
private long[] readLongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = readLong();
}
return a;
}
public static void main(String[] args) {
new Main().run();
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
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 kanak893
*/
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);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader fi, PrintWriter out) {
long n, k;
n = fi.nextLong();
k = fi.nextLong();
long ans = 2 * n;
long mod = (long) Math.pow(10, 9) + 7;
if (k > 0) {
ans = (modulus(modulus(pow(2, k + 1, mod), mod) * modulus(n, mod), mod));
long temp = modulus(pow(2, k, mod) - 1, mod);
ans = modulus(modulus(ans, mod) - modulus(temp, mod), mod);
}
if (n == 0) {
ans = 0;
}
ans=ans%mod;
out.println(ans);
}
static long pow(long x, long y, long mod) {
if (y == 0) return 1 % mod;
if (y == 1) return x % mod;
long res = 1;
x = x % mod;
while (y > 0) {
if ((y % 2) != 0) {
res = (res * x) % mod;
}
y = y / 2;
x = (x * x) % mod;
}
return res;
}
static long modulus(long a, long mod) {
return (a % mod + mod) % mod;
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int snumChars;
private InputReader.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 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 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);
}
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import sun.rmi.transport.DGCImpl_Stub;
import java.io.*;
import java.nio.file.ClosedWatchServiceException;
import java.util.*;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
ConsoleIO io = new ConsoleIO(new InputStreamReader(System.in), new PrintWriter(System.out));
// String fileName = "C-large";
// ConsoleIO io = new ConsoleIO(new FileReader("D:\\Dropbox\\code\\practice\\jb\\src\\" + fileName + ".in"), new PrintWriter(new File("D:\\Dropbox\\code\\practice\\jb\\src\\" + fileName + ".out")));
new Main(io).solve();
// new Main(io).solveLocal();
io.close();
}
ConsoleIO io;
Main(ConsoleIO io) {
this.io = io;
}
ConsoleIO opt;
Main(ConsoleIO io, ConsoleIO opt) {
this.io = io;
this.opt = opt;
}
List<List<Integer>> gr = new ArrayList<>();
long MOD = 1_000_000_007;
public void solve() {
long x = io.readLong(), k = io.readLong();
if(x==0){
io.writeLine("0");
return;
}
long res = ((pow(2, k+1, MOD) * (x % MOD)) % MOD - pow(2, k, MOD) % MOD + 1 + MOD) % MOD;
io.writeLine(res+"");
}
long pow(long a, long p, long mod) {
long res = 1;
while (p > 0) {
if (p % 2 == 1) res = (res * a) % mod;
a = (a * a) % mod;
p /= 2;
}
return res;
}
}
class ConsoleIO {
BufferedReader br;
PrintWriter out;
public ConsoleIO(Reader reader, PrintWriter writer){br = new BufferedReader(reader);out = writer;}
public void flush(){this.out.flush();}
public void close(){this.out.close();}
public void writeLine(String s) {this.out.println(s);}
public void writeInt(int a) {this.out.print(a);this.out.print(' ');}
public void writeWord(String s){
this.out.print(s);
}
public void writeIntArray(int[] a, int k, String separator) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < k; i++) {
if (i > 0) sb.append(separator);
sb.append(a[i]);
}
this.writeLine(sb.toString());
}
public int read(char[] buf, int len){try {return br.read(buf,0,len);}catch (Exception ex){ return -1; }}
public String readLine() {try {return br.readLine();}catch (Exception ex){ return "";}}
public long[] readLongArray() {
String[]n=this.readLine().trim().split("\\s+");long[]r=new long[n.length];
for(int i=0;i<n.length;i++)r[i]=Long.parseLong(n[i]);
return r;
}
public int[] readIntArray() {
String[]n=this.readLine().trim().split("\\s+");int[]r=new int[n.length];
for(int i=0;i<n.length;i++)r[i]=Integer.parseInt(n[i]);
return r;
}
public int[] readIntArray(int n) {
int[] res = new int[n];
char[] all = this.readLine().toCharArray();
int cur = 0;boolean have = false;
int k = 0;
boolean neg = false;
for(int i = 0;i<all.length;i++){
if(all[i]>='0' && all[i]<='9'){
cur = cur*10+all[i]-'0';
have = true;
}else if(all[i]=='-') {
neg = true;
}
else if(have){
res[k++] = neg?-cur:cur;
cur = 0;
have = false;
neg = false;
}
}
if(have)res[k++] = neg?-cur:cur;
return res;
}
public int ri() {
try {
int r = 0;
boolean start = false;
boolean neg = false;
while (true) {
int c = br.read();
if (c >= '0' && c <= '9') {
r = r * 10 + c - '0';
start = true;
} else if (!start && c == '-') {
start = true;
neg = true;
} else if (start || c == -1) return neg ? -r : r;
}
} catch (Exception ex) {
return -1;
}
}
public long readLong() {
try {
long r = 0;
boolean start = false;
boolean neg = false;
while (true) {
int c = br.read();
if (c >= '0' && c <= '9') {
r = r * 10 + c - '0';
start = true;
} else if (!start && c == '-') {
start = true;
neg = true;
} else if (start || c == -1) return neg ? -r : r;
}
} catch (Exception ex) {
return -1;
}
}
public String readWord() {
try {
boolean start = false;
StringBuilder sb = new StringBuilder();
while (true) {
int c = br.read();
if (c!= ' ' && c!= '\r' && c!='\n' && c!='\t') {
sb.append((char)c);
start = true;
} else if (start || c == -1) return sb.toString();
}
} catch (Exception ex) {
return "";
}
}
public char readSymbol() {
try {
while (true) {
int c = br.read();
if (c != ' ' && c != '\r' && c != '\n' && c != '\t') {
return (char) c;
}
}
} catch (Exception ex) {
return 0;
}
}
//public char readChar(){try {return (char)br.read();}catch (Exception ex){ return 0; }}
}
class Pair {
public Pair(int a, int b) {this.a = a;this.b = b;}
public int a;
public int b;
}
class PairLL {
public PairLL(long a, long b) {this.a = a;this.b = b;}
public long a;
public long b;
}
class Triple {
public Triple(int a, int b, int c) {this.a = a;this.b = b;this.c = c;}
public int a;
public int b;
public int c;
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner scan=new Scanner(System.in);
long x=scan.nextLong();
long k=scan.nextLong();
long MOD=1000000007;
if(x==0){System.out.println(0);return;}
x%=MOD;
long a=(new Num()).pow(2L,k+1);
long b=(new Num()).pow(2L,k);
long res=(a*x)%MOD-b+1;
if(res<0){res+=MOD;}
System.out.println(res%MOD);
}
}
class Num{
long MOD=1000000007;
long pow(long x,long k){
long base=x%MOD;
long res=1;
while(k>0){
if((k&1)==1){
res=(res*base)%MOD;
}
base=(base*base)%MOD;
k>>=1;
}
return res;
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
static BigInteger tow=new BigInteger("2"),mod=new BigInteger("1000000007");
static BigInteger pow(BigInteger a,BigInteger b) {
if(b.equals(BigInteger.ZERO))return BigInteger.ONE;
BigInteger x=pow(a,b.divide(tow));
if(b.mod(tow).equals(BigInteger.ZERO))
return x.mod(mod).multiply(x.mod(mod)).mod(mod);
else
return x.mod(mod).multiply(x.mod(mod)).mod(mod).multiply(a).mod(mod);
}
public static void main(String[] args) throws IOException {
BigInteger x=in.RB(),k=in.RB();
if(k.equals(BigInteger.ZERO))System.out.println(x.multiply(tow).mod(mod));
else if(x.equals(BigInteger.ZERO))System.out.println(0);
else {
BigInteger x1=tow.multiply(x).subtract(BigInteger.ONE);
x1=x1.mod(mod);
BigInteger x2=pow(tow,k);
x2=x2.mod(mod);
System.out.println(x1.multiply(x2).add(BigInteger.ONE).mod(mod));
}
}
}
class in{
static StringTokenizer st=new StringTokenizer("");
static BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
static String next() throws IOException {
while(!st.hasMoreTokens())st=new StringTokenizer(bf.readLine());
return st.nextToken();
}
static int RI() throws IOException {
return Integer.parseInt(next());
}
static BigInteger RB() throws IOException {
return new BigInteger(next());
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
static BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer tok;
static boolean hasNext()
{
while(tok==null||!tok.hasMoreTokens())
try{
tok=new StringTokenizer(in.readLine());
}
catch(Exception e){
return false;
}
return true;
}
static String next()
{
hasNext();
return tok.nextToken();
}
static long nextLong()
{
return Long.parseLong(next());
}
static int nextInt()
{
return Integer.parseInt(next());
}
static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out));
public static void main(String args []){
long x = nextLong();
long a = 2, b = nextLong(), c = 1000000000+7;
long res = 1;
a %= c;
if (x==0){
out.println(0);
out.flush();
return;
}
for (; b != 0; b /= 2) {
if (b % 2 == 1)
res = (res * a) % c;
a = (a * a) % c;
}
BigInteger r = new BigInteger(String.valueOf(res));
BigInteger y = new BigInteger(String.valueOf(x));
BigInteger ans = y.multiply(new BigInteger("2")).subtract(new BigInteger("1")).multiply(r).add(new BigInteger("1")).mod(new BigInteger(String.valueOf(c)));
out.println(ans);
out.flush();
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.IOException;
import java.io.InputStream;
import java.util.InputMismatchException;
public class Main {
static long MOD = (long) 1e9 + 7;
static long[][] identity = {{1, 0}, {0, 1}};
public static void main(String[] args) {
FastScanner input = new FastScanner(System.in);
long x = input.nextLong();
long k = input.nextLong();
long[][] matrix = {
{2, MOD - 1},
{0, 1}
};
if (x == 0)
System.out.println(0);
else if (k == 0) {
System.out.println((x * 2) % MOD);
} else {
x %= MOD;
matrix = matrixexpo(k, matrix);
long low = (x * matrix[0][0] + matrix[0][1]) % MOD;
long hi = x * mathpow(k, 2) % MOD;
System.out.println((low + hi) % MOD);
}
}
static long mathpow(long k, long x) {
if (k == 0)
return 1L;
else return mathpow(k / 2, (x * x) % MOD) * (k % 2 == 1 ? x : 1) % MOD;
}
static long[][] matrixexpo(long k, long[][] matrix) {
if (k == 0)
return identity;
if (k % 2 == 0)
return matrixexpo(k / 2, multiply(matrix, matrix));
else
return multiply(matrix, matrixexpo(k / 2, multiply(matrix, matrix)));
}
static long[][] multiply(long[][] arr, long[][] brr) {
int n = arr.length, m = arr[0].length, p = brr[0].length;
long[][] product = new long[n][p];
for (int i = 0; i < n; i++)
for (int j = 0; j < p; j++)
for (int k = 0; k < m; k++)
product[i][j] = (product[i][j] + arr[i][k] * brr[k][j]) % MOD;
return product;
}
// Matt Fontaine's Fast IO
static class FastScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastScanner(InputStream stream) {
this.stream = stream;
}
int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
boolean isEndline(int c) {
return c == '\n' || c == '\r' || c == -1;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
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();
}
String nextLine() {
int c = read();
while (isEndline(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndline(c));
return res.toString();
}
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.io.*;
public class Test5{
static long mod=1000000007;
public static void main(String[] z) throws Exception{
Scanner s = new Scanner(System.in);
long a = s.nextLong(), b=s.nextLong(), c=(a*2-1)%mod, i=binpow(2,b)%mod;
System.out.println(a<1 ? a : (c*i+1)%mod);
}
static long binpow(long c, long step){
if(step==0) return 1;
if(step==1) return c%mod;
if(step%2<1){
return binpow(((c%mod)*(c%mod))%mod, step/2)%mod;
}
else{
return (c%mod)*(binpow(c%mod, step-1)%mod);
}
}
static class PyraSort {
private static int heapSize;
public static void sort(int[] a) {
buildHeap(a);
while (heapSize > 1) {
swap(a, 0, heapSize - 1);
heapSize--;
heapify(a, 0);
}
}
private static void buildHeap(int[] a) {
heapSize = a.length;
for (int i = a.length / 2; i >= 0; i--) {
heapify(a, i);
}
}
private static void heapify(int[] a, int i) {
int l = 2 * i + 2;
int r = 2 * i + 1;
int largest = i;
if (l < heapSize && a[i] < a[l]) {
largest = l;
}
if (r < heapSize && a[largest] < a[r]) {
largest = r;
}
if (i != largest) {
swap(a, i, largest);
heapify(a, largest);
}
}
private static void swap(int[] a, int i, int j) {
a[i] ^= a[j] ^= a[i];
a[j] ^= a[i];
}
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author bacali
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
CNastyaAndAWardrobe solver = new CNastyaAndAWardrobe();
solver.solve(1, in, out);
out.close();
}
static class CNastyaAndAWardrobe {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
long mod = (long) (1e9 + 7);
long n = in.nextLong();
long k = in.nextLong();
if (n == 0) {
out.println(0);
return;
}
long c = (((2 * n - 1) % mod) * pow(2L, k, mod)) % mod + 1;
c %= mod;
out.println(c);
}
public long pow(long a, long b, long mod) {
long result = 1;
while (b > 0) {
if (b % 2 != 0) {
result *= a;
result %= mod;
b--;
}
a *= a;
a %= mod;
b /= 2;
}
return result % mod;
}
}
static class FastScanner {
private BufferedReader br;
private StringTokenizer st;
public FastScanner(InputStream inputStream) {
br = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.util.*;
public class prob
{
public static long ans(long x, long y, long p)
{
long r = 1;
x = x % p;
while (y > 0)
{
if((y & 1)==1)
r = (r * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return r;
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner scan = new Scanner(System.in);
long x = scan.nextLong();
long k = scan.nextLong();
long v = 1000000007L;
if(x>0){
long p = ((2*x)-1)%v;
long a = ans(2L,k,v);
long b = (p*a)%v;
System.out.println((b+1)%v);
}
else{
System.out.println(0);
}
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.HashSet;
import java.util.StringTokenizer;
/**
* Created by artur on 18/06/18
*/
public class A
{
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private StringTokenizer tokenizer = null;
long mod = 1000000007;
public static void main(String[] args) throws IOException
{
new A().solve();
}
private void solve() throws IOException
{
long x = nl();
long k = nl();
if (x == 0)
{
System.out.println(0);
System.exit(0);
}
if (k == 0)
{
System.out.println((x * 2) % mod);
System.exit(0);
}
// for (int sx = 0; sx < 100; sx++)
// {
// for (int sk = 0; sk < 100; sk++)
// {
// BigInteger n = BigInteger.valueOf(2)
// .modPow(BigInteger.valueOf(k + 1), BigInteger.valueOf(mod))
// .multiply(BigInteger.valueOf(x))
// .add(BigInteger.ONE)
// .subtract(BigInteger.valueOf(2)
// .modPow(BigInteger.valueOf(k), BigInteger.valueOf(mod)))
// .mod(BigInteger.valueOf(mod));
// long res = n.longValue();
//
// long aux = aux(sx, sk);
// if ((res % mod) != aux) {
// System.out.println(sx + " " + sk + ": " + res + " " + aux);
// }
// }
// }
BigInteger n = BigInteger.valueOf(2)
.modPow(BigInteger.valueOf(k + 1), BigInteger.valueOf(mod))
.multiply(BigInteger.valueOf(x))
.add(BigInteger.ONE)
.subtract(BigInteger.valueOf(2)
.modPow(BigInteger.valueOf(k), BigInteger.valueOf(mod)))
.mod(BigInteger.valueOf(mod));
System.out.println(n.toString());
}
long aux(long x, long k) {
long p1 = 2 * x;
long p2 = 2 * x - 1;
for (int i = 0; i < k - 1; i++)
{
p1 = (p1 * 2) % mod;
p2 = (p2 * 2 - 1) % mod;
}
return ((p1 + p2) % mod);
}
void debug(Object... os)
{
System.out.println(Arrays.deepToString(os));
}
int ni() throws IOException
{
return Integer.parseInt(ns());
}
long nl() throws IOException
{
return Long.parseLong(ns());
}
double nd() throws IOException
{
return Double.parseDouble(ns());
}
String ns() throws IOException
{
while (tokenizer == null || !tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(br.readLine());
return tokenizer.nextToken();
}
String nline() throws IOException
{
tokenizer = null;
return br.readLine();
}
private static long gcd(long a, long b)
{
while (b > 0)
{
long temp = b;
b = a % b; // % is remainder
a = temp;
}
return a;
}
private static long lcm(long a, long b)
{
return a * (b / gcd(a, b));
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.Stack;
import java.util.StringTokenizer;
public class Main {
static boolean visited[] ;
static boolean ends[] ;
static long mod = 1000000007 ;
static int lens[] ;
static int seeds[] ;
static int a[] ;
static double total ;
public static ArrayList adj[] ;
public static long x,y ;
public static ArrayList<Long> xx ;
public static void main(String[] args) throws IOException, InterruptedException {
Scanner sc = new Scanner(System.in) ;
long x = sc.nextLong() ;
long k = sc.nextLong() ;
if(x==0)
{System.out.println(0); return ;}
if(k==0)
{System.out.println((2l*x)%mod);return ;}
long m=pow(2,k);
long a = 2l*(x%mod)*(m%mod);
a = a-m+1 ;
a=a%mod ;
if(a<0)a=(a%mod + mod) % mod;
System.out.println(a);
}
// method to print the divisors
static ArrayList<Long> divisors(long n)
{
ArrayList<Long> arr = new ArrayList<Long>() ;
// Note that this loop runs till square root
for (int i=1; i<=Math.sqrt(n); i++)
{
if (n%i==0)
// If divisors are equal, print only one
if (n/i == i)
{arr.add(1l*i);arr.add(1l*i);}
else // Otherwise print both
{arr.add(1l*i); arr.add(1l*n/i);}
}
return arr ;
}
public static void generate(long current)
{
if(current>10000000000l)
return ;
xx.add(current) ;
generate((10*current) +4);
generate((10*current) +7);
}
public static int neededFromLeft(String x)
{
Stack<Character> st = new Stack<Character>() ;
int c=0;
for (int i = 0; i < x.length(); i++)
{
char cur = x.charAt(i);
if(cur==')' && st.isEmpty())
c ++;
else if(cur==')' && !st.isEmpty())
st.pop();
else if(cur=='(')
st.push(cur);
}
return c;
}
public static int neededFromRight(String x)
{
Stack<Character> st = new Stack<Character>() ;
int c=0;
boolean f=true;
for (int i = 0; i < x.length(); i++)
{
char cur = x.charAt(i);
if(cur==')' && st.isEmpty())
f=false;
else if(cur==')' && !st.isEmpty())
st.pop();
else if(cur=='(')
st.push(cur);
}
return st.size();
}
public static boolean fromBoth(String x)
{
Stack<Character> st = new Stack<Character>() ;
boolean f1=true ,f2=true ;
for (int i = 0; i < x.length(); i++)
{
char cur = x.charAt(i);
if(cur==')' && st.isEmpty())
f1 =false ;
else if(cur==')' && !st.isEmpty())
st.pop();
else if(cur=='(')
st.push(cur);
}
if(st.size()>0)f2 = false ;
if(f1==false && f2==false)
return true ;
else
return false;
}
public static boolean isRegular(String x)
{
Stack<Character> st = new Stack<Character>() ;
for (int i = 0; i < x.length(); i++)
{
char cur = x.charAt(i);
if(cur==')' && st.isEmpty())
return false ;
else if(cur==')' && !st.isEmpty())
st.pop();
else if(cur=='(')
st.push(cur);
}
if(st.size()>0)return false ; else return true ;
}
public static int gcdExtended(int a, int b)
{
// Base Case
if (a == 0)
{
x = 0;
y = 1;
return b;
}
//int x1=1, y1=1; // To store results of recursive call
int gcd = gcdExtended(b%a, a);
// Update x and y using results of recursive
// call
long x1 = y - (b/a) * x;
long y1 = x;
x = x1 ;
y = y1 ;
return gcd;
}
static int even(String x , int b )
{
for (int j = b; j>=0; j--)
{
int current = x.charAt(j)-48 ;
if(current%2==0)
return current ;
}
return -1;
}
static int odd(String x , int b )
{
for (int j = b; j>=0; j--)
{
int current = x.charAt(j)-48 ;
if(current%2!=0)
return current ;
}
return -1;
}
static long pow(long base, long k) {
long res = 1;
while(k > 0) {
if(k % 2 == 1) {
res = (res * base) % mod;
}
base = (base * base) % mod;
k /= 2;
}
return res;
}
public static long solve(int k1, long k2)
{
long x = 1l*k2*(pow(2, k1)-1) ;
return x%(1000000007) ;
}
public static long getN(long x)
{
long n = (long) Math.sqrt(x*2) ;
long y = n*(n+1)/2;
if(y==x)
return n ;
else if(y>x)
return n ;
else
for (long i = n; ; i++)
{
y = i*(i+1)/2 ;
if(y>=x)
return i ;
} }
public static void dfss(int root , int len)
{
visited[root]=true ;
if(ends[root] && root!=0) lens[root] = len ;
for (int i = 0; i < adj[root].size(); i++)
{
int c= (int) adj[root].get(i) ;
if(visited[c]==false)
dfss(c, len+1);
}
}
public static void pr(int root , int seed){
visited[root] = true ;
int dv = adj[root].size()-1 ;
if(root==0) dv++ ;
for (int i = 0; i < adj[root].size(); i++)
{
int c = (int)adj[root].get(i) ;
seeds[c]=dv*seed ;
}
for (int i = 0; i < adj[root].size() ; i++)
{
int c = (int)adj[root].get(i) ;
if(visited[c]==false)
pr(c , seeds[c]);
}
}
public static String concatinate(String s ,int n)
{
if(s.length()==n)
return s ;
else return concatinate("0"+s, n) ;
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
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());
}
public boolean ready() throws IOException {
return br.ready();
}
}
public static long getGCD(long n1, long n2) {
if (n2 == 0) {
return n1;
}
return getGCD(n2, n1 % n2);
}
public static int cnt1(int mat[][]) //how many swaps to be a 1 matrix
{
int m = mat.length ;
int c=0 ;
for (int i = 0; i < mat.length; i++)
{
for (int j = 0; j < mat.length; j++)
{
int x = (i*m) +j ;
if(x%2==0 && mat[i][j]==0)
c++;
if(x%2!=0 && mat[i][j]==1)
c++;
}
}
return c;
}
public static int cnt0(int mat[][])
{
int m = mat.length ;
int c=0 ;
for (int i = 0; i < mat.length; i++)
{
for (int j = 0; j < mat.length; j++)
{
int x = (i*m) +j ;
if(x%2!=0 && mat[i][j]==0)
c++;
if(x%2==0 && mat[i][j]==1)
c++;
}
}
return c;
}
public static boolean canFit2(int x1, int y1 , int x2 , int y2 , int x3 , int y3){
if(x1==x2)
if(x1==x3)
return true ;
else
return false ;
else
if(x1==x3)
return false ;
else
{
long a = 1l*(y2-y1)*(x3-x2) ;
long b = 1l*(y3-y2)*(x2-x1) ;
if(a==b)
return true;
else
return false ;
}
}
public static void shuffle(pair[] ss){
if(ss.length==1)
return ;
for (int i = 0; i < ss.length; i++)
{
Random rand = new Random();
int n = rand.nextInt(ss.length-1) + 0;
pair temp = ss[i] ;
ss[i] = ss[n] ;
ss[n] = temp ;
}
}
public static int binary(ArrayList<pair> arr, int l, int r, long x) /// begin by 0 and n-1
{
if (r>=l)
{
int mid = l + (r - l)/2;
if (arr.get(mid).x== x)
return mid;
if (arr.get(mid).x> x)
return binary(arr, l, mid-1, x);
return binary(arr, mid+1, r, x);
}
return -1;
}
/// searching for the index of first elment greater than x
public static int binary1(int[]arr , int x) {
int low = 0, high = arr.length; // numElems is the size of the array i.e arr.size()
while (low != high) {
int mid = (low + high) / 2; // Or a fancy way to avoid int overflow
if (arr[mid] <= x) {
/* This index, and everything below it, must not be the first element
* greater than what we're looking for because this element is no greater
* than the element.
*/
low = mid + 1;
}
else {
/* This element is at least as large as the element, so anything after it can't
* be the first element that's at least as large.
*/
high = mid;
}
}
return low ; // return high ;
}
////// searching for last element less than X
public static int binary2(pair[]arr , int x) {
int low = 0, high = arr.length; // numElems is the size of the array i.e arr.size()
while (low != high) {
int mid = (low + high) / 2; // Or a fancy way to avoid int overflow
if (arr[mid].x >= x) {
/* This index, and everything below it, must not be the first element
* greater than what we're looking for because this element is no greater
* than the element.
*/
high=mid;
}
else {
/* This element is at least as large as the element, so anything after it can't
* be the first element that's at least as large.
*/
low = mid+1 ;
}
}
return low ; // return high ;
}
private static boolean triangle(int a, int b , int c){
if(a+b>c && a+c>b && b+c>a)
return true ;
else
return false ;
}
private static boolean segment(int a, int b , int c){
if(a+b==c || a+c==b && b+c==a)
return true ;
else
return false ;
}
private static int gcdThing(long a, long b) {
BigInteger b1 = BigInteger.valueOf(a);
BigInteger b2 = BigInteger.valueOf(b);
BigInteger gcd = b1.gcd(b2);
return gcd.intValue();
}
public static boolean is(int i){
if(Math.log(i)/ Math.log(2) ==(int) (Math.log(i)/ Math.log(2)))
return true ;
if(Math.log(i)/ Math.log(3) ==(int) (Math.log(i)/ Math.log(3)) )
return true ;
if(Math.log(i)/ Math.log(6) ==(int) (Math.log(i)/ Math.log(6)) )
return true ;
return false;
}
public static boolean contains(int b[] , int x)
{
for (int i = 0; i < b.length; i++)
{
if(b[i]==x)
return true ;
}
return false ;
}
public static int binary(long []arr , long target , int low , long shift) {
int high = arr.length;
while (low != high) {
int mid = (low + high) / 2;
if (arr[mid]-shift <= target) {
low = mid + 1;
}
else {
high = mid;
}
}
return low ; // return high ;
}
public static boolean isLetter(char x){
if(x+0 <=122 && x+0 >=97 )
return true ;
else if (x+0 <=90 && x+0 >=65 )
return true ;
else return false;
}
public static long getPrimes(long x ){
if(x==2 || x==3 || x==1)
return 2 ;
if(isPrime(x))
return 5 ;
for (int i = 2; i*i<=x; i++)
{
if(x%i==0 && isPrime(i))
return getPrimes(x/i) ;
}
return -1;
}
public static String solve11(String x){
int n = x.length() ;
String y = "" ;
for (int i = 0; i < n-2; i+=2)
{
if(ifPalindrome(x.substring(i, i+2)))
y+= x.substring(i, i+2) ;
else
break ;
}
return y+ solve11(x.substring(y.length(),x.length())) ;
}
public static String solve1(String x){
String y = x.substring(0 , x.length()/2) ;
return "" ;
}
public static String reverse(String x){
String y ="" ;
for (int i = 0; i < x.length(); i++)
{
y = x.charAt(i) + y ;
}
return y ;
}
public static boolean ifPalindrome(String x){
int numbers[] = new int[10] ;
for (int i = 0; i < x.length(); i++)
{
int z = Integer.parseInt(x.charAt(i)+"") ;
numbers[z] ++ ;
}
for (int i = 0; i < numbers.length; i++)
{
if(numbers[i]%2!=0)
return false;
}
return true ;
}
public static int get(int n){
return n*(n+1)/2 ;
}
// public static long getSmallestDivisor( long y){
// if(isPrime(y))
// return -1;
//
// for (long i = 2; i*i <= y; i++)
// {
// if(y%i ==0)
// {
// return i;
// }
// }
// return -1;
// }
public static int lis( int[]a , int n){
int lis[] = new int[n] ;
Arrays.fill(lis,1) ;
for(int i=1;i<n;i++)
for(int j=0 ; j<i; j++)
if (a[i]>a[j] && lis[i] < lis[j]+1)
lis[i] = lis[j] + 1;
int max = lis[0];
for(int i=1; i<n ; i++)
if (max < lis[i])
max = lis[i] ;
return (max);
// ArrayList<Integer> s = new ArrayList<Integer>() ;
// for (int i = n-1; i >=0; i--)
// {
// if(lis[i]==max)
// {
// s.add(a[i].z);
// max --;
// }
// }
//
// for (int i = s.size()-1 ; i>=0 ; i--)
// {
// System.out.print(s.get(i)+" ");
// }
//
}
public static int calcDepth(Vertix node){
if(node.depth>0) return node.depth;
// meaning it has been updated before;
if(node.parent != null)
return 1+ calcDepth(node.parent);
else
return -1;
}
public static boolean isPrime (long num){
if (num < 2) return false;
if (num == 2) return true;
if (num % 2 == 0) return false;
for (int i = 3; i * i <= num; i += 2)
if (num % i == 0) return false;
return true;
}
public static ArrayList<Long> getDiv(Long n)
{
ArrayList<Long> f = new ArrayList<Long>() ;
while (n%2==0)
{
if(!f.contains(2))f.add((long) 2) ;
n /= 2;
}
// n must be odd at this point. So we can
// skip one element (Note i = i +2)
for (long i = 3; i <= Math.sqrt(n); i+= 2)
{
// While i divides n, print i and divide n
while (n%i == 0)
{
if(!f.contains(i))f.add(i);
n /= i;
}
}
// This condition is to handle the case whien
// n is a prime number greater than 2
if (n > 2)
if(!f.contains(n))f.add(n);
return f ;
}
// public static boolean dfs(Vertix v , int target){
// try{
// visited[v.i]= true ;
// } catch (NullPointerException e)
// {
// System.out.println(v.i);
// }
// if(v.i == target)
//
// return true ;
// for (int i =0 ; i< v.neighbours.size() ; i++)
// {
//
// Vertix child = v.neighbours.get(i) ;
// if(child.i == target){
// found = true ;
// }
// if(visited[child.i]==false){
// found |= dfs(child, target) ;
// }
// }
// return found;
// }
public static class Vertix{
long i ;
int depth ;
ArrayList<Vertix> neighbours ;
Vertix parent ;
Vertix child ;
public Vertix(long i){
this.i = i ;
this.neighbours = new ArrayList<Vertix> () ;
this.parent = null ;
depth =-1;
this.child = null ;
}
}
public static class pair implements Comparable<pair> {
int x ;
int y ;
int i;
public pair(int x, int y, int i ){
this.x=x ;
this.y =y ;
this.i =i ;
}
@Override
public int compareTo(pair p) {
if(this.x > p.x)
return 1 ;
else if (this.x == p.x)
return 0 ;
else
return -1 ;
}
}
public static class pair2 implements Comparable<pair2>{
int i ;
int j ;
int plus ;
public pair2(int i , int j , int plus){
this.i =i ;
this.j = j ;
this.plus = plus ;
}
@Override
public int compareTo(pair2 p) {
if(this.j > p.j)
return 1 ;
else if (this.j == p.j) return 0 ;
else
return -1 ;
}
}
public static class point implements Comparable<point>
{
int x, y ;
public point(int x,int y){
this.x=x ; this.y=y;
}
@Override
public boolean equals(Object o) {
// If the object is compared with itself then return true
if (o == this) {
return true;
}
/* Check if o is an instance of Complex or not
"null instanceof [type]" also returns false */
if (!(o instanceof point)) {
return false;
}
// typecast o to Complex so that we can compare data members
point c = (point) o;
// Compare the data members and return accordingly
return Integer.compare(x, c.x) == 0
&& Integer.compare(y, c.y) == 0;
}
@Override
public int compareTo(point p) {
if(this.x == p.x && this.y ==p.y)
return 0 ;
else
return -1 ;
}
@Override
public int hashCode()
{
return 15+x+(y%2) ;
}
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Vadim Semenov
*/
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);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static final class TaskC {
private static final int MODULO = 1_000_000_000 + 7;
public void solve(int __, InputReader in, PrintWriter out) {
long qty = in.nextLong();
long months = in.nextLong();
if (qty == 0) {
out.println(0);
return;
}
qty %= MODULO;
long pow = pow(2, months + 1);
qty = (qty * pow) % MODULO;
long sub = (pow - 2 + MODULO) % MODULO * pow(2, MODULO - 2) % MODULO;
qty = (qty - sub + MODULO) % MODULO;
out.println(qty);
}
private long pow(long base, long power) {
long result = 1;
while (power > 0) {
if ((power & 1) != 0) {
result = (result * base) % MODULO;
}
base = (base * base) % MODULO;
power >>>= 1;
}
return result;
}
}
static class InputReader {
private final BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
}
public long nextLong() {
return Long.parseLong(next());
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(readLine());
}
return tokenizer.nextToken();
}
public String readLine() {
String line;
try {
line = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return line;
}
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
public class C {
public static void main(String[] args) throws Exception {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
// Scanner scan = new Scanner(System.in);
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
// int n = Integer.parseInt(bf.readLine());
StringTokenizer st = new StringTokenizer(bf.readLine());
// int[] a = new int[n]; for(int i=0; i<n; i++) a[i] = Integer.parseInt(st.nextToken());
long n = Long.parseLong(st.nextToken());
long k = Long.parseLong(st.nextToken());
int mod = 1000000007;
if(n == 0) {
out.println(0);
out.close(); System.exit(0);
}
n %= mod;
long ans = exp(2, (int)((k+1) % (mod-1)), mod);
ans = (1L*ans * n) % mod;
ans = ans + mod + 1 - exp(2, (int)((k) % (mod-1)), mod);
ans %= mod;
out.println(ans);
// int n = scan.nextInt();
out.close(); System.exit(0);
}
public static int exp(int base, int e, int mod) {
if(e == 0) return 1;
if(e == 1) return base;
int val = exp(base, e/2, mod);
int ans = (int)(1L*val*val % mod);
if(e % 2 == 1)
ans = (int)(1L*ans*base % mod);
return ans;
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.*;
import java.util.*;
public class ModifyLongest {
InputStream is;
PrintWriter out;
String INPUT = "";
//boolean codechef=true;
boolean codechef=true;
void solve()
{
/*
long l=ni(),r=ni(),x=ni(),y=ni();
long prod=x;
prod*=y;
int cnt=0;
if(l==r && r==x && x==y && x==1)
{
System.out.println(1);
return;
}
//HashSet<Long> set=new HashSet<>();
for(long i=2;i<=Math.sqrt(prod);i++)
{
if(prod%i==0)
{
if(Math.min(i,prod/i)>=l && Math.max(i,prod/i)<=r && gcd(i,prod/i)==x)
{
//set.add(fnc2(i,prod/i));
//set.add(fnc2(prod/i,i));
if(i!=prod/i)cnt+=2;
else cnt++;
}
}
}
ArrayList<Long> factors=new ArrayList<>();
while(prod!=1)
{
long currF=PollardRho(prod);
while(prod%currF!=0)
{
prod/=currF;
factors.add(currF);
}
}
if(l==1)
{
System.out.println((cnt+2));
}
else
{
System.out.println(cnt);
}
*/
long mod=1000000007;
long x=nl(),k=nl();
if(x==0)
{
System.out.println(0);
return;
}
long val=calc((pow(2,k,mod)*(x%mod))%mod);
val-=calc(((pow(2,k,mod)*(x%mod))%mod-(pow(2,k,mod)-1)-1+mod)%mod);
//val*=2;
val=(val+mod)%mod;
val=(val*inv(pow(2,k,mod),mod))%mod;
System.out.println(val);
}
static long calc(long a)
{
long b=(a*(a+1))%1000000007;
return b;
}
/* method to return prime divisor for n */
long PollardRho(long n)
{
/* initialize random seed */
//srand (time(NULL));
/* no prime divisor for 1 */
if (n==1) return n;
/* even number means one of the divisors is 2 */
if (n % 2 == 0) return 2;
Random r=new Random();
/* we will pick from the range [2, N) */
long x = (r.nextLong()%(n-2))+2;
long y = x;
/* the constant in f(x).
* Algorithm can be re-run with a different c
* if it throws failure for a composite. */
long c = (r.nextLong()%(n-1))+1;
/* Initialize candidate divisor (or result) */
long d = 1;
/* until the prime factor isn't obtained.
If n is prime, return n */
while (d==1)
{
/* Tortoise Move: x(i+1) = f(x(i)) */
x = (pow(x, 2, n) + c + n)%n;
/* Hare Move: y(i+1) = f(f(y(i))) */
y = (pow(y, 2, n) + c + n)%n;
y = (pow(y, 2, n) + c + n)%n;
/* check gcd of |x-y| and n */
d = gcd(Math.abs(x-y), n);
/* retry if the algorithm fails to find prime factor
* with chosen x and c */
if (d==n) return PollardRho(n);
}
return d;
}
static HashMap<Long,HashSet<Long>> globalSet;
static long fnc(int a,int b)
{
long val=Math.min(a,b)*1000000007;
val+=Math.max(a,b);
return val;
}
static long fnc2(long a,long b)
{
long val=a*1000000007;
val+=b;
return val;
}
static class Pair
{
int a,b;
public Pair(int a,int b)
{
this.a=a;
this.b=b;
}
}
static int bit[];
static void add(int x,int d,int n)
{
for(int i=x;i<=n;i+=i&-i)bit[i]+=d;
}
static int query(int x)
{
int ret=0;
for(int i=x;i>0;i-=i&-i)
ret+=bit[i];
return ret;
}
static long lcm(int a,int b)
{
long val=a;
val*=b;
return (val/gcd(a,b));
}
static long gcd(long a,long b)
{
if(a==0)return b;
return gcd(b%a,a);
}
static long pow(long a, long b, long p)
{
long ans = 1, base = a;
while (b!=0)
{
if ((b & 1)!=0)
{
ans *= base;
ans%= p;
}
base *= base;
base%= p;
b >>= 1;
}
return ans;
}
static long inv(long x,long p)
{
return pow(x, (int)p - 2, p);
}
void run() throws Exception
{
if(codechef)oj=true;
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception {new ModifyLongest().run();}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
private void solve() throws IOException {
out.println(solve(nl()));
out.close();
}
private long solve(long n) throws IOException {
if (n > 0) {
n <<= 1;
long k = nl();
n--;
int M = 1000000007;
long p = power(2, k, M);
// Helper.tr(n * p + 1);
n = (n % M * p + 1) % M;
}
return n;
}
long power(long a, long b, long mod) {
long x = 1, y = a;
while (b > 0) {
if (b % 2 != 0) {
x = (x * y) % mod;
}
y = (y * y) % mod;
b /= 2;
}
return x % mod;
}
static BufferedReader in;
static PrintWriter out;
static StringTokenizer tok;
private int[][] na(int n) throws IOException {
int[][] a = new int[n][2];
for (int i = 0; i < n; i++) {
a[i][0] = ni();
a[i][1] = i;
}
return a;
}
String ns() throws IOException {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine(), " ");
}
return tok.nextToken();
}
int ni() throws IOException {
return Integer.parseInt(ns());
}
long nl() throws IOException {
return Long.parseLong(ns());
}
double nd() throws IOException {
return Double.parseDouble(ns());
}
String[] nsa(int n) throws IOException {
String[] res = new String[n];
for (int i = 0; i < n; i++) {
res[i] = ns();
}
return res;
}
int[] nia(int n) throws IOException {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = ni();
}
return res;
}
long[] nla(int n) throws IOException {
long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = nl();
}
return res;
}
public static void main(String[] args) throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
tok = new StringTokenizer("");
Main main = new Main();
main.solve();
out.close();
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Iterator;
import java.util.Vector;
public class con67 {
public static void main(String[] args) throws IOException
{
// System.out.println(power(2,9,1000000007));
long x=l();
long k=l();
if(x!=0)
{
long f=x%1000000007;
long s=(f*power(2,k+1,1000000007))%1000000007;
//out.println(s);
long e= (power(2,k,1000000007)-1)%1000000007;
//out.println(e);
long ans=(s-e+1000000007)%1000000007;
out.println(ans);
}
else
{
out.println(0);
}
out.close();
}
static long power(long x, long y, long p)
{
// Initialize result
long res = 1;
// 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 / 2
y = y >> 1;
x = (x * x) % p;
}
return res;
}
static InputReader in = new InputReader(System.in);
static OutputWriter out = new OutputWriter(System.out);
static int i()
{
return in.readInt();
}
static long l()
{
return in.readLong();
}
static double d()
{
return in.readDouble();
}
static String s()
{
return in.readString();
}
static void Iarr( int[] array, int no )
{
for( int i=0 ; i<no ; i++ )
{
array[i] = i();
}
}
static void Larr( long[] array, int no )
{
for( int i=0 ; i<no ; i++ )
{
array[i] = l();
}
}
static void Darr( double[] array, int no )
{
for( int i=0 ; i<no ; i++ )
{
array[i] = d();
}
}
static void Sarr( String[] array, int no )
{
for( int i=0 ; i<no ; i++ )
{
array[i] = s();
}
}
private static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt()
{
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 String readString()
{
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 double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public long readLong() {
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 boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
private static class OutputWriter
{
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream)
{
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer)
{
this.writer = new PrintWriter(writer);
}
public void print(Object... objects)
{
for (int i = 0; i < objects.length; i++)
{
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void println(Object... objects)
{
print(objects);
writer.println();
}
public void close()
{
writer.close();
}
public void flush()
{
writer.flush();
}
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Vadim Semenov
*/
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);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static final class TaskC {
private static final int MODULO = 1_000_000_000 + 7;
public void solve(int __, InputReader in, PrintWriter out) {
long qty = in.nextLong();
long months = in.nextLong();
if (qty == 0) {
out.println(0);
return;
}
qty %= MODULO;
long pow = pow(2, months + 1);
qty = (qty * pow) % MODULO;
long sub = (pow - 2 + MODULO) % MODULO * pow(2, MODULO - 2) % MODULO;
qty = (qty - sub + MODULO) % MODULO;
out.println(qty);
}
private long pow(long base, long power) {
long result = 1;
while (power > 0) {
if ((power & 1) != 0) {
result = (result * base) % MODULO;
}
base = (base * base) % MODULO;
power >>>= 1;
}
return result;
}
}
static class InputReader {
private final BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
}
public long nextLong() {
return Long.parseLong(next());
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(readLine());
}
return tokenizer.nextToken();
}
public String readLine() {
String line;
try {
line = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return line;
}
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class C
{
static int mod = (int) (1e9+7);
static InputReader in;
static PrintWriter out;
public static void main(String[] args)
{
in = new InputReader(System.in);
out = new PrintWriter(System.out);
long x = in.nextLong();
long k = in.nextLong();
if(x == 0){
out.println(0);
}
else{
long mul = pow(2, k + 1, mod);
x %= mod;
mul = (mul * x) % mod;
long sub = pow(2, k, mod);
sub = (sub - 1 + mod) % mod;
mul = (mul - sub + mod) % mod;
out.println(mul);
}
out.close();
}
static class Pair implements Comparable<Pair>
{
int x,y;
int i;
Pair (int x,int y)
{
this.x = x;
this.y = y;
}
Pair (int x,int y, int i)
{
this.x = x;
this.y = y;
this.i = i;
}
public int compareTo(Pair o)
{
return Integer.compare(this.x, o.x);
}
public boolean equals(Object o)
{
if (o instanceof Pair)
{
Pair p = (Pair)o;
return p.x == x && p.y==y;
}
return false;
}
@Override
public String toString()
{
return x + " "+ y + " "+i;
}
/*public int hashCode()
{
return new Long(x).hashCode() * 31 + new Long(y).hashCode();
}*/
}
static String rev(String s){
StringBuilder sb=new StringBuilder(s);
sb.reverse();
return sb.toString();
}
static long gcd(long x,long y)
{
if(y==0)
return x;
else
return gcd(y,x%y);
}
static int gcd(int x,int y)
{
if(y==0)
return x;
else
return gcd(y,x%y);
}
static long pow(long n,long p,long m)
{
long result = 1;
if(p==0){
return 1;
}
while(p!=0)
{
if(p%2==1)
result *= n;
if(result >= m)
result %= m;
p >>=1;
n*=n;
if(n >= m)
n%=m;
}
return result;
}
static long pow(long n,long p)
{
long result = 1;
if(p==0)
return 1;
while(p!=0)
{
if(p%2==1)
result *= n;
p >>=1;
n*=n;
}
return result;
}
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;
}
public long[] nextLongArray(int n)
{
long a[] = new long[n];
for (int i = 0; i < n; i++)
{
a[i] = nextLong();
}
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);
}
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
//package round489;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class C {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int[][] M = {
{2, mod-1},
{0, 1}
};
long n = nl();
if(n == 0){
out.println(0);
return;
}
n = n*2%mod;
long K = nl();
int[] v = new int[]{(int)n, 1};
out.println(pow(M, v, K)[0]);
}
///////// begin
public static final int mod = 1000000007;
public static final long m2 = (long)mod*mod;
public static final long BIG = 8L*m2;
// A^e*v
public static int[] pow(int[][] A, int[] v, long e)
{
for(int i = 0;i < v.length;i++){
if(v[i] >= mod)v[i] %= mod;
}
int[][] MUL = A;
for(;e > 0;e>>>=1) {
if((e&1)==1)v = mul(MUL, v);
MUL = p2(MUL);
}
return v;
}
// int matrix*int vector
public static int[] mul(int[][] A, int[] v)
{
int m = A.length;
int n = v.length;
int[] w = new int[m];
for(int i = 0;i < m;i++){
long sum = 0;
for(int k = 0;k < n;k++){
sum += (long)A[i][k] * v[k];
if(sum >= BIG)sum -= BIG;
}
w[i] = (int)(sum % mod);
}
return w;
}
// int matrix^2 (be careful about negative value)
public static int[][] p2(int[][] A)
{
int n = A.length;
int[][] C = new int[n][n];
for(int i = 0;i < n;i++){
long[] sum = new long[n];
for(int k = 0;k < n;k++){
for(int j = 0;j < n;j++){
sum[j] += (long)A[i][k] * A[k][j];
if(sum[j] >= BIG)sum[j] -= BIG;
}
}
for(int j = 0;j < n;j++){
C[i][j] = (int)(sum[j] % mod);
}
}
return C;
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new C().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.util.Scanner;
public class Main {
public static long power(long a, long b, long c){
if(b == 0){
return 1;
}
a %= c;
if(b % 2 == 0){
return power((a % c * a % c) % c, b / 2, c);
}else{
return (a % c * power((a % c * a % c) % c, b / 2, c) % c) % c;
}
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
long x = s.nextLong(), k = s.nextLong() + 1, mod = (long)Math.pow(10, 9) + 7;
long ans;
if(x == 0){
System.out.println(0);
return;
}
// if(x != 0){
ans = ((power(2, k % (mod - 1), mod) % mod) * (x % mod)) % mod;
/* }else{
ans = 0;
}
*/ans = (ans - power(2, (k - 1) % (mod - 1), mod) % mod + 2 * mod) % mod;
System.out.println((ans + 1) % mod);
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
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
*/
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);
CNastyaAndAWardrobe solver = new CNastyaAndAWardrobe();
solver.solve(1, in, out);
out.close();
}
static class CNastyaAndAWardrobe {
public void solve(int testNumber, InputReader in, PrintWriter out) {
long x = in.nextLong(), k = in.nextLong();
if (x != 0) {
long m = (int) 1e9 + 7;
x = x % m;
long res = in.fastPowerMod(2, k, m);
long res1 = (2 * res) % m;
long ans = ((res1 * x) % m - (res - 1) % m) % m;
ans = (ans + m) % m;
out.println(ans);
} else {
out.println(0);
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
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 boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public long fastPowerMod(long x, long y, long m) {
long res = 1;
x = x % m;
while (y > 0) {
if ((y & 1) == 1) {
res = (x * res) % m;
}
x = (x * x) % m;
y = y >> 1;
}
return res % m;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.math.BigInteger;
import java.util.*;
import java.io.*;
public class Contest {
public static void main(String[] args)throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] s=br.readLine().split(" ");
BigInteger x = new BigInteger(s[0]);
BigInteger k = new BigInteger(s[1]);
BigInteger mod = new BigInteger(String.valueOf((int) (Math.pow(10, 9) + 7)));
BigInteger two = new BigInteger("2");
BigInteger interm = two.modPow(k, mod);
BigInteger res = interm.multiply(two.multiply(x).subtract(BigInteger.ONE)).add(BigInteger.ONE).mod(mod);
if(x.equals(BigInteger.ZERO)) {
System.out.println("0");
return;
}
System.out.println(res);
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.