src
stringlengths 95
64.6k
| complexity
stringclasses 7
values | problem
stringlengths 6
50
| from
stringclasses 1
value |
---|---|---|---|
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 kessido
*/
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 in, PrintWriter out) {
long MOD = MathExtentions.DEFAULT_MOD;
long x = in.NextLong();
long k = in.NextLong();
if (x == 0) {
out.println(0);
return;
}
x %= MOD;
long res = x * MathExtentions.powerMod(2, k + 1, MOD);
res %= MOD;
res -= MathExtentions.powerMod(2, k, MOD) - 1;
res %= MOD;
while (res < 0) res += MOD;
while (res >= MOD) res -= MOD;
out.println(res);
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine(), " \t\n\r\f,");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long NextLong() {
return Long.parseLong(next());
}
}
static class MathExtentions {
public static final long DEFAULT_MOD = 1_000_000_007;
public static long powerMod(final long x, final long y, final long m) {
if (y == 0)
return 1;
long p = powerMod(x, y / 2, m) % m;
p = (p * p) % m;
if (y % 2 == 0)
return p;
else
return (x * p) % m;
}
}
}
| 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
*/
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);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
int MOD = 1000000007;
public void solve(int testNumber, FastScanner in, PrintWriter out) {
long x = in.nextLong();
long k = in.nextLong();
if (x == 0) {
out.print(0);
return;
}
long b = fast_expo(2, k);
long a = (b * 2) % MOD;
long u = ((x % MOD) * a) % MOD;
long v = (b - 1 + MOD) % MOD;
out.print((u - v + MOD) % MOD);
}
private long fast_expo(long a, long b) {
long res = 1L;
a = a % MOD;
while (b > 0) {
if ((b & 1) != 0) {
res = (res * a) % MOD;
}
b = b >> 1;
a = (a * a) % MOD;
}
return res % MOD;
}
}
static class FastScanner {
private BufferedReader bufferedReader;
private StringTokenizer stringTokenizer;
public FastScanner(InputStream inputStream) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() {
while (stringTokenizer == null || !stringTokenizer.hasMoreElements()) {
try {
stringTokenizer = new StringTokenizer(bufferedReader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return stringTokenizer.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| 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 ankur
*/
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 {
long mod = (long) 1e9 + 7;
public void solve(int testNumber, InputReader in, PrintWriter out) {
long x = in.nextLong();
long k = in.nextLong();
if (x == 0) {
out.print(0);
return;
}
long n = pow(2, k);
long l = (n * ((x % mod)) % mod);
l = l % mod;
long ans = 2 * l - n + 1;
ans = ans % mod;
if (ans < 0)
ans += mod;
out.print(ans);
}
long pow(long a, long val) {
if (val == 0) {
return 1;
}
if (val % 2 == 0) {
long ans = pow(a, val / 2);
return (ans * ans) % mod;
}
return ((a % mod) * (pow(a, val - 1))) % mod;
}
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar;
private int snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
//*-*------clare------
//remeber while comparing 2 non primitive data type not to use ==
//remember Arrays.sort for primitive data has worst time case complexity of 0(n^2) bcoz it uses quick sort
//again silly mistakes ,yr kb tk krta rhega ye mistakes
//try to write simple codes ,break it into simple things
//knowledge>rating
/*
public class Main
implements Runnable{
public static void main(String[] args) {
new Thread(null,new Main(),"Main",1<<26).start();
}
public void run() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();//chenge the name of task
solver.solve(1, in, out);
out.close();
}
*/
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 = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
| 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.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Jenish
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
C489 solver = new C489();
solver.solve(1, in, out);
out.close();
}
static class C489 {
int mod = 1000000007;
public void solve(int testNumber, ScanReader in, PrintWriter out) {
long x = in.scanLong();
long k = in.scanLong();
if (x == 0) {
out.println(0);
return;
}
long p = CodeX.power(2, k, mod);
long ans = (2 * p * (x % mod)) % mod;
ans = (ans + 1) % mod;
ans = (ans - p + mod) % mod;
out.println(ans);
}
}
static class CodeX {
public static long power(long x, long y, long p) {
long res = 1;
x = x % p;
while (y > 0) {
if ((y & 1) != 0)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
}
static class ScanReader {
private byte[] buf = new byte[4 * 1024];
private int INDEX;
private BufferedInputStream in;
private int TOTAL;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() {
if (INDEX >= TOTAL) {
INDEX = 0;
try {
TOTAL = in.read(buf);
} catch (Exception e) {
e.printStackTrace();
}
if (TOTAL <= 0) return -1;
}
return buf[INDEX++];
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
public long scanLong() {
long I = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
I *= 10;
I += n - '0';
n = scan();
}
}
return neg * 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.Scanner;
/** 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;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
static final long MODULO = (int) (1e9 + 7);
public void solve(int testNumber, Scanner in, PrintWriter out) {
long x = in.nextLong();
long k = in.nextLong();
if (x == 0) {
out.println(0);
} else {
long e = modPow(2, k, MODULO);
long y = 2 * x - 1;
long w = ((e % MODULO) * (y % MODULO)) % MODULO;
long z = (w + 1) % MODULO;
out.println(z);
}
}
private long modPow(long a, long b, long m) {
if (b == 0) return 1 % m;
if (b == 1) return a % m;
long res = modPow(a, b / 2, m);
res = (res * res) % m;
if (b % 2 == 1) res = (res * a) % m;
return res;
}
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
new Solver().run(1);
}
}
class Solver {
private BufferedReader reader = null;
private StringTokenizer st = null;
private static final long MOD = (long)1e9 + 7;
private long x, k;
public void run(int inputType) throws Exception {
if (inputType == 0)
reader = new BufferedReader(new FileReader("input.txt"));
else
reader = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(reader.readLine());
x = Long.parseLong(st.nextToken());
k = Long.parseLong(st.nextToken());
if (x == 0) {
System.out.println(0);
return;
}
long pow = binpow(2, k);
long m = (2 * x) % MOD;
m = (m - 1 < 0) ? MOD - 1 : m - 1;
m = (m * pow) % MOD;
m = (m + 1) % MOD;
System.out.println(m);
reader.close();
}
long binpow(long v, long p) {
long res = 1L;
while(p > 0) {
if ((p & 1) > 0)
res = (res * v) % MOD;
v = (v * v) % MOD;
p /= 2;
}
return res;
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.math.BigInteger;
import java.util.Scanner;
public class TaskC {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
BigInteger x = new BigInteger(sc.next());
BigInteger k = new BigInteger(sc.next());
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(x).add(interm.multiply(x)).subtract(interm).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 |
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
*
* @author Allen Li
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Nas solver = new Nas();
solver.solve(1, in, out);
out.close();
}
static class Nas {
public void solve(int testNumber, FastReader in, PrintWriter out) {
long x = in.nextLong();
if (x == 0) {
out.println(0);
return;
}
BigInteger n1 = BigInteger.valueOf(x);
BigInteger n2 = BigInteger.valueOf(in.nextLong());
BigInteger mod = BigInteger.valueOf(1000000007);
BigInteger a = BigInteger.valueOf(2).modPow(n2.add(BigInteger.ONE), mod);
a = a.multiply(n1);
a = a.mod(mod);
BigInteger b = BigInteger.valueOf(2).modPow(n2, mod).subtract(BigInteger.ONE);
a = a.subtract(b);
a = a.add(mod);
a = a.mod(mod);
out.println(a);
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private FastReader.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 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 static boolean isWhitespace(int 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 java.util.*;
import java.io.*;
import java.text.DecimalFormat;
public class Main{
final long mod = (int)1e9+7, IINF = (long)1e19;
final int MAX = (int)1e6+1, MX = (int)1e7+1, INF = (int)1e9;
DecimalFormat df = new DecimalFormat("0.0000000000000");
FastReader in;
PrintWriter out;
static boolean multipleTC = false, memory = false;
public static void main(String[] args) throws Exception{
if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 26).start();
else new Main().run();
}
void run() throws Exception{
in = new FastReader();
out = new PrintWriter(System.out);
for(int i = 1, t = (multipleTC)?ni():1; i<=t; i++)solve(i);
out.flush();
out.close();
}
void solve(int TC) throws Exception{
long x = nl(), k = nl();
if(x==0)pn(0);
else {
x%=mod;
long p = modPow(2,k);
long b = mul((x-1+mod)%mod,p), e = mul(x,p);
long ans = c(e)%mod;
ans -= c(b)%mod;
ans%=mod;
if(ans<0)ans+=mod;
ans = mul(ans, 2);
ans = mul(ans, modPow(p, mod-2));
pn(ans);
}
}
long modPow(long a, long p){
long o = 1;
while(p>0){
if((p&1)==1)o = mul(a,o);
a = mul(a,a);
p>>=1;
}
return o;
}
long mul(long a, long b){
if(a>=mod)a%=mod;
if(b>=mod)b%=mod;
a*=b;
if(a>=mod)a%=mod;
return a;
}
long c(long c){
return (c*c+c)/2;
}
int[] reverse(int[] a){
int[] o = new int[a.length];
for(int i = 0; i< a.length; i++)o[i] = a[a.length-i-1];
return o;
}
int[] sort(int[] a){
if(a.length==1)return a;
int mid = a.length/2;
int[] b = sort(Arrays.copyOfRange(a,0,mid)), c = sort(Arrays.copyOfRange(a,mid,a.length));
for(int i = 0, j = 0, k = 0; i< a.length; i++){
if(j<b.length && k<c.length){
if(b[j]<c[k])a[i] = b[j++];
else a[i] = c[k++];
}else if(j<b.length)a[i] = b[j++];
else a[i] = c[k++];
}
return a;
}
long[] sort(long[] a){
if(a.length==1)return a;
int mid = a.length/2;
long[] b = sort(Arrays.copyOfRange(a,0,mid)), c = sort(Arrays.copyOfRange(a,mid,a.length));
for(int i = 0, j = 0, k = 0; i< a.length; i++){
if(j<b.length && k<c.length){
if(b[j]<c[k])a[i] = b[j++];
else a[i] = c[k++];
}else if(j<b.length)a[i] = b[j++];
else a[i] = c[k++];
}
return a;
}
int[] ia(int ind,int n){
int[] out = new int[ind+n];
for(int i = 0; i< n; i++)out[ind+i] = ni();
return out;
}
long[] la(int ind, int n){
long[] out = new long[ind+n];
for(int i = 0; i< n; i++)out[ind+i] = nl();
return out;
}
double[] da(int ind, int n){
double[] out = new double[ind+n];
for(int i = 0; i< n; i++)out[ind+i] = nd();
return out;
}
long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
int bitcount(long n){return (n==0)?0:(1+bitcount(n&(n-1)));}
void p(Object o){out.print(o);}
void pn(Object o){out.println(o);}
void pni(Object o){out.println(o);out.flush();}
String n(){return in.next();}
String nln(){return in.nextLine();}
int ni(){return Integer.parseInt(in.next());}
long nl(){return Long.parseLong(in.next());}
double nd(){return Double.parseDouble(in.next());}
class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception{
br = new BufferedReader(new FileReader(s));
}
String next(){
while (st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}catch (IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
String nextLine(){
String str = "";
try{
str = br.readLine();
}catch (IOException e){
e.printStackTrace();
}
return str;
}
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.StringTokenizer;
public class Tester
{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static long mod = 1000000007;
public static void main(String[] args) {
solveQ3();
}
private static void solveQ3() {
// TODO Auto-generated method stub
FastReader sc = new FastReader();
long x = sc.nextLong();
long k = sc.nextLong();
if(x == 0) {
System.out.println(0);
return;
}
long ans = modExp(2, k);
x = (2*x)%mod;
x = (x - 1 + mod)%mod;
ans = (ans*x)%mod;
ans = (ans + 1)%mod;
System.out.println(ans);
}
private static long modExp(long a, long n) {
if(n == 0)
return 1;
if(n%2 == 0)
return modExp((a*a)%mod, n/2);
else
return (a*modExp((a*a)%mod, n/2))%mod;
}
private static void solveQ2() {
// TODO Auto-generated method stub
FastReader sc = new FastReader();
long l = sc.nextLong();
long r = sc.nextLong();
long x = sc.nextLong();
long y = sc.nextLong();
long n = x*y;
long count = 0;
for(long i=l; (i<=Math.sqrt(n)) && (n/i<=r); i++) {
if((n%i == 0) && (gcd(i, n/i)==x)) {
if(i*i != n)
count += 2;
else
count += 1;
}
}
System.out.println(count);
}
public static long gcd(long a, long b) {
if(b==0)
return a;
else
return gcd(b, a%b);
}
private static void solveQ1() {
// TODO Auto-generated method stub
FastReader sc = new FastReader();
int n = sc.nextInt();
HashSet<Integer> hs = new HashSet<Integer>();
for(int i=0; i<n; i++) {
int x = sc.nextInt();
if(x != 0) {
hs.add(x);
}
}
System.out.println(hs.size());
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
//package pack;
import java.util.*;
public class first
{
public static long power(long x, long y, long p)
{
long res = 1;
x = x % p;
while (y > 0)
{ if((y & 1)==1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
long x=sc.nextLong();
long k=sc.nextLong();
long mod=1000000007;
if(k==0 || x==0)
System.out.println((2*x)%mod);
else
{ long answer=1;
answer+=(power(2,k,mod))*(((2*x)-1)%mod);
System.out.println(answer%mod);
}
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main
{
long mod = 1000000007;
long pow(long x,long y)
{
if(y==0)
return 1;
else if(y==1)
return x%mod;
else if(y%2==0)
return pow((x*x)%mod,y/2)%mod;
else
return (x*pow((x*x)%mod,y/2)%mod)%mod;
}
void solve()
{
FastReader sc =new FastReader();
long x = sc.nextLong();
long k = sc.nextLong();
if(x == 0) {
System.out.println(0);
return;
}
long ans = pow(2, k);
x = (2*x)%mod;
x = (x - 1 + mod)%mod;
ans = (ans*x)%mod;
ans = (ans + 1)%mod;
System.out.println(ans);
}
public static void main(String[] args)
{
new Main().solve();
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
} | 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.util.StringTokenizer;
import java.io.PrintWriter;
public class C992
{
static class Scanner
{
BufferedReader br;
StringTokenizer tk=new StringTokenizer("");
public Scanner(InputStream is)
{
br=new BufferedReader(new InputStreamReader(is));
}
public int nextInt() throws IOException
{
if(tk.hasMoreTokens())
return Integer.parseInt(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextInt();
}
public long nextLong() throws IOException
{
if(tk.hasMoreTokens())
return Long.parseLong(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextLong();
}
public String next() throws IOException
{
if(tk.hasMoreTokens())
return (tk.nextToken());
tk=new StringTokenizer(br.readLine());
return next();
}
public String nextLine() throws IOException
{
tk=new StringTokenizer("");
return br.readLine();
}
public double nextDouble() throws IOException
{
if(tk.hasMoreTokens())
return Double.parseDouble(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextDouble();
}
public char nextChar() throws IOException
{
if(tk.hasMoreTokens())
return (tk.nextToken().charAt(0));
tk=new StringTokenizer(br.readLine());
return nextChar();
}
public int[] nextIntArray(int n) throws IOException
{
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=nextInt();
return a;
}
public long[] nextLongArray(int n) throws IOException
{
long a[]=new long[n];
for(int i=0;i<n;i++)
a[i]=nextLong();
return a;
}
public int[] nextIntArrayOneBased(int n) throws IOException
{
int a[]=new int[n+1];
for(int i=1;i<=n;i++)
a[i]=nextInt();
return a;
}
public long[] nextLongArrayOneBased(int n) throws IOException
{
long a[]=new long[n+1];
for(int i=1;i<=n;i++)
a[i]=nextLong();
return a;
}
}
static long mod=1000000007;
static long mod_exp(long base,long exp)
{
long ans=1;
base%=mod;
while(exp>0)
{
if(exp%2==1)
{
ans*=base;
ans%=mod;
}
exp/=2;
base*=base;
base%=mod;
}
return ans;
}
public static void main(String args[]) throws IOException
{
Scanner in=new Scanner(System.in);
PrintWriter out=new PrintWriter(System.out);
long x=in.nextLong();
long k=in.nextLong();
long ans=mod_exp(2,k+1);
ans*=(x%mod);
ans%=mod;
ans-=mod_exp(2,k);
ans%=mod;
ans++;
ans%=mod;
if(ans<0)
ans+=mod;
if(x==0)
ans=0;
out.println(ans);
out.close();
}
}
| 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;
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 x = in.nextLong();
long k = in.nextLong();
if (x == 0) {
out.println(0);
} else {
long mod = (long) (1e9 + 7);
long ans = (((((2 * x - 1) % mod)) * power(2, k, mod)) % mod) + 1;
ans %= mod;
out.println(ans);
}
}
long power(long x, long y, long p) {
long res = 1;
x = x % p;
while (y > 0) {
if ((y & 1) > 0)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
}
static class FastScanner {
private final InputStream stream;
private final 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;
}
public long nextLong() {
return Long.parseLong(next());
}
public String next() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
//package com.company;
import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
static long TIME_START, TIME_END;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
// Scanner sc = new Scanner(new FileInputStream("Test.in"));
PrintWriter pw = new PrintWriter(System.out);
// PrintWriter pw = new PrintWriter(new FileOutputStream("Test.out"));
// PrintWriter pw = new PrintWriter(new FileOutputStream("Test.in"));
Runtime runtime = Runtime.getRuntime();
long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory();
TIME_START = System.currentTimeMillis();
Task t = new Task();
t.solve(sc, pw);
TIME_END = System.currentTimeMillis();
long usedMemoryAfter = runtime.totalMemory() - runtime.freeMemory();
pw.close();
System.out.println("Memory increased:" + (usedMemoryAfter-usedMemoryBefore) / 1000000 );
System.out.println("Time used: " + (TIME_END - TIME_START) + ".");
}
public static class Task {
int mod = 1_000_000_007;
public long pow(long a, long b) {
if (b == 0) return 1L;
if (b % 2 == 0) return pow(a * a % mod, b >> 1);
return a * pow(a * a % mod, b >> 1) % mod;
}
public void solve(Scanner sc, PrintWriter pw) throws IOException {
long T = sc.nextLong();
long k = sc.nextLong();
if (T == 0) {
pw.println(0);
return;
}
long a1 = pow(2, k + 1);
long a2 = pow(2, k);
long s = a1 * (T % mod) % mod;
long t = ((1 - a2) + mod) % mod;
long y = (s + t) % mod;
pw.println((y + 5L * mod) % mod);
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public Scanner(FileReader s) throws FileNotFoundException {br = new BufferedReader(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();}
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.math.*;
import java.util.*;
import java.io.*;
public class Main {
void solve() {
long x=nl(),k=nl();
if(x==0) {
pw.println(0);
return;
}
long d=modpow(2,k,M);
long ans=mul(2,d,M);
ans=mul(ans,x,M)%M;
ans++;
ans%=M;
ans=(ans-d+M)%M;
pw.println(ans);
}
// long mul(long a, long b,long M)
// {
// return (a*1L*b)%M;
// }
long mul(long x, long y, long m) {
long ans = 0;
while (y>0) {
if ((y & 1)>0) {
ans += x;
if (ans >= m) ans -= m;
}
x = x + x;
if (x >= m) x -= m;
y >>= 1;
}
return ans;
}
long modpow(long a, long b,long M)
{
long r=1;
while(b>0)
{
if((b&1)>0) r=mul(r,a,M);
a=mul(a,a,M);
b>>=1;
}
return r;
}
long M=(long)1e9+7;
InputStream is;
PrintWriter pw;
String INPUT = "";
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
pw = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
pw.flush();
if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new Main().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 void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); }
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.*;
public class C {
static long x, k;
static long mod = 1000000007;
public static void main(String[] args) {
JS in = new JS();
x = in.nextLong();
k = in.nextLong();
if(x==0) {
System.out.println(0);
return;
}
long c = pow(2,k);
if(c==0) c = mod;
long sub = c-1;
long low = ((c*(x%mod))%mod - sub);
while(low < 0) low += mod;
long res = ((low*2)%mod + sub)%mod;
System.out.println(res);
}
static long pow(long a, long p) {
if(p==0) return 1;
if(p==1) return a;
if(p%2==0) {
long res = pow(a,p/2)%mod;
return (res*res)%mod;
}
else {
return (pow(a,p-1)*a)%mod;
}
}
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.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class C {
static final int M = 1000000007;
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(in.readLine());
long x = Long.parseLong(st.nextToken());
if(x == 0){
System.out.println(0);
System.exit(0);
}
final long k = Long.parseLong(st.nextToken());
x = x%M;
long ans = (exp(2, k+1)*x - (exp(2, k) - 1))%M;
if(ans < 0) ans += M;
System.out.println(ans);
/*
for(long i = 1234567890; i < 1234567999; i++){
ans = (exp(2, i+1)*x - (exp(2, i) - 1))%M;
if(ans < 0) ans += M;
System.out.println(ans);
}
/*
System.out.println((k-1)/2);
System.out.println(x);
System.out.println(exp(2, k));
System.out.println(exp(2, k+1));
*/
}
public static long exp(long a, long n){
if(n == 0) return 1;
if(n == 1) return a%M;
if(n%2 == 0) return exp((a*a)%M, n/2);
else return (a*exp((a*a)%M, (n-1)/2))%M;
}
}
| 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.BufferedReader;
import java.io.InputStreamReader;
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 {
public void solve(int testNumber, InputReader in, PrintWriter out) {
long x = in.nextLong();
long k = in.nextLong();
long max2 = (((x % 1_000_000_007) * (pb(k))) % 1_000_000_007) % 1_000_000_007;
long min2 = ((((x - 1) % 1_000_000_007) * pb(k)) % 1_000_000_007 + 1) % 1_000_000_007;
if (x == 0) min2 = 0;
out.println((max2 + min2) % 1_000_000_007);
}
long pb(long a) {
if (a == 0) return 1;
if (a == 1) return 2;
long tmp = pb(a / 2);
if (a % 2 == 0) return (tmp * tmp) % 1_000_000_007;
return (((tmp * tmp) % 1_000_000_007) * 2) % 1_000_000_007;
}
}
static class InputReader {
private StringTokenizer tokenizer;
private BufferedReader reader;
public InputReader(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
}
private void fillTokenizer() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public String next() {
fillTokenizer();
return tokenizer.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Solution {
private static final long MODULUS = 1000000007;
private static final boolean DEBUG = false;
private static long modularPow(long base, long exponent, long modulus) {
long result = 1;
while (exponent > 0) {
if (exponent % 2 == 1) {
result = (result * base) % modulus;
}
exponent >>= 1;
base = (base * base) % modulus;
}
return result;
}
public static void main(String[] args) throws FileNotFoundException {
long beginTime = System.nanoTime();
InputStream is = DEBUG ? new FileInputStream("resources/codeforcesedu43/ProblemC-1.in") : System.in;
try (Scanner scanner = new Scanner(new BufferedReader(new InputStreamReader(is)))) {
long x = scanner.nextLong();
long k = scanner.nextLong();
if (x != 0) {
x = (2 * x - 1) % MODULUS;
long twoPowK = modularPow(2, k, MODULUS);
x = (x * twoPowK + 1) % MODULUS;
}
System.out.println(x % 1000000007);
}
System.err.println( "Done in " + ((System.nanoTime() - beginTime) / 1e9) + " seconds.");
}
} | 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(x).add(interm.multiply(x)).subtract(interm).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 |
import javax.swing.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.StringTokenizer;
public class A {
public static void main(String[] args) {
FastScanner scanner = new FastScanner();
long x = scanner.nextLong();
long k = scanner.nextLong();
if (x==0) {
System.out.println("0");
return;
}
BigInteger M = BigInteger.valueOf(1000_000_000L+7);
BigInteger modus = BigInteger.valueOf(x).multiply(BigInteger.valueOf(2)).subtract(BigInteger.ONE).mod(M);
BigInteger operandi = BigInteger.valueOf(2).modPow(BigInteger.valueOf(k), M);
BigInteger result = modus.multiply(operandi).mod(M).add(BigInteger.ONE).mod(M);
System.out.println(result);
}
public static long gcd(long a, long b) {
if (b == 0) return a;
return gcd(b, a % b);
}
public static long lcm(long a, long b, long gcd) {
return a * (b / gcd);
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.awt.List;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.util.StringTokenizer;
public class main {
static long d,x,y;
public static void main(String[] args) {
FastScanner in = new FastScanner();
long x = in.nextLong(), k = in.nextLong();
long mod = 1000000007;
long one = pow(2,k,mod);
one %= mod;
long two = (2*x)%mod-1;
two %= mod;
long ans = (one*two)%mod+1;
ans %= mod;
if(ans<0)
ans += mod;
if(x==0)
System.out.println("0");
else
System.out.println(ans);
}
private static long pow(long a, long b, long mod) {
if(b==0) return 1;
if(b==1)
return a;
if(b%2==0)
return pow((a*a)%mod,b/2,mod);
else
return (a*pow((a*a)%mod,(b-1)/2,mod))%mod;
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.util.Scanner;
public class CF489_C {
static long mod = 1000000007;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
long x = s.nextLong(), k = s.nextLong();
if (x == 0) {
System.out.println(0);
return;
}
long max = x % mod;
long temp = power(2, k, mod);
temp %= mod;
max = (max % mod) * (temp % mod);
max %= mod;
long min = max % mod;
min = mod(min - (temp - 1));
min %= mod;
long num = mod(max - min + 1);
long n = num % mod;
n = (n % mod) * (min % mod + max % mod);
n = n % mod;
n %= mod;
long ans = n % mod * modInverse(num, mod);
System.out.println(ans % mod);
}
static long modInverse(long a, long m) {
long m0 = m;
long y = 0, x = 1;
if (m == 1)
return 0;
while (a > 1) {
// q is quotient
long q = a / m;
long t = m;
// m is remainder now, process same as
// Euclid's algo
m = a % m;
a = t;
t = y;
// Update y and x
y = x - q * y;
x = t;
}
// Make x positive
if (x < 0)
x += m0;
return x;
}
static long mod(long val) {
val %= mod;
if (val < 0)
val += mod;
return val;
}
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;
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.*;
import java.util.StringTokenizer;
public class C {
static final int MOD = (int)1e9 + 7;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
long x = sc.nextLong(), k = sc.nextLong();
if(x == 0)
out.println(0);
else
out.println(((x % MOD * 2 - 1 + MOD) % MOD * modPow(2, k) % MOD + 1) % MOD);
out.close();
}
static long modPow(long b, long e) {
long res = 1;
while(e > 0) {
if((e & 1) == 1)
res = res * b % MOD;
b = b * b % MOD;
e >>= 1;
}
return res;
}
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 double nextDouble() throws IOException { return Double.parseDouble(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.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 Rishabhdeep Singh
*/
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);
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, OutputWriter out) {
long x = in.nextLong(), k = in.nextLong();
long res = Utilities.mul(x, Utilities.power(2, k + 1, MOD), MOD) % MOD - Utilities.power(2, k, MOD) + 1;
while (res < 0) res += MOD;
out.println(x == 0 ? 0 : res);
}
}
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 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 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);
}
}
static class Utilities {
public static long mul(long x, long y, long mod) {
return (x % mod) * (y % mod) % mod;
}
public static long power(long a, long k, long m) {
long res = 1;
while (k > 0) {
if ((k & 1) != 0) {
res = mul(res, a, m);
}
a = mul(a, a, m);
k >>= 1;
}
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.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 Rishabhdeep Singh
*/
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);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
int MOD = (int) 1e9 + 7;
long power(long a, long k) {
long res = 1;
while (k > 0) {
if ((k & 1) != 0) {
res = res * a % MOD;
}
a = a * a % MOD;
k /= 2;
}
return res;
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
long x = in.nextLong(), k = in.nextLong();
if (x == 0) {
out.println(0);
return;
}
long res = ((power(2, k + 1) % MOD) * (x % MOD)) % MOD;
long temp = power(2, k);
res = res - temp + 1;
while (res < 0) res += MOD;
out.println(res);
}
}
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 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 static boolean isWhitespace(int 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 java.util.*;
import java.io.*;
// Solution
public class Main
{
public static void main (String[] argv)
{
new Main();
}
boolean test = false;
int n;
long mod = 1000000007;
public Main() {
FastReader in = new FastReader(new BufferedReader(new InputStreamReader(System.in)));
//FastReader in = new FastReader(new BufferedReader(new FileReader("Main.in")));
long x = in.nextLong();
long k = in.nextLong();
if (x == 0) {
System.out.println(0);
return;
}
if (k == 0) {
x %= mod;
System.out.println((2*x%mod));
return;
}
x %= mod;
long f = pow(2, k);
long ans = ((2 * f * x % mod - f + 1) % mod + mod) % mod;
System.out.println(ans);
}
private long pow(long x, long y) {
long ans = 1;
while (y > 0) {
if (y % 2 == 1)
ans = ans * x % mod;
x = x * x % mod;
y /= 2;
}
return ans;
}
private long gcd(long x, long y) {
if (y == 0) return x;
return gcd(y, x % y);
}
private int max(int a, int b) {
return a > b ? a : b;
}
private int min(int a, int b) {
return a > b ? b : a;
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader(BufferedReader in)
{
br = in;
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
String line = br.readLine();
if (line == null || line.length() == 0) return "";
st = new StringTokenizer(line);
}
catch (IOException e)
{
return "";
//e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
return "";
//e.printStackTrace();
}
return str;
}
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.*;
import java.util.*;
/*
* Heart beats fast
* Colors and promises
* How to be brave
* How can I love when I am afraid...
*/
public class Main
{
public static void main(String[] args)
{
long x=nl(),k=nl();
if(x==0)
{
pr(0);
exit();
}
x%=mod;
pr((((x*powm(2,k+1,mod))%mod-powm(2,k,mod)+1)%mod+mod)%mod);
System.out.print(output);
}
///////////////////////////////////////////
///////////////////////////////////////////
///template from here
static class pair
{
long a, b;
pair(){}
pair(long c,long d){a=c;b=d;}
}
static interface combiner
{
public long combine(long a, long b);
}
static final int mod=1000000007;
static final double eps=1e-9;
static final long inf=100000000000000000L;
static Reader in=new Reader();
static StringBuilder output=new StringBuilder();
static Random rn=new Random();
static void reverse(int[]a){for(int i=0; i<a.length/2; i++){a[i]^=a[a.length-i-1];a[a.length-i-1]^=a[i];a[i]^=a[a.length-i-1];}}
static void sort(int[]a)
{
int te;
for(int i=0; i<a.length; i+=2)
{
te=rn.nextInt(a.length);
if(i!=te)
{
a[i]^=a[te];
a[te]^=a[i];
a[i]^=a[te];
}
}
Arrays.sort(a);
}
static void sort(long[]a)
{
int te;
for(int i=0; i<a.length; i+=2)
{
te=rn.nextInt(a.length);
if(i!=te)
{
a[i]^=a[te];
a[te]^=a[i];
a[i]^=a[te];
}
}
Arrays.sort(a);
}
static void sort(double[]a)
{
int te;
double te1;
for(int i=0; i<a.length; i+=2)
{
te=rn.nextInt(a.length);
if(i!=te)
{
te1=a[te];
a[te]=a[i];
a[i]=te1;
}
}
Arrays.sort(a);
}
static void sort(int[][]a)
{
Arrays.sort(a, new Comparator<int[]>()
{
public int compare(int[]a,int[]b)
{
if(a[0]>b[0])
return -1;
if(b[0]>a[0])
return 1;
return 0;
}
});
}
static void sort(pair[]a)
{
Arrays.sort(a,new Comparator<pair>()
{
@Override
public int compare(pair a,pair b)
{
if(a.a>b.a)
return 1;
if(b.a>a.a)
return -1;
return 0;
}
});
}
static int log2n(long a)
{
int te=0;
while(a>0)
{
a>>=1;
++te;
}
return te;
}
static class vector implements Iterable<Integer>
{
int a[],size;
vector(){a=new int[10];size=0;}
vector(int n){a=new int[n];size=0;}
public void add(int b){if(++size==a.length)a=Arrays.copyOf(a, 2*size);a[size-1]=b;}
public void sort(){Arrays.sort(a, 0, size);}
public void sort(int l, int r){Arrays.sort(a, l, r);}
@Override
public Iterator<Integer> iterator() {
Iterator<Integer> hola=new Iterator<Integer>()
{
int cur=0;
@Override
public boolean hasNext() {
return cur<size;
}
@Override
public Integer next() {
return a[cur++];
}
};
return hola;
}
}
//output functions////////////////
static void pr(Object a){output.append(a+"\n");}
static void pr(){output.append("\n");}
static void p(Object a){output.append(a);}
static void pra(int[]a){for(int i:a)output.append(i+" ");output.append("\n");}
static void pra(long[]a){for(long i:a)output.append(i+" ");output.append("\n");}
static void pra(String[]a){for(String i:a)output.append(i+" ");output.append("\n");}
static void pra(double[]a){for(double i:a)output.append(i+" ");output.append("\n");}
static void sop(Object a){System.out.println(a);}
static void flush(){System.out.println(output);output=new StringBuilder();}
//////////////////////////////////
//input functions/////////////////
static int ni(){return Integer.parseInt(in.next());}
static long nl(){return Long.parseLong(in.next());}
static String ns(){return in.next();}
static double nd(){return Double.parseDouble(in.next());}
static int[] nia(int n){int a[]=new int[n];for(int i=0; i<n; i++)a[i]=ni();return a;}
static int[] pnia(int n){int a[]=new int[n+1];for(int i=1; i<=n; i++)a[i]=ni();return a;}
static long[] nla(int n){long a[]=new long[n];for(int i=0; i<n; i++)a[i]=nl();return a;}
static String[] nsa(int n){String a[]=new String[n];for(int i=0; i<n; i++)a[i]=ns();return a;}
static double[] nda(int n){double a[]=new double[n];for(int i=0; i<n; i++)a[i]=nd();return a;}
//////////////////////////////////
//some utility functions
static void exit(){System.out.print(output);System.exit(0);}
static int min(int... a){int min=a[0];for(int i:a)min=Math.min(min, i);return min;}
static int max(int... a){int max=a[0];for(int i:a)max=Math.max(max, i);return max;}
static int gcd(int... a){int gcd=a[0];for(int i:a)gcd=gcd(gcd, i);return gcd;}
static long min(long... a){long min=a[0];for(long i:a)min=Math.min(min, i);return min;}
static long max(long... a){long max=a[0];for(long i:a)max=Math.max(max, i);return max;}
static long gcd(long... a){long gcd=a[0];for(long i:a)gcd=gcd(gcd, i);return gcd;}
static String pr(String a, long b){String c="";while(b>0){if(b%2==1)c=c.concat(a);a=a.concat(a);b>>=1;}return c;}
static long powm(long a, long b, long m)
{long an=1;long c=a;while(b>0)
{if(b%2==1)an=(an*c)%m;c=(c*c)%m;b>>=1;}return an;}
static int gcd(int a, int b){if(b==0)return a;return gcd(b, a%b);}
static long gcd(long a, long b){if(b==0)return a;return gcd(b, a%b);}
static class Reader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public Reader() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
public class Main {
private static void solve() {
long x = nl();
long k = nl();
long mod = 1000000000 + 7;
if (x == 0) {
System.out.println(0);
} else if (k == 0) {
System.out.println(x * 2 % mod);
} else {
//x > 0, n > 0
x %= mod;
long a;
a = (x - 1 + mod) * pow(2, k, mod) + 1;
a %= mod;
long b = x * pow(2, k, mod);
b %= mod;
System.out.println((a + b) % mod);
}
}
public static long pow(long a, long n, long mod)
{
// a %= mod;
long ret = 1; // 1%mod if mod=1,n=0
int x = 63-Long.numberOfLeadingZeros(n);
for(;x >= 0;x--){
ret = ret * ret % mod;
if(n<<~x<0)ret = ret * a % mod;
}
return ret;
}
public static void main(String[] args) {
new Thread(null, new Runnable() {
@Override
public void run() {
long start = System.currentTimeMillis();
String debug = args.length > 0 ? args[0] : null;
if (debug != null) {
try {
is = java.nio.file.Files.newInputStream(java.nio.file.Paths.get(debug));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
reader = new java.io.BufferedReader(new java.io.InputStreamReader(is), 32768);
solve();
out.flush();
tr((System.currentTimeMillis() - start) + "ms");
}
}, "", 64000000).start();
}
private static java.io.InputStream is = System.in;
private static java.io.PrintWriter out = new java.io.PrintWriter(System.out);
private static java.util.StringTokenizer tokenizer = null;
private static java.io.BufferedReader reader;
public static String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new java.util.StringTokenizer(reader.readLine());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
private static double nd() {
return Double.parseDouble(next());
}
private static long nl() {
return Long.parseLong(next());
}
private static int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private static char[] ns() {
return next().toCharArray();
}
private static long[] nal(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nl();
return a;
}
private static int[][] ntable(int n, int m) {
int[][] table = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
table[i][j] = ni();
}
}
return table;
}
private static int[][] nlist(int n, int m) {
int[][] table = new int[m][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
table[j][i] = ni();
}
}
return table;
}
private static int ni() {
return Integer.parseInt(next());
}
private static void tr(Object... o) {
if (is != System.in)
System.out.println(java.util.Arrays.deepToString(o));
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.*;
import java.util.*;
public class template
{
private InputStream is;
private PrintWriter pw;
static char[][] ch;
static int x1,x2,y1,y2,n,m,h,k;
static long dist[][];
static boolean boo[][];
void soln()
{
is = System.in;
pw = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
pw.close();
pw.flush();
// tr(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception
{
new Thread(null, new Runnable()
{
public void run()
{
try
{
// new CODEFORCES().soln();
} catch (Exception e)
{
System.out.println(e);
}
}
}, "1", 1 << 26).start();
new template().soln();
}
void solve()
{
long n = nl(), k = nl();
if(n==0){
pw.println(0);
return;
}
long MOD = 1000000007;
long pow1 = pow(2,k,MOD), pow2 = pow(2,k+1,MOD);
pw.println(((((n%MOD)*pow2)%MOD) - (pow1-1+MOD)%MOD + 2*MOD)%MOD);
pw.close();
}
long pow(long x, long y, long mod){
long ans = 1;
while(y>0){
if(y%2==0) {
x *= x;
x %= mod;
y/=2;
}
else{
ans *= x;
ans %= mod;
y-=1;
}
}
return ans;
}
long gcd(long a, long b){
if(b==0) return a;
return gcd(b,a%b);
}
void printArray(long[] arr) {
for(long i : arr) pw.print(i +" ");
pw.println();
}
static long min(long x, long y){
return (x<y)?x:y;
}
static class Pair implements Comparable<Pair>{
long val;
int x, y;
Pair(long v, int a, int b){
val = v; x = a; y = b;
}
public int compareTo(Pair p){
return Long.compare(this.val,p.val);
}
}
private static class Queue{
int st = 0;
int et = 0;
Pair[] arr;
public Queue(int len) {
arr = new Pair[len];
}
public boolean isEmpty() {
return st==et;
}
public void add(Pair x) {
arr[et++] = x;
}
public Pair poll() {
return arr[st++];
}
public void clear() {
st = et = 0;
}
}
/*void bfs(int k) {
while(!q.isEmpty()) {
int y = q.poll();
for(long i : amp[y]) {
if(!b[i]) {
D[i][k] = D[y][k]+1;
q.add(i);
b[i] = true;
}
}
}
}
*/
/*
int dfs(int x) {
b[x] = true;
//start[x] = time++;
int ans = 1;
for(int i : amp[x]) {
if(!b[i]) {
ans += dfs(i);
}
}
//end[x] = time;
if(x!= 0 && ans%2==0 && (N-ans)%2==0) cost++;
return ans;
}*/
/*void buildGraph(int n)
{
for (int i = 0; i < n; i++)
{
int x1 = ni() - 1, y1 = ni() - 1;
amp[x1].add(y1);
amp[y1].add(x1);
}
}*/
public static int[] shuffle(int[] a, Random gen)
{
for (int i = 0, n = a.length; i < n; i++)
{
int ind = gen.nextInt(n - i) + i;
int d = a[i];
a[i] = a[ind];
a[ind] = d;
}
return a;
}
// To Get Input
// Some Buffer Methods
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.*;
import java.util.*;
import java.math.BigInteger;
import java.util.Map.Entry;
import static java.lang.Math.*;
public class C extends PrintWriter {
final long mod = 1_000_000_007;
long pow(long n, long p) {
long r = 1;
while (p > 0) {
if (p % 2 == 1) {
r = (r * n) % mod;
}
n = (n * n) % mod;
p /= 2;
}
return r;
}
long solve(long n, long k) {
if (k == 0) {
return (2 * n) % mod;
}
if (n == 0) {
return 0;
}
long m = pow(2, k);
long a = 2;
a = (a * n) % mod;
a = (a * m) % mod;
long b = (m + mod - 1) % mod;
return ((a - b + mod) % mod);
}
void run() {
long n = nextLong();
long k = nextLong();
println(solve(n, k));
}
boolean skip() {
while (hasNext()) {
next();
}
return true;
}
int[][] nextMatrix(int n, int m) {
int[][] matrix = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
matrix[i][j] = nextInt();
return matrix;
}
String next() {
while (!tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(nextLine());
return tokenizer.nextToken();
}
boolean hasNext() {
while (!tokenizer.hasMoreTokens()) {
String line = nextLine();
if (line == null) {
return false;
}
tokenizer = new StringTokenizer(line);
}
return true;
}
int[] nextArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = nextInt();
}
return array;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
try {
return reader.readLine();
} catch (IOException err) {
return null;
}
}
public C(OutputStream outputStream) {
super(outputStream);
}
static BufferedReader reader;
static StringTokenizer tokenizer = new StringTokenizer("");
static Random rnd = new Random();
static boolean OJ;
public static void main(String[] args) throws IOException {
OJ = System.getProperty("ONLINE_JUDGE") != null;
C solution = new C(System.out);
if (OJ) {
reader = new BufferedReader(new InputStreamReader(System.in));
solution.run();
} else {
reader = new BufferedReader(new FileReader(new File(C.class.getName() + ".txt")));
long timeout = System.currentTimeMillis();
while (solution.hasNext()) {
solution.run();
solution.println();
solution.println("----------------------------------");
}
solution.println("time: " + (System.currentTimeMillis() - timeout));
}
solution.close();
reader.close();
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
import java.util.StringTokenizer;
public class Main{
public long power(long x, long y, long p)
{
long res = 1;
while (y > 0)
{
if((y & 1)==1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
Main mm=new Main();
long x=sc.nextLong();
long k=sc.nextLong();
if(x==0) {
System.out.println(0);
}
else {
long temp=mm.power(2, k, 1000000007);
long temp1=(2*x-1)%(1000000007);
long temp3=(temp1*temp)%(1000000007);
System.out.println((temp3+1)%1000000007);
}
}
}
class trienode{
trienode[] next=new trienode[26];
int count;
char value;
boolean last;
trienode() {
this.value='0';
this.count=0;
}
trienode(char x) {
this.value=x;
this.count=1;
}
}
class trie{
trienode root=new trienode();
public void insert(String s) {
trienode temp=root;
int length=s.length();
for(int i=0;i<length;i++) {
char c=s.charAt(i);
int index=c-'a';
if(temp.next[index]==null) {
temp.next[index]=new trienode(c);
}
else {
temp.next[index].count++;
}
if(i==length-1) {
temp.next[index].last=true;
}
temp=temp.next[index];
}
}
public String find(String s) {
trienode temp=root;
String ans="";
int pos=0;
char c=s.charAt(pos);
int index=c-'a';
while(temp.next[index]!=null) {
temp=temp.next[index];
ans+=temp.value;
if(pos==s.length()-1) {
break;
}
c=s.charAt(++pos);
index=c-'a';
}
while(temp.last!=true) {
int position=-1;
for(int i=0;i<26;i++) {
if(temp.next[i]!=null) {
ans+=temp.next[i].value;
position=i+0;
break;
}
}
temp=temp.next[position];
}
return ans;
}
}
class node{
int index;
int a;
int b;
node(int index,int a,int b){
this.a=a;
this.b=b;this.index=index;
}
}
class comp implements Comparator<node>{
public int compare(node n1,node n2) {
if(n1.b>n2.b) {
return 1;
}
else if(n1.b<n2.b) {
return -1;
}
else {
return 0;
}
}
}
class cc implements Comparator<node>{
public int compare(node n1,node n2) {
if(n1.index>n2.index) {
return 1;
}
else if(n1.index<n2.index) {
return -1;
}
else {
return 0;
}
}
}
/** Class for buffered reading int and double values */
class Reader {
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() );
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.util.*;
import java.io.*;
public class virtual1{
static InputReader in = new InputReader();
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
long x = in.nextLong();
long k = in.nextLong();
long mod = (long)1e9+7l;
//out.println(mod);
long mul1 = 1;
long mul2 = 2*x-1;
mul2 = mul2%mod;
long pow = k;
long to = 2;
while(pow>0l){
if(pow%2l==1l){
mul1 = mul1*to;
mul1%=mod;
}
to=to*to;
to%=mod;
pow = pow/2l;
}
mul1 = mul1*mul2;
mul1%=mod;
mul1+=1;
if(x!=0)
out.println(mul1%mod);
else
out.println(0);
out.close();
}
static class InputReader
{
BufferedReader br;
StringTokenizer st;
public InputReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.util.*;
public class algo93
{
public static void main(String args[])
{
Scanner ex=new Scanner(System.in);
long x=ex.nextLong();
long k=ex.nextLong();
long mod=1000000007;
if(k==0)
System.out.println((2*x)%mod);
else if(x==0)
System.out.println("0");
else
{
long pow=power(2,k);
long pow1=(2*pow)%mod;
long ans=(pow1*(x%mod))-pow+1;
if(ans<0)
ans=ans+mod;
ans=ans%mod;
System.out.println(ans);
}
}
public static long power(long x,long y)
{
if (y == 0)
return 1;
long mod=1000000007;
long pow=power(x,y/2);
pow=(pow*pow)%mod;
if(y%2==0)
return pow;
else
return ((x%mod)*pow)%mod;
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.*;
import java.util.StringTokenizer;
public class Test {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in), 1024 * 48);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String str = br.readLine();
StringTokenizer st = new StringTokenizer(str, " ");
long x = Long.parseLong(st.nextToken());
long k = Long.parseLong(st.nextToken());
if (x == 0) {
bw.write(0 + "\n");
} else {
int power = power(k, 1000000007);
long answer = (((power * 2) % 1000000007) * (x % 1000000007)) % 1000000007;
answer -= power - 1;
answer = (answer + 1000000007) % 1000000007;
bw.write(answer + "\n");
}
bw.flush();
}
public static int power(long a, int m) {
if (a == 0) {
return 1;
}
long pow = power(a / 2, m);
if (a % 2 == 1) {
return (int)(((pow * pow) % m) * 2) % m;
} else {
return (int)((pow * pow) % m);
}
}
}
| logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
static long MOD=1000000007;
public static 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;
}
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=pow(2L,k+1);
long b=pow(2L,k);
long res=(a*x)%MOD-b+1;
if(res<0){res+=MOD;}
System.out.println(res%MOD);
}
} | logn | 992_C. Nastya and a Wardrobe | CODEFORCES |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* #
* @author pttrung
*/
public class B_Round_371_Div1 {
public static long MOD = 1000000007;
static int c = 0;
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
// "output.txt")));
Scanner in = new Scanner();
int n = in.nextInt();
int minX = -1;
int start = 1;
int end = n;
c = 0;
while (start <= end) {
int mid = (start + end) >> 1;
c = increaseC(c);
System.out.println("? " + mid + " 1 " + n + " " + n);
System.out.flush();
int v = in.nextInt();
if (v == 2) {
minX = mid;
start = mid + 1;
} else {
end = mid - 1;
}
}
//System.out.println("Minx " + minX);
int maxX = -1;
start = minX;
end = n;
while (start <= end) {
int mid = (start + end) >> 1;
c = increaseC(c);
System.out.println("? " + minX + " 1 " + mid + " " + n);
System.out.flush();
int v = in.nextInt();
if (v == 2) {
maxX = mid;
end = mid - 1;
} else {
start = mid + 1;
}
}
// System.out.println("Maxx " + maxX);
int minY = -1;
start = 1;
end = n;
while (start <= end) {
int mid = (start + end) >> 1;
c = increaseC(c);
System.out.println("? " + minX + " " + mid + " " + maxX + " " + n);
System.out.flush();
int v = in.nextInt();
if (v == 2) {
minY = mid;
start = mid + 1;
} else {
end = mid - 1;
}
}
// System.out.println("MinY " + minY);
int maxY = -1;
start = minY;
end = n;
while (start <= end) {
int mid = (start + end) >> 1;
c = increaseC(c);
System.out.println("? " + minX + " " + minY + " " + maxX + " " + mid);
System.out.flush();
int v = in.nextInt();
if (v == 2) {
maxY = mid;
end = mid - 1;
} else {
start = mid + 1;
}
}
// System.out.println("MaxY " + maxY);
int middleMinX = maxX;
start = minX;
end = maxX;
while (start <= end) {
int mid = (start + end) >> 1;
c = increaseC(c);
System.out.println("? " + minX + " " + minY + " " + mid + " " + maxY);
System.out.flush();
int v = in.nextInt();
if (v == 1) {
middleMinX = mid;
end = mid - 1;
} else {
start = mid + 1;
}
}
//System.out.println("MiddleMinX " + middleMinX);
int middleMaxX = -1;
start = middleMinX + 1;
end = maxX;
while (start <= end) {
int mid = (start + end) >> 1;
c = increaseC(c);
System.out.println("? " + mid + " " + minY + " " + maxX + " " + maxY);
System.out.flush();
int v = in.nextInt();
if (v == 1) {
middleMaxX = mid;
start = mid + 1;
} else {
end = mid - 1;
}
}
// System.out.println("MiddleMaxX " + middleMaxX);
if (middleMaxX == -1) {
int middleMinY = -1;
start = minY;
end = maxY;
while (start <= end) {
int mid = (start + end) >> 1;
c = increaseC(c);
System.out.println("? " + minX + " " + minY + " " + maxX + " " + mid);
System.out.flush();
int v = in.nextInt();
if (v == 1) {
middleMinY = mid;
end = mid - 1;
} else {
start = mid + 1;
}
}
//System.out.println("MiddleMinY " + middleMinY);
int middleMaxY = -1;
start = middleMinY + 1;
end = maxY;
while (start <= end) {
int mid = (start + end) >> 1;
c = increaseC(c);
System.out.println("? " + minX + " " + mid + " " + maxX + " " + maxY);
System.out.flush();
int v = in.nextInt();
if (v == 1) {
middleMaxY = mid;
start = mid + 1;
} else {
end = mid - 1;
}
}
//System.out.println("MiddleMaxY " + middleMaxY);
if (minX == maxX) {
System.out.println("! " + minX + " " + minY + " " + maxX + " " + middleMinY + " " + minX + " " + middleMaxY + " " + maxX + " " + maxY);
System.out.flush();
} else {
int[] a = calX(minX, maxX, minY, middleMinY, in);
int[] b = calX(minX, maxX, middleMaxY, maxY, in);
check(a);
check(b);
System.out.println("! " + a[0] + " " + minY + " " + a[1] + " " + middleMinY + " " + b[0] + " " + middleMaxY + " " + b[1] + " " + maxY);
System.out.flush();
}
} else if (minY == maxY) {
System.out.println("! " + minX + " " + minY + " " + middleMinX + " " + maxY + " " + middleMaxX + " " + minY + " " + maxX + " " + maxY);
System.out.flush();
} else {
int[] a = calY(minX, middleMinX, minY, maxY, in);
int[] b = calY(middleMaxX, maxX, minY, maxY, in);
check(a);
check(b);
System.out.println("! " + minX + " " + a[0] + " " + middleMinX + " " + a[1] + " " + middleMaxX + " " + b[0] + " " + maxX + " " + b[1]);
System.out.flush();
}
}
static void check(int[] v) {
if (v[0] == -1 || v[1] == -1) {
throw new NullPointerException();
}
}
static int increaseC(int c) {
if (c == 200) {
throw new NullPointerException();
}
return c + 1;
}
public static int[] calY(int minX, int maxX, int minY, int maxY, Scanner in) {
c = increaseC(c);
System.out.println("? " + minX + " " + minY + " " + maxX + " " + (maxY - 1));
System.out.flush();
int v = in.nextInt();
c = increaseC(c);
System.out.println("? " + minX + " " + (minY + 1) + " " + maxX + " " + maxY);
System.out.flush();
int o = in.nextInt();
if (v == 1 && o == 1) {
int a = -1;
int start = minY;
int end = maxY;
while (start <= end) {
int mid = (start + end) >> 1;
c = increaseC(c);
System.out.println("? " + minX + " " + minY + " " + maxX + " " + mid);
System.out.flush();
if (in.nextInt() == 1) {
a = mid;
end = mid - 1;
} else {
start = mid + 1;
}
}
int b = -1;
start = minY;
end = a;
while (start <= end) {
int mid = (start + end) >> 1;
c = increaseC(c);
System.out.println("? " + minX + " " + mid + " " + maxX + " " + a);
System.out.flush();
if (in.nextInt() == 1) {
b = mid;
start = mid + 1;
} else {
end = mid - 1;
}
}
return new int[]{b, a};
} else if (v == 1) {
int a = -1;
int start = minY;
int end = maxY;
while (start <= end) {
int mid = (start + end) >> 1;
c = increaseC(c);
System.out.println("? " + minX + " " + minY + " " + maxX + " " + mid);
System.out.flush();
if (in.nextInt() == 1) {
a = mid;
end = mid - 1;
} else {
start = mid + 1;
}
}
return new int[]{minY, a};
} else if (o == 1) {
int b = -1;
int start = minY;
int end = maxY;
while (start <= end) {
int mid = (start + end) >> 1;
c = increaseC(c);
System.out.println("? " + minX + " " + mid + " " + maxX + " " + maxY);
System.out.flush();
if (in.nextInt() == 1) {
b = mid;
start = mid + 1;
} else {
end = mid - 1;
}
}
return new int[]{b, maxY};
} else {
return new int[]{minY, maxY};
}
}
public static int[] calX(int minX, int maxX, int minY, int maxY, Scanner in) {
c = increaseC(c);
System.out.println("? " + minX + " " + minY + " " + (maxX - 1) + " " + maxY);
System.out.flush();
int v = in.nextInt();
c = increaseC(c);
System.out.println("? " + (minX + 1) + " " + minY + " " + maxX + " " + maxY);
System.out.flush();
int o = in.nextInt();
if (v == 1 && o == 1) {
int a = -1;
int start = minX;
int end = maxX;
while (start <= end) {
int mid = (start + end) >> 1;
c = increaseC(c);
System.out.println("? " + minX + " " + minY + " " + mid + " " + maxY);
System.out.flush();
if (in.nextInt() == 1) {
a = mid;
end = mid - 1;
} else {
start = mid + 1;
}
}
int b = -1;
start = minX;
end = a;
while (start <= end) {
int mid = (start + end) >> 1;
c = increaseC(c);
System.out.println("? " + mid + " " + minY + " " + a + " " + maxY);
System.out.flush();
if (in.nextInt() == 1) {
b = mid;
start = mid + 1;
} else {
end = mid - 1;
}
}
return new int[]{b, a};
} else if (v == 1) {
int a = -1;
int start = minX;
int end = maxX;
while (start <= end) {
int mid = (start + end) >> 1;
c = increaseC(c);
System.out.println("? " + minX + " " + minY + " " + mid + " " + maxY);
System.out.flush();
if (in.nextInt() == 1) {
a = mid;
end = mid - 1;
} else {
start = mid + 1;
}
}
return new int[]{minX, a};
} else if (o == 1) {
int b = -1;
int start = minX;
int end = maxX;
while (start <= end) {
int mid = (start + end) >> 1;
c = increaseC(c);
System.out.println("? " + mid + " " + minY + " " + maxX + " " + maxY);
System.out.flush();
if (in.nextInt() == 1) {
b = mid;
start = mid + 1;
} else {
end = mid - 1;
}
}
return new int[]{b, maxX};
} else {
return new int[]{minX, maxX};
}
}
public static int[] KMP(String val) {
int i = 0;
int j = -1;
int[] result = new int[val.length() + 1];
result[0] = -1;
while (i < val.length()) {
while (j >= 0 && val.charAt(j) != val.charAt(i)) {
j = result[j];
}
j++;
i++;
result[i] = j;
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
public static int digit(long n) {
int result = 0;
while (n > 0) {
n /= 10;
result++;
}
return result;
}
public static double dist(long a, long b, long x, long y) {
double val = (b - a) * (b - a) + (x - y) * (x - y);
val = Math.sqrt(val);
double other = x * x + a * a;
other = Math.sqrt(other);
return val + other;
}
public static class Point implements Comparable<Point> {
int x, y;
public Point(int start, int end) {
this.x = start;
this.y = end;
}
@Override
public int hashCode() {
int hash = 5;
hash = 47 * hash + this.x;
hash = 47 * hash + this.y;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Point other = (Point) obj;
if (this.x != other.x) {
return false;
}
if (this.y != other.y) {
return false;
}
return true;
}
@Override
public int compareTo(Point o) {
return Integer.compare(x, o.x);
}
}
public static class FT {
long[] data;
FT(int n) {
data = new long[n];
}
public void update(int index, long value) {
while (index < data.length) {
data[index] += value;
index += (index & (-index));
}
}
public long get(int index) {
long result = 0;
while (index > 0) {
result += data[index];
index -= (index & (-index));
}
return result;
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static long pow(long a, long b, long MOD) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2, MOD);
if (b % 2 == 0) {
return val * val % MOD;
} else {
return val * (val * a % MOD) % MOD;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
// System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
} | logn | 713_B. Searching Rectangles | 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.util.Scanner;
import java.util.InputMismatchException;
import java.util.HashMap;
import java.io.IOException;
import java.util.ArrayList;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author ilyakor
*/
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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
ArrayList<PointInt[]> al;
TaskB.Interactor interactor;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
//for (int itt = 0; itt < 100; ++itt) {
interactor = new TaskB.IOInteractor(new Scanner(in.getStream()), out.getWriter());//new TestInteractor(n);
Assert.assertTrue(interactor.query(1, 1, n, n) == 2);
int lx = 1, rx = n, ly = 1, ry = n;
for (int it = 0; it < 20; ++it) {
int tx = (lx + rx) / 2;
if (interactor.query(1, 1, tx, n) >= 1)
rx = tx;
else
lx = tx;
int ty = (ly + ry) / 2;
if (interactor.query(1, 1, n, ty) >= 1)
ry = ty;
else
ly = ty;
}
al = new ArrayList<>();
if (interactor.query(1, 1, lx, n) == 1 && interactor.query(lx + 1, 1, n, n) == 1) {
dfs(1, 1, lx, n);
dfs(lx + 1, 1, n, n);
} else if (interactor.query(1, 1, rx, n) == 1 && interactor.query(rx + 1, 1, n, n) == 1) {
dfs(1, 1, rx, n);
dfs(rx + 1, 1, n, n);
} else if (interactor.query(1, 1, n, ly) == 1 && interactor.query(1, ly + 1, n, n) == 1) {
dfs(1, 1, n, ly);
dfs(1, ly + 1, n, n);
} else if (interactor.query(1, 1, n, ry) == 1 && interactor.query(1, ry + 1, n, n) == 1) {
dfs(1, 1, n, ry);
dfs(1, ry + 1, n, n);
} else {
throw new RuntimeException("WTF");
}
Assert.assertTrue(al.size() == 2);
interactor.answer(al.get(0)[0].x, al.get(0)[0].y, al.get(0)[1].x, al.get(0)[1].y, al.get(1)[0].x, al.get(1)[0].y, al.get(1)[1].x, al.get(1)[1].y);
//}
}
private void dfs(int x1, int y1, int x2, int y2) {
int t;
t = x1;
for (int i = 0; i < 20; ++i) {
int x = (t + x2) / 2;
if (interactor.query(x1, y1, x, y2) == 1)
x2 = x;
else
t = x;
}
if (interactor.query(x1, y1, t, y2) == 1)
x2 = t;
t = x2;
for (int i = 0; i < 20; ++i) {
int x = (t + x1) / 2;
if (interactor.query(x, y1, x2, y2) == 1)
x1 = x;
else
t = x;
}
if (interactor.query(t, y1, x2, y2) == 1)
x1 = t;
t = y1;
for (int i = 0; i < 20; ++i) {
int y = (t + y2) / 2;
if (interactor.query(x1, y1, x2, y) == 1)
y2 = y;
else
t = y;
}
if (interactor.query(x1, y1, x2, t) == 1)
y2 = t;
t = y2;
for (int i = 0; i < 20; ++i) {
int y = (t + y1) / 2;
if (interactor.query(x1, y, x2, y2) == 1)
y1 = y;
else
t = y;
}
if (interactor.query(x1, t, x2, y2) == 1)
y1 = t;
al.add(new PointInt[]{new PointInt(x1, y1), new PointInt(x2, y2)});
}
interface Interactor {
int query(int x1, int y1, int x2, int y2);
void answer(int x11, int y11, int x12, int y12,
int x21, int y21, int x22, int y22);
}
static class Query {
int x1;
int y1;
int x2;
int y2;
public Query(int x1, int y1, int x2, int y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TaskB.Query query = (TaskB.Query) o;
if (x1 != query.x1) return false;
if (y1 != query.y1) return false;
if (x2 != query.x2) return false;
return y2 == query.y2;
}
public int hashCode() {
int result = x1;
result = 31 * result + y1;
result = 31 * result + x2;
result = 31 * result + y2;
return result;
}
}
static class IOInteractor implements TaskB.Interactor {
Scanner in;
PrintWriter out;
HashMap<TaskB.Query, Integer> cache;
public IOInteractor(Scanner in, PrintWriter out) {
this.in = in;
this.out = out;
cache = new HashMap<>();
}
public int query(int x1, int y1, int x2, int y2) {
TaskB.Query q = new TaskB.Query(x1, y1, x2, y2);
if (cache.containsKey(q))
return cache.get(q);
if (x1 > x2 || y1 > y2)
return 0;
Assert.assertTrue(x1 >= 1 && y1 >= 1);
out.println("? " + x1 + " " + y1 + " " + x2 + " " + y2);
out.flush();
int res = in.nextInt();
cache.put(q, res);
return res;
}
public void answer(int x11, int y11, int x12, int y12, int x21, int y21, int x22, int y22) {
out.println("! " + x11 + " " + y11 + " " + x12 + " " + y12 + " " + x21 + " " + y21 + " " + x22 + " " + y22);
out.flush();
}
}
}
static 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 int nextInt() {
int sgn = 1;
int c = readSkipSpace();
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res = res * 10 + c - '0';
c = read();
} while (!isSpace(c));
res *= sgn;
return res;
}
public InputStream getStream() {
return stream;
}
}
static class PointInt {
public int x;
public int y;
public PointInt(int x, int y) {
this.x = x;
this.y = y;
}
public PointInt() {
x = 0;
y = 0;
}
}
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 PrintWriter getWriter() {
return writer;
}
public void close() {
writer.close();
}
}
static class Assert {
public static void assertTrue(boolean flag) {
// if (!flag)
// while (true);
if (!flag)
throw new AssertionError();
}
}
}
| logn | 713_B. Searching Rectangles | 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);
BSearchingRectangles solver = new BSearchingRectangles();
solver.solve(1, in, out);
out.close();
}
}
static class BSearchingRectangles {
FastInput in;
FastOutput out;
int n;
public void solve(int testNumber, FastInput in, FastOutput out) {
this.in = in;
this.out = out;
n = in.readInt();
IntBinarySearch upDown = new IntBinarySearch() {
public boolean check(int mid) {
return query(1, n, 1, mid) >= 1;
}
};
IntBinarySearch leftRight = new IntBinarySearch() {
public boolean check(int mid) {
return query(1, mid, 1, n) >= 1;
}
};
int threshold = upDown.binarySearch(1, n);
int[] r1;
int[] r2;
if (query(1, n, 1, threshold) == 1 &&
query(1, n, threshold + 1, n) == 1) {
r1 = find(1, n, 1, threshold);
r2 = find(1, n, threshold + 1, n);
} else {
threshold = leftRight.binarySearch(1, n);
r1 = find(1, threshold, 1, n);
r2 = find(threshold + 1, n, 1, n);
}
out.append("! ");
output(r1);
output(r2);
out.flush();
}
public void output(int[] ans) {
for (int x : ans) {
out.append(x).append(' ');
}
}
public int[] find(int l, int r, int d, int u) {
IntBinarySearch downIBS = new IntBinarySearch() {
public boolean check(int mid) {
return query(l, r, mid, u) == 0;
}
};
int y1 = downIBS.binarySearch(d, u);
if (query(l, r, y1, u) == 0) {
y1--;
}
IntBinarySearch upIBS = new IntBinarySearch() {
public boolean check(int mid) {
return query(l, r, d, mid) >= 1;
}
};
int y2 = upIBS.binarySearch(d, u);
IntBinarySearch leftIBS = new IntBinarySearch() {
public boolean check(int mid) {
return query(mid, r, d, u) == 0;
}
};
int x1 = leftIBS.binarySearch(l, r);
if (query(x1, r, d, u) == 0) {
x1--;
}
IntBinarySearch rightIBS = new IntBinarySearch() {
public boolean check(int mid) {
return query(l, mid, d, u) >= 1;
}
};
int x2 = rightIBS.binarySearch(l, r);
return new int[]{x1, y1, x2, y2};
}
public int query(int l, int r, int d, int u) {
if (l > r || d > u) {
return 0;
}
out.printf("? %d %d %d %d", l, d, r, u).println().flush();
return in.readInt();
}
}
static class DigitUtils {
private DigitUtils() {
}
public static int floorAverage(int x, int y) {
return (x & y) + ((x ^ y) >> 1);
}
}
static abstract class IntBinarySearch {
public abstract boolean check(int mid);
public int binarySearch(int l, int r) {
if (l > r) {
throw new IllegalArgumentException();
}
while (l < r) {
int mid = DigitUtils.floorAverage(l, r);
if (check(mid)) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
}
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 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 class FastOutput implements AutoCloseable, Closeable, Appendable {
private StringBuilder cache = new StringBuilder(10 << 20);
private final Writer os;
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;
}
public FastOutput(Writer os) {
this.os = os;
}
public FastOutput(OutputStream os) {
this(new OutputStreamWriter(os));
}
public FastOutput append(char c) {
cache.append(c);
return this;
}
public FastOutput append(int c) {
cache.append(c);
return this;
}
public FastOutput append(String c) {
cache.append(c);
return this;
}
public FastOutput printf(String format, Object... args) {
cache.append(String.format(format, args));
return this;
}
public FastOutput println() {
cache.append(System.lineSeparator());
return this;
}
public FastOutput flush() {
try {
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();
}
}
}
| logn | 713_B. Searching Rectangles | CODEFORCES |
import java.io.*;
import java.util.*;
import java.math.*;
public class B {
public static void main(String[] args) throws IOException {
/**/
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
/*/
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream("src/b.in"))));
/**/
int n = sc.nextInt();
int l1 = 1;
int r1 = n;
int b1 = 1;
int t1 = n;
int min = b1;
int max = t1;
while (min != max) {
int mid = (min+max)/2;
System.out.println("? "+l1+" "+b1+" "+r1+" "+mid);
System.out.flush();
if (sc.nextInt() >= 1)
max = mid;
else
min = mid+1;
}
t1 = min;
min = l1;
max = r1;
while (min != max) {
int mid = (min+max)/2;
System.out.println("? "+l1+" "+b1+" "+mid+" "+t1);
System.out.flush();
if (sc.nextInt() >= 1)
max = mid;
else
min = mid+1;
}
r1 = min;
min = b1;
max = t1;
while (min != max) {
int mid = (min+max+1)/2;
System.out.println("? "+l1+" "+mid+" "+r1+" "+t1);
System.out.flush();
if (sc.nextInt() >= 1)
min = mid;
else
max = mid-1;
}
b1 = min;
min = l1;
max = r1;
while (min != max) {
int mid = (min+max+1)/2;
System.out.println("? "+mid+" "+b1+" "+r1+" "+t1);
System.out.flush();
if (sc.nextInt() >= 1)
min = mid;
else
max = mid-1;
}
l1 = min;
int l2 = 1;
int r2 = n;
int b2 = 1;
int t2 = n;
min = b2;
max = t2;
while (min != max) {
int mid = (min+max+1)/2;
System.out.println("? "+l2+" "+mid+" "+r2+" "+t2);
System.out.flush();
if (sc.nextInt() >= 1)
min = mid;
else
max = mid-1;
}
b2 = min;
min = l2;
max = r2;
while (min != max) {
int mid = (min+max+1)/2;
System.out.println("? "+mid+" "+b2+" "+r2+" "+t2);
System.out.flush();
if (sc.nextInt() >= 1)
min = mid;
else
max = mid-1;
}
l2 = min;
min = b2;
max = t2;
while (min != max) {
int mid = (min+max)/2;
System.out.println("? "+l2+" "+b2+" "+r2+" "+mid);
System.out.flush();
if (sc.nextInt() >= 1)
max = mid;
else
min = mid+1;
}
t2 = min;
min = l2;
max = r2;
while (min != max) {
int mid = (min+max)/2;
System.out.println("? "+l2+" "+b2+" "+mid+" "+t2);
System.out.flush();
if (sc.nextInt() >= 1)
max = mid;
else
min = mid+1;
}
r2 = min;
System.out.println("! "+l1+" "+b1+" "+r1+" "+t1+" "+l2+" "+b2+" "+r2+" "+t2);
System.out.flush();
}
} | logn | 713_B. Searching Rectangles | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
private static StringTokenizer st;
private static BufferedReader br;
public static long MOD = 1000000007;
public static void print(Object x) {
System.out.println(x + "");
}
public static String join(Collection<?> x, String space) {
if (x.size() == 0) return "";
StringBuilder sb = new StringBuilder();
boolean first = true;
for (Object elt : x) {
if (first) first = false;
else sb.append(space);
sb.append(elt);
}
return sb.toString();
}
public static String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = br.readLine();
st = new StringTokenizer(line.trim());
}
return st.nextToken();
}
public static int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public static long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
// Finds smallest rectangle containing something along 1 dimension.
public static long[] search(long[] none, long[] some) throws IOException {
long[] med = new long[4];
for (int i = 0; i < 4; i++) {
if (Math.abs(none[i] - some[i]) == 1) {
return some;
}
med[i] = (none[i] + some[i]) / 2;
}
int ans = query(med);
if (ans > 0) return search(none, med);
else return search(med, some);
}
public static int query(long[] query) throws IOException {
print("? " + arr(query));
System.out.flush();
int ans = nextInt();
if (contains(query)) ans -= 1;
return ans;
}
public static boolean contains(long[] search) {
if (rect1 == null) return false;
if (search[0] > rect1[0]) return false;
if (search[1] > rect1[1]) return false;
if (search[2] < rect1[2]) return false;
if (search[3] < rect1[3]) return false;
return true;
}
public static String arr(long[] x) {
return x[0] + " " + x[1] + " " + x[2] + " " + x[3];
}
public static long[] find() throws IOException {
long[] d0 = {1, 1, 1, 1};
long[] some = {1, 1, n, n};
if (query(d0) > 0) {
return d0;
}
// print(" " + arr(some));
long[] none = {1, 1, n, 1};
if (query(none) > 0) some = none;
else some = search(none, some);
// print(" " + arr(some));
none = new long[] {1, 1, 1, some[3]};
if (query(none) > 0) some = none;
else some = search(none, some);
// print(" " + arr(some));
none = new long[] {1, some[3], some[2], some[3]};
if (query(none) > 0) some = none;
else some = search(none, some);
// print(" " + arr(some));
none = new long[] {some[2], some[1], some[2], some[3]};
if (query(none) > 0) some = none;
else some = search(none, some);
return some;
}
public static long[] rect1 = null;
public static long[] rect2 = null;
public static long n;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
n = nextLong();
rect1 = find();
rect2 = find();
print("! " + arr(rect1) + " "
+ arr(rect2));
System.out.flush();
}
}
| logn | 713_B. Searching Rectangles | CODEFORCES |
import java.io.*;
import java.util.Locale;
import java.util.StringTokenizer;
public class B implements Runnable {
private static final boolean ONLINE_JUDGE = true;//System.getProperty("ONLINE_JUDGE") != null;
private BufferedReader in;
private PrintWriter out;
private StringTokenizer tok = new StringTokenizer("");
private void init() throws FileNotFoundException {
Locale.setDefault(Locale.US);
String fileName = "";
if (ONLINE_JUDGE && fileName.isEmpty()) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
if (fileName.isEmpty()) {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} else {
in = new BufferedReader(new FileReader(fileName + ".in"));
out = new PrintWriter(fileName + ".out");
}
}
}
String readString() {
while (!tok.hasMoreTokens()) {
try {
tok = new StringTokenizer(in.readLine());
} catch (Exception e) {
return null;
}
}
return tok.nextToken();
}
int readInt() {
return Integer.parseInt(readString());
}
long readLong() {
return Long.parseLong(readString());
}
double readDouble() {
return Double.parseDouble(readString());
}
int[] readIntArray(int size) {
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = readInt();
}
return a;
}
public static void main(String[] args) {
//new Thread(null, new _Solution(), "", 128 * (1L << 20)).start();
new B().run();
}
long timeBegin, timeEnd;
void time() {
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
@Override
public void run() {
try {
timeBegin = System.currentTimeMillis();
init();
int n = readInt();
int[] rect1 = solve1(n);
int[] rect2 = solve2(n, rect1);
out.printf("! %s %s %s %s %s %s %s %s\n", rect1[0], rect1[1], rect1[2], rect1[3],
rect2[0], rect2[1], rect2[2], rect2[3]);
out.flush();
out.close();
time();
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
int ask(int x1, int y1, int x2, int y2) {
out.println("? " + x1 + " " + y1 + " " + x2 + " " + y2);
out.flush();
return readInt();
}
int ask(int x1, int y1, int x2, int y2, int[] rect) {
out.println("? " + x1 + " " + y1 + " " + x2 + " " + y2);
out.flush();
int res = readInt();
if (rect[0] >= x1 && rect[2] <= x2 && rect[1] >= y1 && rect[3] <= y2) {
res--;
}
return res;
}
int[] dropTopAndLeft1(int x2, int y2) {
int x1 = x2, y1 = y2;
int left = 1, right = x2;
while (left <= right) {
int mid = (left + right) >> 1;
int count = ask(mid, 1, x2, y2);
if (count >= 1) {
x1 = mid;
left = mid + 1;
}
if (count == 0) {
right = mid - 1;
}
}
left = 1;
right = y2;
while (left <= right) {
int mid = (left + right) >> 1;
int count = ask(x1, mid, x2, y2);
if (count >= 1) {
y1 = mid;
left = mid + 1;
}
if (count == 0) {
right = mid - 1;
}
}
return new int[]{x1, y1, x2, y2};
}
private int[] solve1(int n) {
int x = -1;
int left = 1, right = n;
while (left <= right) {
int mid = (left + right) >> 1;
int count = ask(1, 1, mid, n);
if (count >= 1) {
x = mid;
right = mid - 1;
}
if (count == 0) {
left = mid + 1;
}
}
left = 1;
right = n;
int y = -1;
while (left <= right) {
int mid = (left + right) >> 1;
int count = ask(1, 1, x, mid);
if (count >= 1) {
y = mid;
right = mid - 1;
}
if (count == 0) {
left = mid + 1;
}
}
return dropTopAndLeft1(x, y);
}
private int[] solve2(int n, int[] rect) {
int x = -1;
int left = 1, right = n;
while (left <= right) {
int mid = (left + right) >> 1;
int count = ask(mid, 1, n, n, rect);
if (count >= 1) {
x = mid;
left = mid + 1;
}
if (count == 0) {
right = mid - 1;
}
}
left = 1;
right = n;
int y = -1;
while (left <= right) {
int mid = (left + right) >> 1;
int count = ask(x, mid, n, n, rect);
if (count >= 1) {
y = mid;
left = mid + 1;
}
if (count == 0) {
right = mid - 1;
}
}
return dropTopAndLeft2(x, y, n, rect);
}
int[] dropTopAndLeft2(int x1, int y1, int n, int[] rect) {
int x2 = x1, y2 = y1;
int left = x1, right = n;
while (left <= right) {
int mid = (left + right) >> 1;
int count = ask(x1, y1, mid, n, rect);
if (count >= 1) {
x2 = mid;
right = mid - 1;
}
if (count == 0) {
left = mid + 1;
}
}
left = y1;
right = n;
while (left <= right) {
int mid = (left + right) >> 1;
int count = ask(x1, y1, x2, mid, rect);
if (count == 1) {
y2 = mid;
right = mid - 1;
}
if (count == 0) {
left = mid + 1;
}
}
return new int[]{x1, y1, x2, y2};
}
}
| logn | 713_B. Searching Rectangles | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws Exception {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task task = new Task();
task.solve(in, out);
out.close();
}
static class Rectangle {
int x1, y1;
int x2, y2;
}
static class Task {
/**
* BEFORE SUBMITTING!!!
* MAKE SURE IT IS RIGHT!!!!!
* LONG!!
* Check if m,n aren't misused
* Make sure the output format is right (YES/NO vs Yes/No, newlines vs spaces)
* Run with n = 1 or n = 0
* Make sure two ints aren't multiplied to get a long
*
*/
public void solve(InputReader in, PrintWriter out) {
int n = in.nextInt();
//ideas: procurar linha que os divide e procurar dentro desses sub-retangulos
// procurar até ser 1
//corner cases: se procurar até ser 1 e não verificar se tem 1 do outro lado posso chegar a 1,2...not good
// tenho que procurar 1,1
int l = 1;
int r = n;
int ans = 0;
while(r >= l) {
int mid = (r + l) / 2;
if(ask(in,out,1,1,mid, n) == 0) {
l = mid + 1;
} else {
ans = mid;
r = mid - 1;
}
}
//par 1,1
//FDS ISTO
if(ans < n && ask(in,out,ans + 1, 1,n,n) == 1) {
Rectangle r1 = find(in,out,1,1,ans,n,n);
Rectangle r2 = find(in,out,ans + 1,1,n,n,n);
System.out.printf("! %d %d %d %d %d %d %d %d\n", r1.x1, r1.y1, r1.x2, r1.y2, r2.x1, r2.y1, r2.x2, r2.y2);
} else {
l = 1;
r = n;
ans = 0;
while(r >= l) {
int mid = (r + l) / 2;
if(ask(in,out,1,1,n, mid) == 0) {
l = mid + 1;
} else {
ans = mid;
r = mid - 1;
}
}
Rectangle r1 = find(in,out,1,1,n,ans,n);
Rectangle r2 = find(in,out,1,ans + 1,n,n,n);
System.out.printf("! %d %d %d %d %d %d %d %d\n", r1.x1, r1.y1, r1.x2, r1.y2, r2.x1, r2.y1, r2.x2, r2.y2);
}
}
//HASDFDSJGHDFJKSGDFJSGJDFSGJDSFGJF
//FKING WORK
public Rectangle find(InputReader in, PrintWriter out,int x1, int y1, int x2, int y2, int n) {
Rectangle rec = new Rectangle();
int ansx1 = x1;
int ansx2 = x2;
int ansy1 = y1;
int ansy2 = y2;
int l = x1;
int r = x2;
// quero o minimo v >= x2
while(r >= l) {
int mid = (r + l) / 2;
if(ask(in,out,x1,y1,mid,y2) == 1) {
ansx2 = mid;
r = mid - 1;
} else {
l = mid + 1;
}
}
//out.printf("x2 = %d", ansx2);
r = x2;
l = x1;
// quero o maximo v <= x1
while(r >= l) {
int mid = (r + l) / 2;
if(ask(in,out,mid,y1,x2,y2) == 1) {
ansx1 = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
//out.printf("x1 = %d", ansx1);
l = y1;
r = y2;
// quero o minimo v >= y2
while(r >= l) {
int mid = (r + l) / 2;
if(ask(in,out,x1,y1,x2,mid) == 1) {
ansy2 = mid;
r = mid - 1;
} else {
l = mid + 1;
}
}
//out.printf("y2 = %d", ansy2);
r = y2;
l = y1;
// quero o maximo v <= y1
while(r >= l) {
int mid = (r + l) / 2;
if(ask(in,out,x1,mid,x2,y2) == 1) {
ansy1 = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
//out.printf("y1 = %d", ansy1);
rec.x1 = ansx1;
rec.x2 = ansx2;
rec.y1 = ansy1;
rec.y2 = ansy2;
return rec;
}
public int ask(InputReader in, PrintWriter out, int x1, int y1, int x2, int y2) {
System.out.printf("? %d %d %d %d\n",x1,y1,x2,y2);
System.out.flush();
return in.nextInt();
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
}
return null;
}
}
}
| logn | 713_B. Searching Rectangles | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws Exception {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task task = new Task();
task.solve(in, out);
out.close();
}
static class Rectangle {
int x1, y1;
int x2, y2;
}
static class Task {
/**
* BEFORE SUBMITTING!!!
* MAKE SURE IT IS RIGHT!!!!!
* LONG!!
* Check if m,n aren't misused
* Make sure the output format is right (YES/NO vs Yes/No, newlines vs spaces)
* Run with n = 1 or n = 0
* Make sure two ints aren't multiplied to get a long
*
*/
public void solve(InputReader in, PrintWriter out) {
int n = in.nextInt();
//ideas: procurar linha que os divide e procurar dentro desses sub-retangulos
// procurar até ser 1
//corner cases: se procurar até ser 1 e não verificar se tem 1 do outro lado posso chegar a 1,2...not good
// tenho que procurar 1,1
int l = 1;
int r = n;
int ans = 0;
while(r >= l) {
int mid = (r + l) / 2;
if(ask(in,out,1,1,mid, n) == 0) {
l = mid + 1;
} else {
ans = mid;
r = mid - 1;
}
}
//par 1,1
//FDS ISTO
if(ans < n && ask(in,out,ans + 1, 1,n,n) == 1) {
Rectangle r1 = find(in,out,1,1,ans,n,n);
Rectangle r2 = find(in,out,ans + 1,1,n,n,n);
System.out.printf("! %d %d %d %d %d %d %d %d\n", r1.x1, r1.y1, r1.x2, r1.y2, r2.x1, r2.y1, r2.x2, r2.y2);
} else {
l = 1;
r = n;
ans = 0;
while(r >= l) {
int mid = (r + l) / 2;
if(ask(in,out,1,1,n, mid) == 0) {
l = mid + 1;
} else {
ans = mid;
r = mid - 1;
}
}
Rectangle r1 = find(in,out,1,1,n,ans,n);
Rectangle r2 = find(in,out,1,ans + 1,n,n,n);
System.out.printf("! %d %d %d %d %d %d %d %d\n", r1.x1, r1.y1, r1.x2, r1.y2, r2.x1, r2.y1, r2.x2, r2.y2);
}
}
//HASDFDSJGHDFJKSGDFJSGJDFSGJDSFGJF
//FKING WORK
public Rectangle find(InputReader in, PrintWriter out,int x1, int y1, int x2, int y2, int n) {
Rectangle rec = new Rectangle();
int ansx1 = x1;
int ansx2 = x2;
int ansy1 = y1;
int ansy2 = y2;
int l = x1;
int r = x2;
// quero o minimo v >= x2
while(r >= l) {
int mid = (r + l) / 2;
if(ask(in,out,x1,y1,mid,y2) == 1) {
ansx2 = mid;
r = mid - 1;
} else {
l = mid + 1;
}
}
//out.printf("x2 = %d", ansx2);
r = x2;
l = x1;
// quero o maximo v <= x1
while(r >= l) {
int mid = (r + l) / 2;
if(ask(in,out,mid,y1,x2,y2) == 1) {
ansx1 = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
//out.printf("x1 = %d", ansx1);
l = y1;
r = y2;
// quero o minimo v >= y2
while(r >= l) {
int mid = (r + l) / 2;
if(ask(in,out,x1,y1,x2,mid) == 1) {
ansy2 = mid;
r = mid - 1;
} else {
l = mid + 1;
}
}
//out.printf("y2 = %d", ansy2);
r = y2;
l = y1;
// quero o maximo v <= y1
while(r >= l) {
int mid = (r + l) / 2;
if(ask(in,out,x1,mid,x2,y2) == 1) {
ansy1 = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
//out.printf("y1 = %d", ansy1);
rec.x1 = ansx1;
rec.x2 = ansx2;
rec.y1 = ansy1;
rec.y2 = ansy2;
return rec;
}
public int ask(InputReader in, PrintWriter out, int x1, int y1, int x2, int y2) {
System.out.printf("? %d %d %d %d\n",x1,y1,x2,y2);
System.out.flush();
return in.nextInt();
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
}
return null;
}
}
}
| logn | 713_B. Searching Rectangles | CODEFORCES |
import java.io.*;
import java.util.*;
public class B {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
// int X1, Y1, X2, Y2;
// int X3, Y3, X4, Y4;
// {
// X1 = 1;
// Y1 = 2;
// X2 = 3;
// Y2 = 4;
//
// X3 = 5;
// Y3 = 1;
// X4 = 5;
// Y4 = 5;
// }
int ask(int x1, int y1, int x2, int y2) throws IOException {
out.println("? " + x1 + " " + y1 + " " + x2 + " " + y2);
out.flush();
return nextInt();
}
int inside(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {
return inside(x1, x2, x3, x4) & inside(y1, y2, y3, y4);
}
int inside(int x1, int x2, int y1, int y2) {
return (x1 <= y1 && y2 <= x2) ? 1 : 0;
}
// int ask(int x1, int y1, int x2, int y2) throws IOException {
// return inside(x1, y1, x2, y2, X1, Y1, X2, Y2) + inside(x1, y1, x2, y2, X3, Y3, X4, Y4);
// }
int askFlipped(int x1, int y1, int x2, int y2) throws IOException {
return ask(y1, x1, y2, x2);
}
boolean check(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) throws IOException {
if (x1 > x2 || y1 > y2 || x3 > x4 || y3 > y4) {
return false;
}
if (Math.max(x1, x3) <= Math.min(x2, x4) && Math.max(y1, y3) <= Math.min(y2, y4)) {
return false;
}
return check(x1, y1, x2, y2) && check(x3, y3, x4, y4);
}
boolean check(int x1, int y1, int x2, int y2) throws IOException {
if (ask(x1, y1, x2, y2) != 1) {
return false;
}
if (x1 != x2) {
if (ask(x1 + 1, y1, x2, y2) != 0 || ask(x1, y1, x2 - 1, y2) != 0) {
return false;
}
}
if (y1 != y2) {
if (ask(x1, y1 + 1, x2, y2) != 0 || ask(x1, y1, x2, y2 - 1) != 0) {
return false;
}
}
return true;
}
void solve() throws IOException {
int n = nextInt();
int low = 0; // 0
int high = n; // >0
while (high - low > 1) {
int mid = (low + high) >> 1;
int ret = ask(1, 1, mid, n);
if (ret == 0) {
low = mid;
} else {
high = mid;
}
}
int minX2 = high;
low = 0; // <2
high = n; // 2
while (high - low > 1) {
int mid = (low + high) >> 1;
int ret = ask(1, 1, mid, n);
if (ret == 2) {
high = mid;
} else {
low = mid;
}
}
int maxX2 = high;
low = 1; // >0
high = n + 1; // 0
while (high - low > 1) {
int mid = (low + high) >> 1;
int ret = ask(mid, 1, n, n);
if (ret == 0) {
high = mid;
} else {
low = mid;
}
}
int maxX1 = low;
low = 1; // 2
high = n + 1; // <2
while (high - low > 1) {
int mid = (low + high) >> 1;
int ret = ask(mid, 1, n, n);
if (ret == 2) {
low = mid;
} else {
high = mid;
}
}
int minX1 = low;
// / NOW Y
low = 0; // 0
high = n; // >0
while (high - low > 1) {
int mid = (low + high) >> 1;
int ret = askFlipped(1, 1, mid, n);
if (ret == 0) {
low = mid;
} else {
high = mid;
}
}
int minY2 = high;
low = 0; // <2
high = n; // 2
while (high - low > 1) {
int mid = (low + high) >> 1;
int ret = askFlipped(1, 1, mid, n);
if (ret == 2) {
high = mid;
} else {
low = mid;
}
}
int maxY2 = high;
low = 1; // >0
high = n + 1; // 0
while (high - low > 1) {
int mid = (low + high) >> 1;
int ret = askFlipped(mid, 1, n, n);
if (ret == 0) {
high = mid;
} else {
low = mid;
}
}
int maxY1 = low;
low = 1; // 2
high = n + 1; // <2
while (high - low > 1) {
int mid = (low + high) >> 1;
int ret = askFlipped(mid, 1, n, n);
if (ret == 2) {
low = mid;
} else {
high = mid;
}
}
int minY1 = low;
int[] x1s = { minX1, maxX1 };
int[] x2s = { minX2, maxX2 };
int[] y1s = { minY1, maxY1 };
int[] y2s = { minY2, maxY2 };
for (int mask = 0; mask < 8; mask++) {
int x1 = x1s[0];
int x3 = x1s[1];
int x2 = x2s[get(mask, 0)];
int x4 = x2s[get(mask, 0) ^ 1];
int y1 = y1s[get(mask, 1)];
int y3 = y1s[get(mask, 1) ^ 1];
int y2 = y2s[get(mask, 2)];
int y4 = y2s[get(mask, 2) ^ 1];
if (check(x1, y1, x2, y2, x3, y3, x4, y4)) {
out.printf("! %d %d %d %d %d %d %d %d\n", x1, y1, x2, y2, x3, y3, x4, y4);
out.flush();
return;
}
}
}
int get(int mask, int i) {
return (mask >> i) & 1;
}
B() 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 B();
}
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 | 713_B. Searching Rectangles | CODEFORCES |
import java.io.*;
import java.math.*;
import java.util.*;
public class Main {
static int mod = (int) 1e9 + 7;
public static void main(String[] args) throws FileNotFoundException {
FasterScanner s = new FasterScanner();
int test = 1;
testloop: while (test-- > 0) {
int n = s.nextInt();
int left = 1;
int right = n;
int x[][] = new int[2][2];
int y[][] = new int[2][2];
while (left < right) {
int mid = (left + right) / 2;
query(1, mid, 1, n);
int ans = s.nextInt();
if (ans < 2) {
left = mid + 1;
} else {
right = mid;
}
}
x[0][0] = left;
left = 1;
right = n;
while (left < right) {
int mid = (left + right) / 2;
query(1, mid, 1, n);
int ans = s.nextInt();
if (ans < 1) {
left = mid + 1;
} else {
right = mid;
}
}
x[0][1] = left;
left = 1;
right = n;
while (left < right) {
int mid = (left + right + 1) / 2;
query(mid, n, 1, n);
int ans = s.nextInt();
if (ans < 2) {
right = mid - 1;
} else {
left = mid;
}
}
x[1][0] = left;
left = 1;
right = n;
while (left < right) {
int mid = (left + right + 1) / 2;
query(mid, n, 1, n);
int ans = s.nextInt();
if (ans < 1) {
right = mid - 1;
} else {
left = mid;
}
}
x[1][1] = left;
// System.out.println(Arrays.deepToString(x));
left = 1;
right = n;
while (left < right) {
int mid = (left + right) / 2;
query(1, n, 1, mid);
int ans = s.nextInt();
if (ans < 2) {
left = mid + 1;
} else {
right = mid;
}
}
y[0][0] = left;
left = 1;
right = n;
while (left < right) {
int mid = (left + right) / 2;
query(1, n, 1, mid);
int ans = s.nextInt();
if (ans < 1) {
left = mid + 1;
} else {
right = mid;
}
}
y[0][1] = left;
left = 1;
right = n;
while (left < right) {
int mid = (left + right + 1) / 2;
query(1, n, mid, n);
int ans = s.nextInt();
if (ans < 2) {
right = mid - 1;
} else {
left = mid;
}
}
y[1][0] = left;
left = 1;
right = n;
while (left < right) {
int mid = (left + right + 1) / 2;
query(1, n, mid, n);
int ans = s.nextInt();
if (ans < 1) {
right = mid - 1;
} else {
left = mid;
}
}
y[1][1] = left;
// System.out.println(Arrays.deepToString(x));
// System.out.println(Arrays.deepToString(y));
int x11 = 0, x12 = 0, y11 = 0, y12 = 0;
int x21 = 0, x22 = 0, y21 = 0, y22 = 0;
for (int x1 = 0; x1 < 2; x1++) {
x11 = x[1][x1];
x21 = x[1][1 - x1];
for (int x2 = 0; x2 < 2; x2++) {
x12 = x[0][x2];
x22 = x[0][1 - x2];
if (x11 > x12)
continue;
if (x21 > x22)
continue;
for (int y1 = 0; y1 < 2; y1++) {
y11 = y[1][y1];
y21 = y[1][1 - y1];
for (int y2 = 0; y2 < 2; y2++) {
y12 = y[0][y2];
y22 = y[0][1 - y2];
if (y11 > y12)
continue;
if (y21 > y22)
continue;
query(x11, x12, y11, y12);
int ans1 = s.nextInt();
query(x21, x22, y21, y22);
int ans2 = s.nextInt();
if (ans1 == 1 && ans2 == 1) {
System.out.println("! " + x11 + " " + y11 + " " + x12 + " " + y12 + " " + x21 + " "
+ y21 + " " + x22 + " " + y22);
System.out.flush();
break testloop;
}
}
}
}
}
}
}
public static void query(int x1, int x2, int y1, int y2) {
System.out.println("? " + x1 + " " + y1 + " " + x2 + " " + y2);
System.out.flush();
// int count = 0;
// if (x1 <= 2 && y1 <= 2 && x2 >= 2 && y2 >= 2)
// count++;
//
// if (x1 <= 3 && y1 <= 4 && x2 >= 3 && y2 >= 5)
// count++;
// System.out.println(count);
}
public static void set(int[] t, int i, int value) {
i += t.length / 2;
t[i] = value;
for (; i > 1; i >>= 1)
t[i >> 1] = Math.max(t[i], t[i ^ 1]);
}
// max[a, b]
public static int max(int[] t, int a, int b) {
int res = 0;
for (a += t.length / 2, b += t.length / 2; a <= b; a = (a + 1) >> 1, b = (b - 1) >> 1) {
if ((a & 1) != 0)
res = Math.max(res, t[a]);
if ((b & 1) == 0)
res = Math.max(res, t[b]);
}
return res;
}
public static int[] generateDivisorTable(int n) {
int[] divisor = new int[n + 1];
for (int i = 1; i <= n; i++)
divisor[i] = i;
for (int i = 2; i * i <= n; i++)
if (divisor[i] == i)
for (int j = i * i; j <= n; j += i)
if (divisor[j] == j)
divisor[j] = i;
return divisor;
}
public static long pow(long x, long n, long mod) {
long res = 1;
for (long p = x; n > 0; n >>= 1, p = (p * p) % mod) {
if ((n & 1) != 0) {
res = (res * p % mod);
}
}
return res;
}
static long gcd(long n1, long n2) {
long r;
while (n2 != 0) {
r = n1 % n2;
n1 = n2;
n2 = r;
}
return n1;
}
static class FasterScanner {
private byte[] buf = new byte[1024];
private int curChar;
private int snumChars;
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = System.in.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String 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 long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
} | logn | 713_B. Searching Rectangles | CODEFORCES |
import java.awt.*;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.List;
import static java.lang.Math.max;
import static java.lang.Math.min;
public class B implements Runnable{
private final static Random rnd = new Random();
// SOLUTION!!!
// HACK ME PLEASE IF YOU CAN!!!
// PLEASE!!!
// PLEASE!!!
// PLEASE!!!
int n;
private void solve() {
this.query = 0;
this.n = readInt();
int left1 = 0;
int l = 1, r = n;
while (l <= r) {
int m = (l + r) / 2;
int answer = getAnswer(m, 1, n, n);
if (answer < 2) {
r = m - 1;
} else {
left1 = m;
l = m + 1;
}
}
int left2 = left1;
l = left1 + 1;
r = n;
while (l <= r) {
int m = (l + r) / 2;
int answer = getAnswer(m, 1, n, n);
if (answer < 1) {
r = m - 1;
} else {
left2 = m;
l = m + 1;
}
}
int right2 = n + 1;
l = 1;
r = n;
while (l <= r) {
int m = (l + r) / 2;
int answer = getAnswer(1, 1, m, n);
if (answer < 2) {
l = m + 1;
} else {
right2 = m;
r = m - 1;
}
}
int right1 = right2;
l = 1;
r = right2 - 1;
while (l <= r) {
int m = (l + r) / 2;
int answer = getAnswer(1, 1, m, n);
if (answer < 1) {
l = m + 1;
} else {
right1 = m;
r = m - 1;
}
}
int bottom1 = 0;
l = 1;
r = n;
while (l <= r) {
int m = (l + r) / 2;
int answer = getAnswer(1, m, n, n);
if (answer < 2) {
r = m - 1;
} else {
bottom1 = m;
l = m + 1;
}
}
int bottom2 = bottom1;
l = bottom1 + 1;
r = n;
while (l <= r) {
int m = (l + r) / 2;
int answer = getAnswer(1, m, n, n);
if (answer < 1) {
r = m - 1;
} else {
bottom2 = m;
l = m + 1;
}
}
int top2 = n + 1;
l = 1;
r = n;
while (l <= r) {
int m = (l + r) / 2;
int answer = getAnswer(1, 1, n, m);
if (answer < 2) {
l = m + 1;
} else {
top2 = m;
r = m - 1;
}
}
int top1 = top2;
l = 1;
r = top2 - 1;
while (l <= r) {
int m = (l + r) / 2;
int answer = getAnswer(1, 1, n, m);
if (answer < 1) {
l = m + 1;
} else {
top1 = m;
r = m - 1;
}
}
int ansLeftRightMask = -1, ansBottomTopMask = -1;
long answerS = 2L * n * n;
for (int leftRightMask = 0; leftRightMask < 4; ++leftRightMask) {
int left = (checkBit(leftRightMask, 0) ? left1 : left2);
int right = (checkBit(leftRightMask, 1) ? right1 : right2);
for (int bottomTopMask = 0; bottomTopMask < 4; ++bottomTopMask) {
int bottom = (checkBit(bottomTopMask, 0) ? bottom1 : bottom2);
int top = (checkBit(bottomTopMask, 1) ? top1 : top2);
int curTry = getAnswer(left, bottom, right, top);
if (curTry == 1) {
long s = (right - left + 1L) * (top - bottom + 1L);
if (s < answerS) {
answerS = s;
ansLeftRightMask = leftRightMask;
ansBottomTopMask = bottomTopMask;
}
}
}
}
int left = (checkBit(ansLeftRightMask, 0) ? left1 : left2);
int right = (checkBit(ansLeftRightMask, 1) ? right1 : right2);
int bottom = (checkBit(ansBottomTopMask, 0) ? bottom1 : bottom2);
int top = (checkBit(ansBottomTopMask, 1) ? top1 : top2);
printAnswer(left, bottom, right, top,
left1 + left2 - left, bottom1 + bottom2 - bottom,
right1 + right2 - right, top1 + top2 - top);
}
private void printAnswer(int... values) {
printQuery("!", values);
}
private void printQuery(String sign, int... values) {
out.print(sign);
for (int value : values) {
out.print(" " + value);
}
out.println();
out.flush();
}
int query = 0;
final int MAX_QUERY = 200;
private int getAnswer(int left, int bottom, int right, int top) {
if (left < 1 || right > n) {
while (true);
}
if (bottom < 1 || top > n) {
throw new RuntimeException();
}
if (left > right || bottom > top) {
return 0;
}
if (query == MAX_QUERY) {
throw new RuntimeException();
}
++query;
printQuery("?", left, bottom, right, top);
int answer = readInt();
return answer;
}
/////////////////////////////////////////////////////////////////////
private final static boolean FIRST_INPUT_STRING = false;
private final static boolean MULTIPLE_TESTS = true;
private final static boolean INTERACTIVE = true;
private final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
private final static int MAX_STACK_SIZE = 128;
private final static boolean OPTIMIZE_READ_NUMBERS = false;
/////////////////////////////////////////////////////////////////////
public void run(){
try{
timeInit();
Locale.setDefault(Locale.US);
init();
if (ONLINE_JUDGE) {
solve();
} else {
do {
try {
timeInit();
solve();
time();
out.println();
} catch (NumberFormatException e) {
break;
} catch (NullPointerException e) {
if (FIRST_INPUT_STRING) break;
else throw e;
}
} while (MULTIPLE_TESTS);
}
out.close();
time();
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
/////////////////////////////////////////////////////////////////////
private BufferedReader in;
private OutputWriter out;
private StringTokenizer tok = new StringTokenizer("");
public static void main(String[] args){
new Thread(null, new B(), "", MAX_STACK_SIZE * (1L << 20)).start();
}
/////////////////////////////////////////////////////////////////////
private void init() throws FileNotFoundException{
Locale.setDefault(Locale.US);
if (INTERACTIVE || 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");
}
}
////////////////////////////////////////////////////////////////
private long timeBegin;
private void timeInit() {
this.timeBegin = System.currentTimeMillis();
}
private void time(){
long timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
private void debug(Object... objects){
if (ONLINE_JUDGE){
for (Object o: objects){
System.err.println(o.toString());
}
}
}
/////////////////////////////////////////////////////////////////////
private String delim = " ";
private String readLine() {
try {
return in.readLine();
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
private String readString() {
try {
while(!tok.hasMoreTokens()){
tok = new StringTokenizer(readLine());
}
return tok.nextToken(delim);
} catch (NullPointerException e) {
return null;
}
}
/////////////////////////////////////////////////////////////////
private final char NOT_A_SYMBOL = '\0';
private char readChar() {
try {
int intValue = in.read();
if (intValue == -1){
return NOT_A_SYMBOL;
}
return (char) intValue;
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
private char[] readCharArray() {
return readLine().toCharArray();
}
private char[][] readCharField(int rowsCount) {
char[][] field = new char[rowsCount][];
for (int row = 0; row < rowsCount; ++row) {
field[row] = readCharArray();
}
return field;
}
/////////////////////////////////////////////////////////////////
private long optimizedReadLong() {
long result = 0;
boolean started = false;
while (true) {
try {
int j = in.read();
if (-1 == j) {
if (started) return result;
throw new NumberFormatException();
}
if ('0' <= j && j <= '9') {
result = result * 10 + j - '0';
started = true;
} else if (started) {
return result;
}
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
}
private int readInt() {
if (!OPTIMIZE_READ_NUMBERS) {
return Integer.parseInt(readString());
} else {
return (int) optimizedReadLong();
}
}
private int[] readIntArray(int size) {
int[] array = new int[size];
for (int index = 0; index < size; ++index){
array[index] = readInt();
}
return array;
}
private int[] readSortedIntArray(int size) {
Integer[] array = new Integer[size];
for (int index = 0; index < size; ++index) {
array[index] = readInt();
}
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) {
sortedArray[index] = array[index];
}
return sortedArray;
}
private int[] readIntArrayWithDecrease(int size) {
int[] array = readIntArray(size);
for (int i = 0; i < size; ++i) {
array[i]--;
}
return array;
}
///////////////////////////////////////////////////////////////////
private int[][] readIntMatrix(int rowsCount, int columnsCount) {
int[][] matrix = new int[rowsCount][];
for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
matrix[rowIndex] = readIntArray(columnsCount);
}
return matrix;
}
private int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) {
int[][] matrix = new int[rowsCount][];
for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
matrix[rowIndex] = readIntArrayWithDecrease(columnsCount);
}
return matrix;
}
///////////////////////////////////////////////////////////////////
private long readLong() {
if (!OPTIMIZE_READ_NUMBERS) {
return Long.parseLong(readString());
} else {
return optimizedReadLong();
}
}
private long[] readLongArray(int size) {
long[] array = new long[size];
for (int index = 0; index < size; ++index){
array[index] = readLong();
}
return array;
}
////////////////////////////////////////////////////////////////////
private double readDouble() {
return Double.parseDouble(readString());
}
private double[] readDoubleArray(int size) {
double[] array = new double[size];
for (int index = 0; index < size; ++index){
array[index] = readDouble();
}
return array;
}
////////////////////////////////////////////////////////////////////
private BigInteger readBigInteger() {
return new BigInteger(readString());
}
private BigDecimal readBigDecimal() {
return new BigDecimal(readString());
}
/////////////////////////////////////////////////////////////////////
private Point readPoint() {
int x = readInt();
int y = readInt();
return new Point(x, y);
}
private Point[] readPointArray(int size) {
Point[] array = new Point[size];
for (int index = 0; index < size; ++index){
array[index] = readPoint();
}
return array;
}
/////////////////////////////////////////////////////////////////////
private List<Integer>[] readGraph(int vertexNumber, int edgeNumber) {
@SuppressWarnings("unchecked")
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;
}
/////////////////////////////////////////////////////////////////////
private static class IntIndexPair {
static Comparator<IntIndexPair> increaseComparator = new Comparator<B.IntIndexPair>() {
@Override
public int compare(B.IntIndexPair indexPair1, B.IntIndexPair indexPair2) {
int value1 = indexPair1.value;
int value2 = indexPair2.value;
if (value1 != value2) return value1 - value2;
int index1 = indexPair1.index;
int index2 = indexPair2.index;
return index1 - index2;
}
};
static Comparator<IntIndexPair> decreaseComparator = new Comparator<B.IntIndexPair>() {
@Override
public int compare(B.IntIndexPair indexPair1, B.IntIndexPair indexPair2) {
int value1 = indexPair1.value;
int value2 = indexPair2.value;
if (value1 != value2) return -(value1 - value2);
int index1 = indexPair1.index;
int index2 = indexPair2.index;
return index1 - index2;
}
};
int value, index;
IntIndexPair(int value, int index) {
super();
this.value = value;
this.index = index;
}
int getRealIndex() {
return index + 1;
}
}
private IntIndexPair[] readIntIndexArray(int size) {
IntIndexPair[] array = new IntIndexPair[size];
for (int index = 0; index < size; ++index) {
array[index] = new IntIndexPair(readInt(), index);
}
return array;
}
/////////////////////////////////////////////////////////////////////
private static class OutputWriter extends PrintWriter {
final int DEFAULT_PRECISION = 12;
private int precision;
private String format, formatWithSpace;
{
precision = DEFAULT_PRECISION;
format = createFormat(precision);
formatWithSpace = format + " ";
}
OutputWriter(OutputStream out) {
super(out);
}
OutputWriter(String fileName) throws FileNotFoundException {
super(fileName);
}
int getPrecision() {
return precision;
}
void setPrecision(int precision) {
precision = max(0, precision);
this.precision = precision;
format = createFormat(precision);
formatWithSpace = format + " ";
}
String createFormat(int precision){
return "%." + precision + "f";
}
@Override
public void print(double d){
printf(format, d);
}
void printWithSpace(double d){
printf(formatWithSpace, d);
}
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);
}
void printlnAll(double... d){
printAll(d);
println();
}
}
/////////////////////////////////////////////////////////////////////
private static class RuntimeIOException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = -6463830523020118289L;
RuntimeIOException(Throwable cause) {
super(cause);
}
}
/////////////////////////////////////////////////////////////////////
//////////////// Some useful constants and functions ////////////////
/////////////////////////////////////////////////////////////////////
private static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
private static final int[][] steps8 = {
{-1, 0}, {1, 0}, {0, -1}, {0, 1},
{-1, -1}, {1, 1}, {1, -1}, {-1, 1}
};
private static boolean checkCell(int row, int rowsCount, int column, int columnsCount) {
return checkIndex(row, rowsCount) && checkIndex(column, columnsCount);
}
private static boolean checkIndex(int index, int lim){
return (0 <= index && index < lim);
}
/////////////////////////////////////////////////////////////////////
private static boolean checkBit(int mask, int bit){
return (mask & (1 << bit)) != 0;
}
private static boolean checkBit(long mask, int bit){
return (mask & (1L << bit)) != 0;
}
/////////////////////////////////////////////////////////////////////
private static long getSum(int[] array) {
long sum = 0;
for (int value: array) {
sum += value;
}
return sum;
}
private static Point getMinMax(int[] array) {
int min = array[0];
int max = array[0];
for (int index = 0, size = array.length; index < size; ++index, ++index) {
int value = array[index];
if (index == size - 1) {
min = min(min, value);
max = max(max, value);
} else {
int otherValue = array[index + 1];
if (value <= otherValue) {
min = min(min, value);
max = max(max, otherValue);
} else {
min = min(min, otherValue);
max = max(max, value);
}
}
}
return new Point(min, max);
}
/////////////////////////////////////////////////////////////////////
private static int[] getPrimes(int n) {
boolean[] used = new boolean[n];
used[0] = used[1] = true;
int size = 0;
for (int i = 2; i < n; ++i) {
if (!used[i]) {
++size;
for (int j = 2 * i; j < n; j += i) {
used[j] = true;
}
}
}
int[] primes = new int[size];
for (int i = 0, cur = 0; i < n; ++i) {
if (!used[i]) {
primes[cur++] = i;
}
}
return primes;
}
/////////////////////////////////////////////////////////////////////
private static long lcm(long a, long b) {
return a / gcd(a, b) * b;
}
private static long gcd(long a, long b) {
return (a == 0 ? b : gcd(b % a, a));
}
/////////////////////////////////////////////////////////////////////
private static class IdMap<KeyType> extends HashMap<KeyType, Integer> {
/**
*
*/
private static final long serialVersionUID = -3793737771950984481L;
public IdMap() {
super();
}
int getId(KeyType key) {
Integer id = super.get(key);
if (id == null) {
super.put(key, id = size());
}
return id;
}
}
}
| logn | 713_B. Searching Rectangles | CODEFORCES |
import java.io.*;
import java.util.*;
public class Template implements Runnable {
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws FileNotFoundException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
try {
tok = new StringTokenizer(in.readLine(), " :");
} catch (Exception e) {
return null;
}
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
int[] readIntArray(int size) throws IOException {
int[] res = new int[size];
for (int i = 0; i < size; i++) {
res[i] = readInt();
}
return res;
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
<T> List<T>[] createGraphList(int size) {
List<T>[] list = new List[size];
for (int i = 0; i < size; i++) {
list[i] = new ArrayList<>();
}
return list;
}
public static void main(String[] args) {
new Thread(null, new Template(), "", 1l * 200 * 1024 * 1024).start();
}
long timeBegin, timeEnd;
void time() {
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
long memoryTotal, memoryFree;
void memory() {
memoryFree = Runtime.getRuntime().freeMemory();
System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10)
+ " KB");
}
public void run() {
try {
timeBegin = System.currentTimeMillis();
memoryTotal = Runtime.getRuntime().freeMemory();
init();
solve();
out.close();
if (System.getProperty("ONLINE_JUDGE") == null) {
time();
memory();
}
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
int fx = -1;
int sx = -1;
int fy = -1;
int sy = -1;
int query(int x1, int y1, int x2, int y2) throws IOException {
out.println("? " + x1 + " " + y1 + " " + x2 + " " + y2);
out.flush();
int res = readInt();
if (fx >= x1 && sx <= x2 && fy >= y1 && sy <= y2) res--;
return res;
}
int[] bs(int n) throws IOException {
int l = 1;
int r = n;
int lx = 0, rx = 0, ly = 0, ry = 0;
while (l <= r) {
int mid = (l + r) >> 1;
if (query(1, 1, mid, n) > 0) {
rx = mid;
r = mid - 1;
} else {
l = mid + 1;
}
}
l = 1;
r = rx;
while (l <= r) {
int mid = (l + r) >> 1;
if (query(mid, 1, rx, n) > 0) {
lx = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
l = 1;
r = n;
while (l <= r) {
int mid = (l + r) >> 1;
if (query(lx, mid, rx, n) > 0) {
ly = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
l = ly;
r = n;
while (l <= r) {
int mid = (l + r) >> 1;
if (query(lx, ly, rx, mid) > 0) {
ry = mid;
r = mid - 1;
} else {
l = mid + 1;
}
}
fx = lx;
sx = rx;
fy = ly;
sy = ry;
return new int[] {lx, ly, rx, ry};
}
void solve() throws IOException {
int n = readInt();
int[] a = bs(n);
int[] b = bs(n);
out.print("! ");
for (int i : a) out.print(i + " ");
for (int i : b) out.print(i + " ");
}
} | logn | 713_B. Searching Rectangles | CODEFORCES |
import java.util.*;
public class B {
public static void main(String[] args) {
Scanner qwe = new Scanner(System.in);
int n = qwe.nextInt();
//! x11 y11 x12 y12 x21 y21 x22 y22"
int x11 = bins(true,1,2,n,qwe,true);
int y11 = bins(true,1,2,n,qwe,false);
int x12 = bins(false,0,1,n,qwe,true);
int y12 = bins(false,0,1,n,qwe,false);
int x21 = bins(true,0,1,n,qwe,true);
int y21 = bins(true,0,1,n,qwe,false);
int x22 = bins(false,1,2,n,qwe,true);
int y22 = bins(false,1,2,n,qwe,false);
int[] xsl = {x11,x21};
int[] xsr = {x12,x22};
int[] ysl = {y11,y21};
int[] ysr = {y12,y22};
int[] ans = new int[8];
for(int xpl = 0; xpl < 2; xpl++){
for(int xpr = 0; xpr < 2; xpr++)
for(int ypl = 0; ypl < 2; ypl++){
for(int ypr = 0; ypr < 2; ypr++){
if(xsl[xpl] <= xsr[xpr] && xsl[1-xpl] <= xsr[1-xpr] && ysl[ypl] <= ysr[ypr] && ysl[1-ypl] <= ysr[1-ypr]){
System.out.printf("? %d %d %d %d",xsl[xpl],ysl[ypl],xsr[xpr],ysr[ypr]);
System.out.println();
System.out.flush();
int response1 = qwe.nextInt();
System.out.printf("? %d %d %d %d",xsl[1-xpl],ysl[1-ypl],xsr[1-xpr],ysr[1-ypr]);
System.out.println();
System.out.flush();
int response2 = qwe.nextInt();
if(response1 == 1 && response2 == 1){
ans = new int[]{xsl[xpl],ysl[ypl],xsr[xpr],ysr[ypr],xsl[1-xpl],ysl[1-ypl],xsr[1-xpr],ysr[1-ypr]};
}
}
}
}
}
System.out.printf("! %d %d %d %d %d %d %d %d",ans[0],ans[1],ans[2],ans[3],ans[4],ans[5],ans[6],ans[7]);
System.out.println();
System.out.flush();
qwe.close();
}
static int bins(boolean leftbound, int small, int big, int n, Scanner qwe, boolean isx){
int min = 0;
int max = n;
if(leftbound){
min++;
max++;
}
int y1 = 1;
int y2 = n;
int x1 = 1;
int x2 = n;
//"? x1 y1 x2 y2"
while(min+1 < max){
int med = (min+max)/2;
if(isx){
if(!leftbound) x2 = med;
else x1 = med;
}
else{
if(!leftbound) y2 = med;
else y1 = med;
}
System.out.printf("? %d %d %d %d",x1,y1,x2,y2);
System.out.println();
System.out.flush();
int response = qwe.nextInt();
if(leftbound){
if(response >= big) min = med;
else max= med;
}
else{
if(response < big){
min = med;
}
else{
max = med;
}
}
}
if(leftbound) max--;
return max;
}
} | logn | 713_B. Searching Rectangles | CODEFORCES |
import java.io.*;
import java.util.*;
import java.util.function.IntPredicate;
import static java.lang.Math.*;
public class Main {
FastScanner in;
PrintWriter out;
static final String FILE = "";
public static final int TEST = 0;
class Interact {
Rect a, b;
public Interact(int x11, int y11, int x12, int y12, int x21, int y21, int x22, int y22) {
a = new Rect(x11, y11, x12, y12);
b = new Rect(x21, y21, x22, y22);
}
int query(int x1, int y1, int x2, int y2) {
int ans = 0;
if (x1 <= a.x1 && x2 >= a.x2 && y1 <= a.y1 && y2 >= a.y2)
ans++;
if (x1 <= b.x1 && x2 >= b.x2 && y1 <= b.y1 && y2 >= b.y2)
ans++;
return ans;
}
}
Interact interact;
class Rect {
int x1, y1, x2, y2;
public Rect() {
}
public Rect(int x1, int y1, int x2, int y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
@Override
public String toString() {
return x1 + " " + y1 + " " + x2 + " " + y2;
}
}
int calls;
int query(int x1, int y1, int x2, int y2, Rect rect) {
calls++;
if (calls >= 190)
throw new RuntimeException();
if (TEST == 0) {
out.println("? " + x1 + " " + y1 + " " + x2 + " " + y2);
out.flush();
int ans = in.nextInt();
if (x1 <= rect.x1 && x2 >= rect.x2 && y1 <= rect.y1 && y2 >= rect.y2)
ans--;
return ans;
} else {
int ans = interact.query(x1, y1, x2, y2);
if (x1 <= rect.x1 && x2 >= rect.x2 && y1 <= rect.y1 && y2 >= rect.y2)
ans--;
return ans;
}
}
static int binarySearchFirstTrue(IntPredicate predicate, int fromInclusive, int toInclusive) {
int a = fromInclusive, b = toInclusive;
while (a != b) {
int la = a, lb = b;
int mid = (a + b) / 2;
if (predicate.test(mid))
b = mid;
else
a = mid;
if (la == a && lb == b) {
if (predicate.test(a))
b = a;
else
a = b;
}
}
return a;
}
static int binarySearchLastTrue(IntPredicate predicate, int fromInclusive, int toInclusive) {
int a = fromInclusive, b = toInclusive;
while (a != b) {
int la = a, lb = b;
int mid = (a + b) / 2;
if (predicate.test(mid))
a = mid;
else
b = mid;
if (la == a && lb == b) {
if (predicate.test(b))
a = b;
else
b = a;
}
}
return a;
}
static Rect rect;
void test() {
Random random = new Random(13);
for (int test = 0; test < 1000; test++) {
}
}
void solve() {
rect = new Rect();
if (TEST == 0) {
int n = in.nextInt();
List<Rect> list = new ArrayList<>();
for (int r = 0; r < 2; r++) {
int x2 = binarySearchFirstTrue(i -> query(1, 1, i, n, rect) >= 1, 1, n);
int x1 = binarySearchLastTrue(i -> query(i, 1, x2, n, rect) >= 1, 1, x2);
int y2 = binarySearchFirstTrue(i -> query(x1, 1, x2, i, rect) >= 1, 1, n);
int y1 = binarySearchLastTrue(i -> query(x1, i, x2, y2, rect) >= 1, 1, y2);
rect = new Rect(x1, y1, x2, y2);
list.add(rect);
}
out.println("! " + list.get(0) + " " + list.get(1));
out.flush();
} else {
int n = in.nextInt();
int x11 = in.nextInt(), y11 = in.nextInt(), x12 = in.nextInt(), y12 = in.nextInt();
int x21 = in.nextInt(), y21 = in.nextInt(), x22 = in.nextInt(), y22 = in.nextInt();
interact = new Interact(x11, y11, x12, y12, x21, y21, x22, y22);
List<Rect> list = new ArrayList<>();
for (int r = 0; r < 2; r++) {
int x2 = binarySearchFirstTrue(i -> query(1, 1, i, n, rect) >= 1, 1, n);
int x1 = binarySearchLastTrue(i -> query(i, 1, x2, n, rect) >= 1, 1, x2);
int y2 = binarySearchFirstTrue(i -> query(x1, 1, x2, i, rect) >= 1, 1, n);
int y1 = binarySearchLastTrue(i -> query(x1, i, x2, y2, rect) >= 1, 1, y2);
rect = new Rect(x1, y1, x2, y2);
list.add(rect);
}
out.println("! " + list.get(0) + " " + list.get(1));
out.flush();
}
}
public void run() {
if (FILE.equals("")) {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
} else {
try {
in = new FastScanner(new FileInputStream(FILE +
".in"));
out = new PrintWriter(new FileOutputStream(FILE +
".out"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
solve();
out.close();
}
public static void main(String[] args) {
(new Main()).run();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public float nextFloat() {
return Float.parseFloat(next());
}
}
} | logn | 713_B. Searching Rectangles | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.PrintStream;
import java.io.BufferedWriter;
import java.util.Random;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Jialin Ouyang ([email protected])
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
QuickScanner in = new QuickScanner(inputStream);
QuickWriter out = new QuickWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
static boolean LOCAL = false;
static int TEST_CASE = 10000;
QuickScanner in;
QuickWriter out;
int n;
Server server;
public void solve(int testNumber, QuickScanner in, QuickWriter out) {
this.in = in;
this.out = out;
n = LOCAL ? 1 << 16 : in.nextInt();
server = new Server();
for (int remCases = LOCAL ? TEST_CASE : 1; remCases > 0; --remCases) {
server.init(n);
Rect[] rects = split(0);
if (rects == null) {
rects = split(1);
}
rects[0] = shrink(rects[0]);
rects[1] = shrink(rects[1]);
server.answer(rects[0], rects[1]);
}
}
Rect[] split(int dim) {
int lower = 1, upper = n - 1, res = 0;
Rect fullRect = new Rect(1, 1, n, n);
while (lower <= upper) {
int medium = (lower + upper) >> 1;
if (server.ask(fullRect.update(1, dim, medium)) == 0) {
res = medium;
lower = medium + 1;
} else {
upper = medium - 1;
}
}
Rect[] rects = new Rect[]{
fullRect.update(1, dim, res + 1),
fullRect.update(0, dim, res + 2)};
return server.ask(rects[0]) == 1
&& server.ask(rects[1]) == 1
? rects : null;
}
Rect shrink(Rect rect) {
rect = shrink(rect, 0);
rect = shrink(rect, 1);
return rect;
}
Rect shrink(Rect rect, int dim) {
int lower, upper, res;
// lower
lower = rect.getValue(0, dim) + 1;
upper = rect.getValue(1, dim);
res = lower - 1;
while (lower <= upper) {
int medium = (lower + upper) >> 1;
if (server.ask(rect.update(0, dim, medium)) == 1) {
res = medium;
lower = medium + 1;
} else {
upper = medium - 1;
}
}
rect = rect.update(0, dim, res);
// upper
lower = rect.getValue(0, dim);
upper = rect.getValue(1, dim) - 1;
res = upper + 1;
while (lower <= upper) {
int medium = (lower + upper) >> 1;
if (server.ask(rect.update(1, dim, medium)) == 1) {
res = medium;
upper = medium - 1;
} else {
lower = medium + 1;
}
}
return rect.update(1, dim, res);
}
class Server {
Rect rect1;
Rect rect2;
Server() {
rect1 = new Rect();
rect2 = new Rect();
}
void init(int n) {
if (LOCAL) {
do {
rect1.initRandom(n);
rect2.initRandom(n);
} while (!rect1.valid(rect2));
//rect1 = new Rect(2, 2, 2, 2);
//rect2 = new Rect(3, 4, 3, 5);
}
}
int ask(Rect rect) {
out.print("? ");
rect.print();
out.println();
out.flush();
if (LOCAL) {
return (rect1.in(rect) ? 1 : 0)
+ (rect2.in(rect) ? 1 : 0);
} else {
return in.nextInt();
}
}
void answer(Rect rect1, Rect rect2) {
out.print("! ");
rect1.print();
out.print(' ');
rect2.print();
out.println();
out.flush();
if (LOCAL) {
if ((rect1.equals(this.rect1) && rect2.equals(this.rect2))
|| (rect2.equals(this.rect1) && rect1.equals(this.rect2))) {
System.out.println("AC!");
} else {
System.out.println("WA!");
throw new IllegalArgumentException();
}
}
}
}
class Rect {
final Random random = new Random();
int x1;
int y1;
int x2;
int y2;
Rect() {
}
Rect(int x1, int y1, int x2, int y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
void initRandom(int n) {
x1 = random.nextInt(n);
x2 = random.nextInt(n - x1) + x1 + 1;
++x1;
y1 = random.nextInt(n);
y2 = random.nextInt(n - y1) + y1 + 1;
++y1;
}
int getValue(int idx1, int idx2) {
switch ((idx1 << 1) | idx2) {
case 0:
return x1;
case 1:
return y1;
case 2:
return x2;
case 3:
return y2;
}
throw new IllegalArgumentException();
}
Rect update(int idx1, int idx2, int value) {
switch ((idx1 << 1) | idx2) {
case 0:
return new Rect(value, y1, x2, y2);
case 1:
return new Rect(x1, value, x2, y2);
case 2:
return new Rect(x1, y1, value, y2);
case 3:
return new Rect(x1, y1, x2, value);
}
return null;
}
boolean valid(Rect o) {
if (x2 < o.x1) return true;
if (y2 < o.y1) return true;
if (o.x2 < x1) return true;
if (o.y2 < y1) return true;
return false;
}
boolean in(Rect o) {
return o.x1 <= x1 && x2 <= o.x2
&& o.y1 <= y1 && y2 <= o.y2;
}
boolean equals(Rect o) {
return x1 == o.x1 && y1 == o.y1
&& x2 == o.x2 && y2 == o.y2;
}
void print() {
out.printf("%d %d %d %d", x1, y1, x2, y2);
}
}
}
static class QuickScanner {
private static final int BUFFER_SIZE = 1024;
private InputStream stream;
private byte[] buffer;
private int currentPostion;
private int numberOfChars;
public QuickScanner(InputStream stream) {
this.stream = stream;
this.buffer = new byte[BUFFER_SIZE];
this.currentPostion = 0;
this.numberOfChars = 0;
}
public int nextInt() {
int c = nextNonSpaceChar();
boolean positive = true;
if (c == '-') {
positive = false;
c = nextChar();
}
int res = 0;
do {
if (c < '0' || '9' < c) throw new RuntimeException();
res = res * 10 + c - '0';
c = nextChar();
} while (!isSpaceChar(c));
return positive ? res : -res;
}
public int nextNonSpaceChar() {
int res = nextChar();
for (; isSpaceChar(res) || res < 0; res = nextChar()) ;
return res;
}
public int nextChar() {
if (numberOfChars == -1) {
throw new RuntimeException();
}
if (currentPostion >= numberOfChars) {
currentPostion = 0;
try {
numberOfChars = stream.read(buffer);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (numberOfChars <= 0) {
return -1;
}
}
return buffer[currentPostion++];
}
public boolean isSpaceChar(int c) {
return c == ' '
|| c == '\n'
|| c == '\r'
|| c == '\t'
|| c < 0;
}
}
static class QuickWriter {
private final PrintWriter writer;
public QuickWriter(OutputStream outputStream) {
this.writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public QuickWriter(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.print('\n');
}
public void printf(String format, Object... objects) {
writer.printf(format, objects);
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
}
| logn | 713_B. Searching Rectangles | CODEFORCES |
//make sure to make new file!
import java.io.*;
import java.util.*;
public class B713{
public static BufferedReader f;
public static PrintWriter out;
public static void main(String[] args)throws IOException{
f = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
int n = Integer.parseInt(f.readLine());
int l;
int r;
int mid;
int ans;
l = 1;
r = n;
ans = -1;
//see if you can draw vertical line between them
while(l <= r){
mid = l + (r-l)/2;
if(mid == n) break;
int il = query(1,1,n,mid);
int ir = query(1,mid+1,n,n);
if(il == 1 && ir == 1){
ans = mid;
break;
}
if(il > ir){
r = mid-1;
} else {
l = mid+1;
}
}
int x11 = -1;
int y11 = -1;
int x12 = -1;
int y12 = -1;
int x21 = -1;
int y21 = -1;
int x22 = -1;
int y22 = -1;
if(ans == -1){
//find horizontal line
l = 1;
r = n;
ans = -1;
while(l <= r){
mid = l + (r-l)/2;
int il = query(1,1,mid,n);
int ir = query(mid+1,1,n,n);
if(il == 1 && ir == 1){
ans = mid;
break;
}
if(il > ir){
r = mid-1;
} else {
l = mid+1;
}
}
int bar = ans;
//find top line of top block
l = 1;
r = bar;
ans = -1;
while(l <= r){
mid = l + (r-l)/2;
int i = query(mid,1,bar,n);
if(i == 1){
ans = mid;
l = mid+1;
} else {
r = mid-1;
}
}
x11 = ans;
//find bottom line of top block
l = 1;
r = bar;
ans = -1;
while(l <= r){
mid = l + (r-l)/2;
int i = query(1,1,mid,n);
if(i == 1){
ans = mid;
r = mid-1;
} else {
l = mid+1;
}
}
x12 = ans;
//find left of top block
l = 1;
r = n;
ans = -1;
while(l <= r){
mid = l + (r-l)/2;
int i = query(1,mid,bar,n);
if(i == 1){
ans = mid;
l = mid+1;
} else {
r = mid-1;
}
}
y11 = ans;
//find right of top block
l = 1;
r = n;
ans = -1;
while(l <= r){
mid = l + (r-l)/2;
int i = query(1,1,bar,mid);
if(i == 1){
ans = mid;
r = mid-1;
} else {
l = mid+1;
}
}
y12 = ans;
//find top line of bottom block
l = bar+1;
r = n;
ans = -1;
while(l <= r){
mid = l + (r-l)/2;
int i = query(mid,1,n,n);
if(i == 1){
ans = mid;
l = mid+1;
} else {
r = mid-1;
}
}
x21 = ans;
//find bottom line of bottom block
l = bar+1;
r = n;
ans = -1;
while(l <= r){
mid = l + (r-l)/2;
int i = query(bar+1,1,mid,n);
if(i == 1){
ans = mid;
r = mid-1;
} else {
l = mid+1;
}
}
x22 = ans;
//find left of bottom block
l = 1;
r = n;
ans = -1;
while(l <= r){
mid = l + (r-l)/2;
int i = query(bar+1,mid,n,n);
if(i == 1){
ans = mid;
l = mid+1;
} else {
r = mid-1;
}
}
y21 = ans;
//find right of bottom block
l = 1;
r = n;
ans = -1;
while(l <= r){
mid = l + (r-l)/2;
int i = query(bar+1,1,n,mid);
if(i == 1){
ans = mid;
r = mid-1;
} else {
l = mid+1;
}
}
y22 = ans;
} else {
//ans is the vertical line between
int bar = ans;
//find left line of left block
l = 1;
r = bar;
ans = -1;
while(l <= r){
mid = l + (r-l)/2;
int i = query(1,mid,n,bar);
if(i == 1){
ans = mid;
l = mid+1;
} else {
r = mid-1;
}
}
y11 = ans;
//find right line of left block
l = 1;
r = bar;
ans = -1;
while(l <= r){
mid = l + (r-l)/2;
int i = query(1,1,n,mid);
if(i == 1){
ans = mid;
r = mid-1;
} else {
l = mid+1;
}
}
y12 = ans;
//find top of left block
l = 1;
r = n;
ans = -1;
while(l <= r){
mid = l + (r-l)/2;
int i = query(mid,1,n,bar);
if(i == 1){
ans = mid;
l = mid+1;
} else {
r = mid-1;
}
}
x11 = ans;
//find bottom of left block
l = 1;
r = n;
ans = -1;
while(l <= r){
mid = l + (r-l)/2;
int i = query(1,1,mid,bar);
if(i == 1){
ans = mid;
r = mid-1;
} else {
l = mid+1;
}
}
x12 = ans;
//find left line of right block
l = bar+1;
r = n;
ans = -1;
while(l <= r){
mid = l + (r-l)/2;
int i = query(1,mid,n,n);
if(i == 1){
ans = mid;
l = mid+1;
} else {
r = mid-1;
}
}
y21 = ans;
//find right line of right block
l = bar+1;
r = n;
ans = -1;
while(l <= r){
mid = l + (r-l)/2;
int i = query(1,bar+1,n,mid);
if(i == 1){
ans = mid;
r = mid-1;
} else {
l = mid+1;
}
}
y22 = ans;
//find top of right block
l = 1;
r = n;
ans = -1;
while(l <= r){
mid = l + (r-l)/2;
int i = query(mid,bar+1,n,n);
if(i == 1){
ans = mid;
l = mid+1;
} else {
r = mid-1;
}
}
x21 = ans;
//find bottom of right block
l = 1;
r = n;
ans = -1;
while(l <= r){
mid = l + (r-l)/2;
int i = query(1,bar+1,mid,n);
if(i == 1){
ans = mid;
r = mid-1;
} else {
l = mid+1;
}
}
x22 = ans;
}
out.println("! " + x11 + " " + y11 + " " + x12 + " " + y12 + " " + x21 + " " + y21 + " " + x22 + " " + y22);
out.close();
}
public static int query(int a,int b, int c, int d)throws IOException{
out.println("? " + a + " " + b + " " + c + " " + d);
out.flush();
return Integer.parseInt(f.readLine());
}
} | logn | 713_B. Searching Rectangles | CODEFORCES |
//package round371;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class BT {
Scanner in;
PrintWriter out;
String INPUT = "";
int q(int r1, int c1, int r2, int c2)
{
out.printf("? %d %d %d %d\n", r1+1, c1+1, r2+1, c2+1);
out.flush();
return ni();
}
void e(int r1, int c1, int r2, int c2, int r3, int c3, int r4, int c4)
{
out.printf("! %d %d %d %d %d %d %d %d\n",
r1+1, c1+1, r2+1, c2+1,
r3+1, c3+1, r4+1, c4+1
);
out.flush();
}
void solve()
{
int n = ni();
int cu = -1, cv = -1;
{
int low = -1, high = n-1;
while(high - low > 1){
int h = high+low>>1;
if(q(0, 0, n-1, h) >= 2){
high = h;
}else{
low = h;
}
}
cu = high;
}
{
int low = -1, high = n-1;
while(high - low > 1){
int h = high+low>>1;
if(q(0, 0, n-1, h) >= 1){
high = h;
}else{
low = h;
}
}
cv = high;
}
int du = -1, dv = -1;
{
int low = 0, high = n;
while(high - low > 1){
int h = high+low>>1;
if(q(0, h, n-1, n-1) >= 2){
low = h;
}else{
high = h;
}
}
du = low;
}
{
int low = 0, high = n;
while(high - low > 1){
int h = high+low>>1;
if(q(0, h, n-1, n-1) >= 1){
low = h;
}else{
high = h;
}
}
dv= low;
}
int eu = -1, ev = -1;
{
int low = -1, high = n-1;
while(high - low > 1){
int h = high+low>>1;
if(q(0, 0, h, n-1) >= 2){
high = h;
}else{
low = h;
}
}
eu = high;
}
{
int low = -1, high = n-1;
while(high - low > 1){
int h = high+low>>1;
if(q(0, 0, h, n-1) >= 1){
high = h;
}else{
low = h;
}
}
ev = high;
}
int fu = -1, fv = -1;
{
int low = 0, high = n;
while(high - low > 1){
int h = high+low>>1;
if(q(h, 0, n-1, n-1) >= 2){
low = h;
}else{
high = h;
}
}
fu = low;
}
{
int low = 0, high = n;
while(high - low > 1){
int h = high+low>>1;
if(q(h, 0, n-1, n-1) >= 1){
low = h;
}else{
high = h;
}
}
fv= low;
}
// cv <= cu
// du <= dv
int[][][] canc = {
{{du, cu}, {dv, cv}},
{{du, cv}, {dv, cu}}
};
int[][][] canr = {
{{fu, eu}, {fv, ev}},
{{fu, ev}, {fv, eu}}
};
for(int[][] cr : canr){
if(cr[0][0] > cr[0][1])continue;
if(cr[1][0] > cr[1][1])continue;
for(int[][] cc : canc){
if(cc[0][0] > cc[0][1])continue;
if(cc[1][0] > cc[1][1])continue;
for(int z = 0;z < 2;z++){
if(
q(cr[0][0], cc[0^z][0], cr[0][1], cc[0^z][1]) == 1 &&
q(cr[1][0], cc[1^z][0], cr[1][1], cc[1^z][1]) == 1){
e(cr[0][0], cc[0^z][0], cr[0][1], cc[0^z][1], cr[1][0], cc[1^z][0], cr[1][1], cc[1^z][1]);
return;
}
}
}
}
throw new RuntimeException();
}
void run() throws Exception
{
in = oj ? new Scanner(System.in) : new Scanner(INPUT);
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 BT().run();
}
int ni() { return Integer.parseInt(in.next()); }
long nl() { return Long.parseLong(in.next()); }
double nd() { return Double.parseDouble(in.next()); }
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| logn | 713_B. Searching Rectangles | CODEFORCES |
import javax.crypto.AEADBadTagException;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author AlexFetisov
*/
public class TaskB_AF {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB_cf371 solver = new TaskB_cf371();
solver.solve(1, in, out);
out.close();
}
static class TaskB_cf371 {
List<Rectangle> rects;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int xLeft = 1, xRight = n;
int xSeparate = -1;
while (xLeft <= xRight) {
int e = (xLeft + xRight) / 2;
int t = makeRequest(in, out, 1, 1, e, n);
if (t == 1) {
xSeparate = e;
xRight = e - 1;
} else if (t == 0) {
xLeft = e + 1;
} else {
xRight = e - 1;
}
}
rects = new ArrayList<Rectangle>();
if (xSeparate != -1 && makeRequest(in, out, xSeparate + 1, 1, n, n) == 1) {
detectRectangle(in, out, 1, 1, xSeparate, n);
detectRectangle(in, out, xSeparate + 1, 1, n, n);
out.print("! ");
for (Rectangle r : rects) {
out.print(r.toString() + " ");
}
out.println();
out.flush();
return;
}
int yLeft = 1, yRight = n;
int ySeparate = -1;
while (yLeft <= yRight) {
int e = (yLeft + yRight) / 2;
int t = makeRequest(in, out, 1, 1, n, e);
if (t == 1) {
ySeparate = e;
yRight = e - 1;
} else if (t == 0) {
yLeft = e + 1;
} else {
yRight = e - 1;
}
}
if (ySeparate != -1) {
detectRectangle(in, out, 1, 1, n, ySeparate);
detectRectangle(in, out, 1, ySeparate + 1, n, n);
out.print("! ");
for (Rectangle r : rects) {
out.print(r.toString() + " ");
}
out.println();
out.flush();
return;
}
throw new AssertionError("!");
}
private void detectRectangle(InputReader in, PrintWriter out, int xMin, int yMin, int xMax, int yMax) {
int xLeft = -1, xRight = -1, yLeft = -1, yRight = -1;
int left = xMin, right = xMax;
while (left <= right) {
int e = (left + right) / 2;
if (makeRequest(in, out, xMin, yMin, e, yMax) == 1) {
xRight = e;
right = e - 1;
} else {
left = e + 1;
}
}
left = xMin;
right = xRight;
while (left <= right) {
int e = (left + right) / 2;
if (makeRequest(in, out, e, yMin, xRight, yMax) == 1) {
xLeft = e;
left = e + 1;
} else {
right = e - 1;
}
}
left = yMin;
right = yMax;
while (left <= right) {
int e = (left + right) / 2;
if (makeRequest(in, out, xLeft, yMin, xRight, e) == 1) {
yRight = e;
right = e - 1;
} else {
left = e + 1;
}
}
left = yMin;
right = yRight;
while (left <= right) {
int e = (left + right) / 2;
if (makeRequest(in, out, xLeft, e, xRight, yRight) == 1) {
yLeft = e;
left = e + 1;
} else {
right = e - 1;
}
}
rects.add(new Rectangle(xLeft, yLeft, xRight, yRight));
}
private int makeRequest(InputReader in, PrintWriter out, int x1, int y1, int x2, int y2) {
out.print("? " + x1 + " " + y1 + " " + x2 + " " + y2);
out.println();
out.flush();
return in.nextInt();
}
class Rectangle {
int x1;
int x2;
int y1;
int y2;
public Rectangle(int x1, int y1, int x2, int y2) {
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
}
public String toString() {
StringBuilder b = new StringBuilder("");
b.append(x1).append(' ');
b.append(y1).append(' ');
b.append(x2).append(' ');
b.append(y2);
return b.toString();
}
}
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer stt;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
return null;
}
}
public String nextString() {
while (stt == null || !stt.hasMoreTokens()) {
stt = new StringTokenizer(nextLine());
}
return stt.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextString());
}
}
}
| logn | 713_B. Searching Rectangles | 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
*/
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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
int[][] dr = new int[][]{{0, 0, 0, -1}, {0, 0, -1, 0}, {0, 1, 0, 0}, {1, 0, 0, 0}};
int[][] dd = new int[][]{{1, 3}, {0, 2}, {1, 3}, {0, 2}};
PrintWriter out;
InputReader in;
int[] re1;
int[] re2;
int N;
public void solve(int testNumber, InputReader in, PrintWriter out) {
N = in.nextInt();
int r[] = new int[]{1, 1, N, N};
this.out = out;
this.in = in;
re1 = new int[]{1, 1, 1, 1};
re2 = new int[]{2, 1, 2, 1};
//probuje najpierw lewa sciane
int fr[] = moveSide(r, dr[2], dd[2]);
int sr[] = subtract(r, fr);
if (!validSeparation(sr)) {
fr = moveSide(r, dr[1], dd[1]);
sr = subtract(r, fr);
}
fr = boundary(fr);
sr = boundary(sr);
out.println(String.format("! %d %d %d %d %d %d %d %d", fr[0], fr[1], fr[2], fr[3], sr[0], sr[1], sr[2], sr[3]));
}
private boolean validSeparation(int[] sr) {
if (!validRectangle(sr)) return false;
out.println(String.format("? %d %d %d %d", sr[0], sr[1], sr[2], sr[3]));
out.flush();
return in.nextInt() == 1;
}
private boolean validRectangle(int[] sr) {
for (int i = 0; i < 4; i++) {
if (sr[i] < 1 || sr[i] > N) return false;
}
return true;
}
private int[] boundary(int[] r) {
for (int d = 0; d < 4; d++) {
r = moveSide(r, dr[d], dd[d]);
}
return r;
}
private int[] subtract(final int[] r, final int[] fr) {
if (r[1] == fr[1]) {
//jesli lewy dolny taki sam to ucieto horyzontalnie od gory
return new int[]{fr[2] + 1, r[1], r[2], r[3]};
}
//else ucieto wertykalnie od lewej
return new int[]{r[0], r[1], r[2], fr[1] - 1};
}
private int[] moveSide(final int[] rect, final int[] factors, final int[] widths) {
int width = Math.abs(rect[widths[0]] - rect[widths[1]]);
int lo = -1, hi = width + 1;
while (lo + 1 < hi) {
int m = lo + (hi - lo) / 2;
int qr[] = new int[4];
for (int d = 0; d < 4; d++) qr[d] = rect[d] + factors[d] * m;
int ans = query(qr);
if (ans != 0) {
lo = m;
} else {
hi = m;
}
}
int ans_rect[] = new int[4];
for (int d = 0; d < 4; d++) ans_rect[d] = rect[d] + factors[d] * lo;
return ans_rect;
}
private int query(final int[] qr) {
int ans = 0;
out.println(String.format("? %d %d %d %d", qr[0], qr[1], qr[2], qr[3]));
out.flush();
ans = in.nextInt();
// if (contains(qr, re1)) ans++;
// if (contains(qr, re2)) ans++;
return ans;
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| logn | 713_B. Searching Rectangles | CODEFORCES |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class Solution {
static BufferedReader br;
static int[] ans;
public static void main(String[] args) throws Exception{
br = new BufferedReader(new InputStreamReader(System.in));
ans = new int[8];
int n = Integer.parseInt(br.readLine());
System.out.println("?"+"1 1 "+n+" "+n);
System.out.flush();
int q = Integer.parseInt(br.readLine());
cut(n);
System.out.print("! ");
for(int i=0 ; i<8 ; i++) System.out.print(ans[i]+" ");
System.out.println();
}
public static void solve(int x1, int y1, int x2, int y2, int t) throws Exception{
int l=x1, r=x2;
int xx1,yy1,xx2,yy2;
while(l<r){
int mid = (l+r)/2;
if(query(x1,y1,mid,y2)==1) r=mid;
else l=mid+1;
}
xx2 = l;
l=x1; r=x2;
while(r>l){
int mid = (l+r+1)/2;
if(query(mid,y1,x2,y2)==1) l = mid;
else r=mid-1;
}
xx1 = l;
l=y1; r=y2;
while(l<r){
int mid = (l+r)/2;
if(query(x1,y1,x2,mid)==1) r=mid;
else l=mid+1;
}
yy2=l;
l=y1;r=y2;
while(r>l){
int mid = (l+r+1)/2;
if(query(x1,mid,x2,y2)==1) l=mid;
else r=mid-1;
}
yy1 = l;
ans[t] = xx1; ans[t+1] = yy1 ; ans[t+2] = xx2; ans[t+3] = yy2;
// System.out.println("!"+xx1+" "+yy1+" "+xx2+" "+yy2);
}
public static void cut(int n) throws Exception{
int l=1, r=n;
while(l<r){
int mid = (l+r)/2;
if(query(1,1,n,mid)==0) l=mid+1;
else r = mid;
}
if(query(1,1,n,l)==1 && query(1,l+1,n,n)==1){
solve(1,1,n,l,0);
solve(1,l+1,n,n,4);
return;
}
l=1;r=n;
while(l<r){
int mid = (l+r)/2;
if(query(1,1,mid,n)==0) l=mid+1;
else r=mid;
}
solve(1,1,l,n,0);
solve(l+1,1,n,n,4);
}
public static int query(int x1, int y1, int x2, int y2) throws Exception{
System.out.println("?"+x1+" "+y1+" "+x2+" "+y2);
System.out.flush();
int q = Integer.parseInt(br.readLine());
return q;
}
} | logn | 713_B. Searching Rectangles | 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 Egor Kulikov ([email protected])
*/
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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
int stage;
int n;
OutputWriter out;
InputReader in;
void query(int end) {
switch (stage) {
case 0:
out.printLine('?', 1, 1, end, n);
break;
case 1:
out.printLine('?', 1, 1, n, end);
break;
case 2:
out.printLine('?', n + 1 - end, 1, n, n);
break;
case 3:
out.printLine('?', 1, n + 1 - end, n, n);
break;
}
out.flush();
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
this.out = out = new OutputWriter(System.out);
this.in = in = new InputReader(System.in);
n = in.readInt();
int[] endx = new int[2];
int[] endy = new int[2];
int[] stx = new int[2];
int[] sty = new int[2];
find(endx);
stage++;
find(endy);
stage++;
find(stx);
for (int i = 0; i < 2; i++) {
stx[i] = n + 1 - stx[i];
}
stage++;
find(sty);
for (int i = 0; i < 2; i++) {
sty[i] = n + 1 - sty[i];
}
for (int i = 0; i < 8; i++) {
if (stx[i & 1] > endx[i >> 2 & 1] || sty[i >> 1 & 1] > endy[0]) {
continue;
}
if (stx[1 - (i & 1)] > endx[1 - (i >> 2 & 1)] || sty[1 - (i >> 1 & 1)] > endy[1]) {
continue;
}
out.printLine('?', stx[i & 1], sty[i >> 1 & 1], endx[i >> 2 & 1], endy[0]);
out.flush();
if (in.readInt() == 0) {
continue;
}
out.printLine('?', stx[1 - (i & 1)], sty[1 - (i >> 1 & 1)], endx[1 - (i >> 2 & 1)], endy[1]);
out.flush();
if (in.readInt() != 0) {
out.printLine("!", stx[i & 1], sty[i >> 1 & 1], endx[i >> 2 & 1], endy[0], stx[1 - (i & 1)],
sty[1 - (i >> 1 & 1)], endx[1 - (i >> 2 & 1)], endy[1]);
out.flush();
return;
}
}
}
private void find(int[] endx) {
int left = 1;
int right = n;
while (left < right) {
int middle = (left + right) >> 1;
query(middle);
if (in.readInt() == 2) {
right = middle;
} else {
left = middle + 1;
}
}
endx[0] = left;
left = 0;
right--;
while (left < right) {
int middle = (left + right + 1) >> 1;
query(middle);
if (in.readInt() == 0) {
left = middle;
} else {
right = middle - 1;
}
}
endx[1] = left + 1;
}
}
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 printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
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 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 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);
}
}
}
| logn | 713_B. Searching Rectangles | CODEFORCES |
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
public class DTask {
static Scanner in;
static int[] first = new int[4];
static int[] second = new int[4];
static PrintWriter out;
static int n;
public static void main(String[] args) throws IOException {
in = new Scanner(System.in);
out = new PrintWriter(System.out);
n = in.nextInt() + 1;
first = new int[]{0, 0, n, n};
second = new int[]{0, 0, n, n};
for (int i = 0; i < first.length; i++) {
boolean inc = i < 2;
search(first, i, inc, false);
if (!inc) {
first[i] += 1;
}
}
for (int i = 0; i < second.length; i++) {
boolean inc = i < 2;
search(second, i, inc, true);
if (!inc) {
second[i] += 1;
}
}
String s = "!";
for (int i = 0; i < 4; i++) {
s += " " + second[i];
}
for (int i = 0; i < 4; i++) {
s += " " + first[i];
}
out.println(s);
out.flush();
}
static void search(int arr[], int i, boolean inc, boolean cond) {
int start = 0;
int end = n;
while (true) {
if (end - start <= 1) {
arr[i] = start;
return;
}
int mid = (start + end) / 2;
arr[i] = mid;
int n = ask(arr, cond);
if (n > 0) {
if (inc) {
start = mid;
} else {
end = mid;
}
} else {
if (inc) {
end = mid;
} else {
start = mid;
}
}
}
}
static int ask(int arr[], boolean cond) {
if (arr[1] > arr[3] || arr[0] > arr[2]) {
return 0;
}
arr = Arrays.copyOf(arr, 4);
String q = "";
q += "?";
for (int i = 0; i < arr.length; i++) {
int x = Math.min(arr[i], n - 1);
x = Math.max(x, 1);
q += " " + x;
}
out.println(q);
out.flush();
int x = in.nextInt();
if (cond) {
x -= within(arr, first) ? 1 : 0;
}
return x;
/*if (arr[1] > arr[3] || arr[0] > arr[2]) {
return 0;
}
int[] check = new int[]{1, 1, 10, 1};
int[] check1 = new int[]{5, 5, 5, 10};
int result = within(arr, check) ? 1 : 0;
result += within(arr, check1) ? 1 : 0;
if (cond) {
result -= within(arr, first) ? 1 : 0;
}
return result;*/
}
static boolean within(int outer[], int inner[]) {
return (outer[0] <= inner[0] && outer[1] <= inner[1] && outer[2] >= inner[2] && outer[3] >= inner[3]);
}
static class MyInputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public MyInputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| logn | 713_B. Searching Rectangles | 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.Arrays;
import java.util.StringTokenizer;
public class B {
static StringTokenizer st;
static BufferedReader br;
static PrintWriter pw;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n = nextInt();
int left = 0, right = n;
int x1 = 0, y1 = 0, x2 = 0, y2 = 0, x3 = 0, y3 = 0, x4 = 0, y4 = 0;
while (right-left > 1) {
int mid = (left+right) >> 1;
System.out.println("? "+1+" "+1+" "+mid+" "+n);
int ans = nextInt();
if (ans==2)
right = mid;
else
left = mid;
}
x4 = right;
left = 0;
right = n;
while (right-left > 1) {
int mid = (left+right) >> 1;
System.out.println("? "+1+" "+1+" "+mid+" "+n);
int ans = nextInt();
if (ans >= 1)
right = mid;
else
left = mid;
}
x2 = right;
left = 1;
right = n+1;
while (right-left > 1) {
int mid = (left+right) >> 1;
System.out.println("? "+mid+" "+1+" "+n+" "+n);
int ans = nextInt();
if (ans >= 1)
left = mid;
else
right = mid;
}
x3 = left;
left = 1;
right = n+1;
while (right-left > 1) {
int mid = (left+right) >> 1;
System.out.println("? "+mid+" "+1+" "+n+" "+n);
int ans = nextInt();
if (ans >= 2)
left = mid;
else
right = mid;
}
x1 = left;
left = 0;
right = n;
while (right-left > 1) {
int mid = (left+right) >> 1;
System.out.println("? "+1+" "+1+" "+n+" "+mid);
int ans = nextInt();
if (ans>=2)
right = mid;
else
left = mid;
}
y4 = right;
left = 0;
right = n;
while (right-left > 1) {
int mid = (left+right) >> 1;
System.out.println("? "+1+" "+1+" "+n+" "+mid);
int ans = nextInt();
if (ans >= 1)
right = mid;
else
left = mid;
}
y2 = right;
left = 1;
right = n+1;
while (right-left > 1) {
int mid = (left+right) >> 1;
System.out.println("? "+1+" "+mid+" "+n+" "+n);
int ans = nextInt();
if (ans >= 1)
left = mid;
else
right = mid;
}
y3 = left;
left = 1;
right = n+1;
while (right-left > 1) {
int mid = (left+right) >> 1;
System.out.println("? "+1+" "+mid+" "+n+" "+n);
int ans = nextInt();
if (ans >= 2)
left = mid;
else
right = mid;
}
y1 = left;
if (y3 <= y2 && x3 <= x2) {
System.out.println("! "+x3+" "+y3+" "+x2+" "+y2+" "+x1+" "+y1+" "+x4+" "+y4);
return;
}
System.out.println("? "+x1+" "+y1+" "+x2+" "+y2);
int ans1 = nextInt();
System.out.println("? "+x3+" "+y3+" "+x4+" "+y4);
int ans2 = nextInt();
if (ans1==1 && ans2==1) {
System.out.println("! "+x1+" "+y1+" "+x2+" "+y2+" "+x3+" "+y3+" "+x4+" "+y4);
return;
}
System.out.println("? "+x1+" "+y3+" "+x2+" "+y4);
ans1 = nextInt();
System.out.println("? "+x3+" "+y1+" "+x4+" "+y2);
ans2 = nextInt();
if (ans1==1 && ans2==1) {
System.out.println("! "+x1+" "+y3+" "+x2+" "+y4+" "+x3+" "+y1+" "+x4+" "+y2);
return;
}
System.out.println("? "+x1+" "+y1+" "+x4+" "+y2);
ans1 = nextInt();
System.out.println("? "+x3+" "+y3+" "+x2+" "+y4);
ans2 = nextInt();
if (ans1==1 && ans2==1) {
System.out.println("! "+x1+" "+y1+" "+x4+" "+y2+" "+x3+" "+y3+" "+x2+" "+y4);
return;
}
System.out.println("? "+x1+" "+y3+" "+x2+" "+y2);
ans1 = nextInt();
System.out.println("? "+x3+" "+y1+" "+x4+" "+y4);
ans2 = nextInt();
if (ans1==1 && ans2==1) {
System.out.println("! "+x1+" "+y3+" "+x2+" "+y2+" "+x3+" "+y1+" "+x4+" "+y4);
return;
}
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(br.readLine());
return st.nextToken();
}
} | logn | 713_B. Searching Rectangles | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.PrintStream;
import java.util.StringTokenizer;
import java.util.Scanner;
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 Wolfgang Beyer
*/
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
int found = 0;
int queryCount = 0;
int[] result = new int[8];
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
//int n = 100;
//int n = 65536;
int left = 1;
int right = n + 1;
while (left + 1 < right) {
int middle = (left + right) / 2;
int res = query(middle, 1, n, n);
if (res == 2) left = middle;
else if (res == 1) {
//System.out.println("Searching single: ");
findSingle(middle, 1, n, n);
found++;
break;
} else {
right = middle;
}
}
int top = 1;
int bottom = n + 1;
while (top + 1 < bottom) {
int middle = (top + bottom) / 2;
int res = query(1, middle, n, n);
if (res == 2) top = middle;
else if (res == 1) {
if ((found == 0) || (!containsRect(1, middle, n, n, result[0], result[1], result[2], result[3]))) {
//System.out.println("Searching single: ");
findSingle(1, middle, n, n);
found++;
}
break;
} else {
bottom = middle;
}
}
if (found < 2) {
//System.out.println("Dia 3: ");
left = 0;
right = n;
while (left + 1 < right) {
int middle = (left + right) / 2;
int res = query(1, 1, middle, n);
if (res == 2) right = middle;
else if (res == 1) {
if ((found == 0) || (!containsRect(1, 1, middle, n, result[0], result[1], result[2], result[3]))) {
//System.out.println("Searching single: ");
findSingle(1, 1, middle, n);
found++;
}
break;
} else {
left = middle;
}
}
}
if (found < 2) {
//System.out.println("Dia 4:");
top = 0;
bottom = n;
while (top + 1 < bottom) {
int middle = (top + bottom) / 2;
int res = query(1, 1, n, middle);
if (res == 2) bottom = middle;
else if (res == 1) {
if ((found == 0) || (!containsRect(1, 1, n, middle, result[0], result[1], result[2], result[3]))) {
//System.out.println("Searching single: ");
findSingle(1, 1, n, middle);
found++;
}
break;
} else {
top = middle;
}
}
}
System.out.print("! ");
for (int i = 0; i < 8; i++) System.out.print(result[i] + " ");
//System.out.println("\n" + queryCount + " queries used");
}
public boolean containsRect(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {
if ((x1 <= x3) && (y1 <= y3) && (x2 >= x4) && (y2 >= y4)) return true;
return false;
}
public void findSingle(int x1, int y1, int x2, int y2) {
x1 = findTopX(x1, y1, x2, y2);
y1 = findTopY(x1, y1, x2, y2);
x2 = findBottomX(x1, y1, x2, y2);
y2 = findBottomY(x1, y1, x2, y2);
//System.out.println("x1: " + x1 + ", y1: " + y1 + ", x2: " + x2 + ", y2: " + y2);
result[0 + 4 * found] = x1;
result[1 + 4 * found] = y1;
result[2 + 4 * found] = x2;
result[3 + 4 * found] = y2;
}
public int findTopX(int x1, int y1, int x2, int y2) {
int left = x1;
int right = x2;
while (left + 1 < right) {
int mid = (left + right) / 2;
if (query(mid, y1, x2, y2) == 1) {
left = mid;
} else {
right = mid;
}
}
while (query(right, y1, x2, y2) == 0) right--;
return right;
}
public int findTopY(int x1, int y1, int x2, int y2) {
int left = y1;
int right = y2;
while (left + 1 < right) {
int mid = (left + right) / 2;
if (query(x1, mid, x2, y2) == 1) {
left = mid;
} else {
right = mid;
}
}
while (query(x1, right, x2, y2) == 0) right--;
return right;
}
public int findBottomX(int x1, int y1, int x2, int y2) {
int left = x1;
int right = x2;
while (left + 1 < right) {
int mid = (left + right) / 2;
if (query(x1, y1, mid, y2) == 1) {
right = mid;
} else {
left = mid;
}
}
while (query(x1, y1, left, y2) == 0) left++;
return left;
}
public int findBottomY(int x1, int y1, int x2, int y2) {
int left = y1;
int right = y2;
while (left + 1 < right) {
int mid = (left + right) / 2;
if (query(x1, y1, x2, mid) == 1) {
right = mid;
} else {
left = mid;
}
}
while (query(x1, y1, x2, left) == 0) left++;
return left;
}
public int query(int x1, int y1, int x2, int y2) {
queryCount++;
System.out.println("? " + x1 + " " + y1 + " " + x2 + " " + y2);
System.out.flush();
Scanner sc = new Scanner(System.in);
return sc.nextInt();
/*int ret = 0;
//if(x1 <= 17 && 57 <= x2 && y1 <= 80 && 80 <= y2) ++ret;
//if(x1 <= 25 && 88 <= x2 && y1 <= 51 && 61 <= y2) ++ret;
if(x1 <= 10 && 10 <= x2 && y1 <= 11 && 11 <= y2) ++ret;
//if(x1 <= 11 && 11 <= x2 && y1 <= 10 && 10 <= y2) ++ret;
if(x1 <= 10 && 10 <= x2 && y1 <= 15 && 15 <= y2) ++ret;
//System.out.println(x1 + ", " + y1 + ", " + x2 + ", " + y2 + ": " + ret);
return ret;*/
}
}
static class InputReader {
private static BufferedReader in;
private static StringTokenizer tok;
public InputReader(InputStream in) {
this.in = new BufferedReader(new InputStreamReader(in));
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
try {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
} catch (IOException ex) {
System.err.println("An IOException was caught :" + ex.getMessage());
}
return tok.nextToken();
}
}
}
| logn | 713_B. Searching Rectangles | 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
*/
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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
int n;
int sepX;
int sepY;
int x1;
int y1;
int x2;
int y2;
FastScanner in;
PrintWriter out;
public void solve(int testNumber, FastScanner in, PrintWriter out) {
this.in = in;
this.out = out;
n = in.nextInt();
int x11, x12, y11, y12;
int x21, x22, y21, y22;
findSeparatingX();
findSeparatingY();
if (sepX >= 0) {
locate(0, 0, sepX, n);
x11 = x1;
y11 = y1;
x12 = x2;
y12 = y2;
locate(sepX, 0, n, n);
x21 = x1;
y21 = y1;
x22 = x2;
y22 = y2;
} else {
locate(0, 0, n, sepY);
x11 = x1;
y11 = y1;
x12 = x2;
y12 = y2;
locate(0, sepY, n, n);
x21 = x1;
y21 = y1;
x22 = x2;
y22 = y2;
}
++x11;
++x21;
++y11;
++y21;
out.println("! " + x11 + " " + y11 + " " + x12 + " " + y12 + " " + +x21 + " " + y21 + " " + x22 + " " + y22);
out.flush();
}
void locate(int x1, int y1, int x2, int y2) {
for (int step = 15; step >= 0; step--) {
int h = 1 << step;
if (query(x1 + h, y1, x2, y2) > 0) {
x1 += h;
}
if (query(x1, y1, x2 - h, y2) > 0) {
x2 -= h;
}
if (query(x1, y1 + h, x2, y2) > 0) {
y1 += h;
}
if (query(x1, y1, x2, y2 - h) > 0) {
y2 -= h;
}
}
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
private void findSeparatingX() {
int l = 0;
int r = n;
while (r - l > 1) {
int m = (l + r) / 2;
if (query(0, 0, m, n) == 0) {
l = m;
} else {
r = m;
}
}
sepX = -1;
if (query(0, 0, r, n) == 1 && query(r, 0, n, n) == 1) {
sepX = r;
}
}
private void findSeparatingY() {
int l = 0;
int r = n;
while (r - l > 1) {
int m = (l + r) / 2;
if (query(0, 0, n, m) == 0) {
l = m;
} else {
r = m;
}
}
sepY = -1;
if (query(0, 0, n, r) == 1 && query(0, r, n, n) == 1) {
sepY = r;
}
}
int query(int x1, int y1, int x2, int y2) {
if (x1 >= x2 || y1 >= y2) {
return 0;
}
++x1;
++y1;
out.println("? " + x1 + " " + y1 + " " + x2 + " " + y2);
out.flush();
return in.nextInt();
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
String rl = in.readLine();
if (rl == null) {
return null;
}
st = new StringTokenizer(rl);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| logn | 713_B. Searching Rectangles | 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 Hieu Le
*/
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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
private int n;
private InputReader in;
private PrintWriter out;
public void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.nextInt();
this.in = in;
this.out = out;
query(new Point(1, 1), new Point(n, n), new Rectangle());
}
private boolean query(Point bottomLeft, Point topRight, Rectangle rectangle) {
if (bottomLeft.r > topRight.r || bottomLeft.c > topRight.c)
return false;
// Find the column of the right edge.
int low = bottomLeft.c, high = topRight.c;
while (low < high) {
int mid = low + (high - low) / 2;
int answer = ask(bottomLeft.r, bottomLeft.c, topRight.r, mid);
if (answer > 0)
high = mid;
else
low = mid + 1;
}
int rightCol = low;
// Find the column of the left edge.
low = bottomLeft.c;
high = topRight.c;
while (low < high) {
int mid = low + (high - low + 1) / 2;
int answer = ask(bottomLeft.r, mid, topRight.r, topRight.c);
if (answer > 0)
low = mid;
else
high = mid - 1;
}
int leftCol = low;
// Find the topmost row.
low = bottomLeft.r;
high = topRight.r;
while (low < high) {
int mid = low + (high - low) / 2;
int answer = ask(bottomLeft.r, bottomLeft.c, mid, topRight.c);
if (answer > 0)
high = mid;
else
low = mid + 1;
}
int topRow = low;
// Find the bottommost row.
low = bottomLeft.r;
high = topRight.r;
while (low < high) {
int mid = low + (high - low + 1) / 2;
int answer = ask(mid, bottomLeft.c, topRight.r, topRight.c);
if (answer > 0)
low = mid;
else
high = mid - 1;
}
int bottomRow = low;
if (leftCol > rightCol) {
Rectangle first = new Rectangle();
query(new Point(1, leftCol), new Point(n, n), first);
Rectangle second = new Rectangle();
query(new Point(1, 1), new Point(n, rightCol), second);
out.printf("! %d %d %d %d %d %d %d %d\n",
first.bottomLeft.r, first.bottomLeft.c, first.topRight.r, first.topRight.c,
second.bottomLeft.r, second.bottomLeft.c, second.topRight.r, second.topRight.c);
return true;
}
if (bottomRow > topRow) {
Rectangle first = new Rectangle();
query(new Point(bottomRow, 1), new Point(n, n), first);
Rectangle second = new Rectangle();
query(new Point(1, 1), new Point(topRow, n), second);
out.printf("! %d %d %d %d %d %d %d %d\n",
first.bottomLeft.r, first.bottomLeft.c, first.topRight.r, first.topRight.c,
second.bottomLeft.r, second.bottomLeft.c, second.topRight.r, second.topRight.c);
return true;
}
rectangle.bottomLeft.r = bottomRow;
rectangle.bottomLeft.c = leftCol;
rectangle.topRight.r = topRow;
rectangle.topRight.c = rightCol;
return true;
}
private int ask(int r1, int c1, int r2, int c2) {
out.printf("? %d %d %d %d\n", r1, c1, r2, c2);
out.flush();
return in.nextInt();
}
private class Point {
private int r;
private int c;
public Point(int r, int c) {
this.r = r;
this.c = c;
}
}
private class Rectangle {
private Point bottomLeft;
private Point topRight;
public Rectangle() {
bottomLeft = new Point(-1, -1);
topRight = new Point(-1, -1);
}
}
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
private static final int BUFFER_SIZE = 32768;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), BUFFER_SIZE);
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());
}
}
}
| logn | 713_B. Searching Rectangles | CODEFORCES |
import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
InputStream is;
PrintWriter out;
String INPUT = "" ;
boolean local = false;
int inf=0x7FFFFFFF;
int MOD=(int)(1e9+7);
double eps=1e-5;
double PI=Math.acos(-1);
void solve() {
long maxn=nl();
long L=1,R=maxn,ans=-1;
while (L<=R){
long mid=(L+R)/2;
if(ask(1,1,mid,maxn)<1)L=mid+1;
else{
R=mid-1;
ans=mid;
}
}
if(ask(1,1,ans,maxn)==1 && ask(ans+1,1,maxn,maxn)==1){
Yts1999 a1=gao(1,1,ans,maxn);
Yts1999 a2=gao(ans+1,1,maxn,maxn);
answer(a1,a2);
}else{
L=1;R=maxn;ans=-1;
while (L<=R){
long mid=(L+R)/2;
if(ask(1,1,maxn,mid)<1)L=mid+1;
else{
R=mid-1;
ans=mid;
}
}
Yts1999 a1=gao(1,1,maxn,ans);
Yts1999 a2=gao(1,ans+1,maxn,maxn);
answer(a1,a2);
}
}
void answer(Yts1999 a1,Yts1999 a2){
out.print("!");
a1.print();
a2.print();
out.flush();
}
int ask(long a,long b,long c,long d){
out.printf("? %d %d %d %d",a,b,c,d);
out.println();
out.flush();
return ni();
}
Yts1999 gao(long x1,long x2,long y1,long y2){
long a1=0,a2=0,a3=0,a4=0;
long L,R;
L=x1;R=y1;
while(L<=R){
long mid=(L+R)/2;
if(ask(mid,x2,y1,y2)==1){
a1=mid;
L=mid+1;
}else R=mid-1;
}
L=x1;R=y1;
while(L<=R){
long mid=(L+R)/2;
if(ask(x1,x2,mid,y2)==1){
a3=mid;
R=mid-1;
}else L=mid+1;
}
L=x2;R=y2;
while(L<=R){
long mid=(L+R)/2;
if(ask(x1,mid,y1,y2)==1){
a2=mid;
L=mid+1;
}else R=mid-1;
}
L=x2;R=y2;
while(L<=R){
long mid=(L+R)/2;
if(ask(x1,x2,y1,mid)==1){
a4=mid;
R=mid-1;
}else L=mid+1;
}
return new Yts1999(a1,a2,a3,a4);
}
public class Yts1999 implements Comparable{
public long a,b,c,d;
public Yts1999(long a,long b,long c,long d){
this.a=a;
this.b=b;
this.c=c;
this.d=d;
}
public int compareTo(Object o) {
Yts1999 to=(Yts1999)o;
if(this.d<to.d) return 1;
else if(this.d==to.d) return 0;
else return -1;
}
public void print(){
out.printf(" %d %d %d %d",a,b,c,d);
}
}
long[] exgcd(long a, long b) {
if (b == 0) return new long[]{1,0,a};
long[] res = exgcd(b, a%b);
long t = res[0]; res[0] = res[1]; res[1] = t;
res[1] -= a/b*res[0];
return res;
}
long gcd(long a,long b){
return b==0?a:gcd(b,a%b);
}
long lcm(long a,long b){
return a*b/gcd(a,b);
}
private void run() {
is = local? new ByteArrayInputStream(INPUT.getBytes()):System.in;
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 Main().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 void tr(Object... o) { if(local)System.out.println(Arrays.deepToString(o)); }
} | logn | 713_B. Searching Rectangles | CODEFORCES |
import java.io.*;
import java.math.*;
import static java.lang.Math.*;
import java.security.SecureRandom;
import static java.util.Arrays.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import sun.misc.Regexp;
import java.awt.geom.*;
import sun.net.www.content.text.plain;
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(boolean[] A) {
for (Object oo : A) {
System.out.print(oo + " ");
}
System.out.println("");
}
public static void deb(double[] A) {
for (Object oo : A) {
System.out.print(oo + " ");
}
System.out.println("");
}
public static void deb(String[] 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(double[][] 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;
}
void run() throws IOException {
// in = new StreamTokenizer(new BufferedReader(new FileReader("input.txt")));
// out = new PrintWriter(new FileWriter("output.txt"));
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(new OutputStreamWriter(System.out));
solve();
out.flush();
}
//boolean inR(int x,int y){
//return (x<=0)&&(x<4)&&(y<=0)&&(y<4);
//}
@SuppressWarnings("unchecked")
void solve() throws IOException {
// BufferedReader re= new BufferedReader(new FileReader("C:\\Users\\ASELA\\Desktop\\PROBLEMSET\\input\\F\\10.in"));
BufferedReader re= new BufferedReader(new InputStreamReader(System.in));
Scanner sc= new Scanner(System.in);
long n=sc.nextLong(),k=sc.nextLong();
if(k*(k-1)/2<n-1)
System.out.println("-1");
else{
long ff=k*(k-1)/2;
ff=-2*(n-1-ff);
// System.out.println(ff);
long up=k,dw=0;
while(up-dw>1){
long c=(up+dw)/2;
if(c*(c-1)<=ff)dw=c;
else up=c;
}
if(n==1)
{ System.out.println("0");
return;
}
System.out.println(k-dw);
}
}
}
| logn | 287_B. Pipeline | CODEFORCES |
import java.util.*;
import java.io.*;
public class Main {
BufferedReader in;
StringTokenizer str = null;
PrintWriter out;
private String next() throws Exception{
if (str == null || !str.hasMoreElements())
str = new StringTokenizer(in.readLine());
return str.nextToken();
}
private int nextInt() throws Exception{
return Integer.parseInt(next());
}
private long nextLong() throws Exception{
return Long.parseLong(next());
}
private double nextDouble() throws Exception{
return Double.parseDouble(next());
}
public void run() throws Exception{
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
long n = nextLong();
if (n == 1) {
System.out.println(0);
return;
}
long k = nextLong();
long t = 1-(k-1) + k*(k+1)/2-1;
if (t < n){
System.out.println(-1);
return;
}
long l = 0;
long r = k;
while(r - l > 1) {
long m = (r + l)/2;
long s = 1 - m + k*(k+1)/2 - (k-m)*(k-m+1)/2;
//System.out.println(m + " " + s + " " + n);
if (s >= n){
r = m;
}else{
l = m;
}
}
System.out.println(r);
out.close();
}
public static void main(String[] args) throws Exception{
new Main().run();
}
}
| logn | 287_B. Pipeline | CODEFORCES |
import java.util.Scanner;
public class B {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long n = sc.nextLong();
long k = sc.nextLong();
if ((k - 1) * k / 2 + 1 < n) {
System.out.println(-1);
return;
}
long left = 0;
long right = k;
while (left < right) {
long m = (left + right) / 2;
if (k * (k - 1)/2 - (k - m) * (k - m - 1) / 2 +1 < n)
left = m + 1;
else
right = m;
}
System.out.println(left);
}
} | logn | 287_B. Pipeline | CODEFORCES |
import java.util.*;
public class B {
static long sum(long from, long to){
final long d = to - from;
return (d*(d + 1))/2 + (d + 1)*from;
}
static long howMany(long n, long k){
if (n == 1){
return 0;
}
if (n > (k*(k - 1))/2 + 1){
return -1;
}
long hi = k - 1;
long lo = 1;
while (lo < hi){
final long mi = (lo + hi + 1) >> 1;
final long sum = sum(mi, k - 1);
if (n - 1 - sum < mi){
lo = mi;
}else{
hi = mi - 1;
}
}
long res = k - lo;
final long sum = sum(lo, k - 1);
if (n - 1 - sum > 0){
res++;
}
return res;
}
public static void main(String [] args){
try (Scanner s = new Scanner(System.in)){
final long n = s.nextLong();
final long k = s.nextLong();
System.out.println(howMany(n, k));
}
}
}
| logn | 287_B. Pipeline | CODEFORCES |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
(new Main()).solve();
}
public Main() {
}
MyReader in = new MyReader();
PrintWriter out = new PrintWriter(System.out);
void solve() throws IOException {
// BufferedReader in = new BufferedReader(new
// InputStreamReader(System.in));
// Scanner in = new Scanner(System.in);
//Scanner in = new Scanner(new FileReader("forbidden-triples.in"));
//PrintWriter out = new PrintWriter("forbidden-triples.out");
long n = in.nextLong();
long k = in.nextLong();
long sum = 1;
long count = 0;
long index = k - 1;
long[] delta = {1000000000, 100000000, 10000000, 1000000, 100000, 10000, 1000, 100, 10, 1, 0};
while (index > 0) {
if (index + sum <= n) {
for (int d = 0; d < delta.length; d++) {
if (delta[d] < index) {
long m = (2 * index - delta[d])*(delta[d] + 1)/2;
if (m + sum <= n) {
sum += m;
index -= (delta[d] + 1);
count += (delta[d] + 1);
}
}
}
} else {
index = n - sum;
}
}
if (sum == n) {
out.println(count);
} else {
out.println(-1);
}
out.close();
}
};
class MyReader {
private BufferedReader in;
String[] parsed;
int index = 0;
public MyReader() {
in = new BufferedReader(new InputStreamReader(System.in));
}
public int nextInt() throws NumberFormatException, IOException {
if (parsed == null || parsed.length == index) {
read();
}
return Integer.parseInt(parsed[index++]);
}
public long nextLong() throws NumberFormatException, IOException {
if (parsed == null || parsed.length == index) {
read();
}
return Long.parseLong(parsed[index++]);
}
public String nextString() throws IOException {
if (parsed == null || parsed.length == index) {
read();
}
return parsed[index++];
}
private void read() throws IOException {
parsed = in.readLine().split(" ");
index = 0;
}
public String readLine() throws IOException {
return in.readLine();
}
}; | logn | 287_B. Pipeline | CODEFORCES |
import java.io.PrintWriter;
import java.util.Scanner;
public class Problem2 implements Runnable {
public void run() {
Scanner scanner = new Scanner(System.in);
PrintWriter writer = new PrintWriter(System.out);
long n = scanner.nextLong();
long k = scanner.nextLong();
long count = 1;
if (n == 1) {
writer.println(0);
writer.close();
return;
}
if (k >= n) {
writer.println(1);
writer.close();
return;
}
long answer = 0;
while (k > 1) {
if (k > 2000) {
if (count + k <= n) {
if (count + (k - 1 + k - 1000) * 500 <= n) {
count += (k - 1 + k - 1000) * 500;
k -= 1000;
answer += 1000;
}
}
}
if ((count + k - 1) <= n) {
count += (k - 1);
answer++;
}
if (count + k - 100000000000000000l > n) {
k -= 99999999999999999l;
}
if (count + k - 10000000000000000l > n) {
k -= 9999999999999999l;
}
if (count + k - 1000000000000000l > n) {
k -= 999999999999999l;
}
if (count + k - 100000000000000l > n) {
k -= 99999999999999l;
}
if (count + k - 10000000000000l > n) {
k -= 9999999999999l;
}
if (count + k - 1000000000000l > n) {
k -= 999999999999l;
}
if (count + k - 100000000000l > n) {
k -= 99999999999l;
}
if (count + k - 10000000000l > n) {
k -= 9999999999l;
}
if (count + k - 1000000000l > n) {
k -= 999999999l;
}
if (count + k - 100000000l > n) {
k -= 99999999l;
}
if (count + k - 10000000l > n) {
k -= 9999999l;
}
if (count + k - 1000000l > n) {
k -= 999999l;
}
if (count + k - 100000l > n) {
k -= 99999l;
}
if (count + k - 10000l > n) {
k -= 9999l;
}
if (count + k - 1000l > n) {
k -= 999l;
}
if (count + k - 100l > n) {
k -= 99l;
}
if (n - count + 1 < k) {
k = n - count + 1;
} else {
k--;
}
}
if (count == n) {
writer.println(answer);
} else {
writer.println(-1);
}
writer.close();
}
public static void main(String[] args) {
new Problem2().run();
}
}
| logn | 287_B. Pipeline | CODEFORCES |
import java.io.*;
import java.util.*;
public class My {
public static void main(String[] args) {
new My().go();
}
void go() {
Scanner in = new Scanner(System.in);
long n = in.nextLong();
int k = in.nextInt();
int mn = 0, mx = k + 1;
while (mn < mx) {
int mid = (mn + mx) / 2;
if (works(n, k, mid)) {
mx = mid;
} else {
mn = mid + 1;
}
}
if (mn > k) {
pl("-1");
} else {
pl((mn - 1) + "");
}
}
boolean works(long n, int k, int use) {
return 1 + T(k - 1) - T(k - use) >= n;
}
long T(int n) {
return n * (long)(n + 1) / 2;
}
void p(String s) {
System.out.print(s);
}
void pl(String s) {
System.out.println(s);
}
} | logn | 287_B. Pipeline | CODEFORCES |
import java.io.PrintWriter;
import java.util.*;
public class B {
public static void main(String[] args) {
PrintWriter out = new PrintWriter(System.out);
Scanner sc = new Scanner(System.in);
long N = sc.nextLong();
long K = sc.nextLong();
if (N == 1) {
out.println(0);
} else if (N <= K) {
out.println(1);
} else if (N > ((K - 1) * (K)) / 2 + 1) {
out.println(-1);
} else {
long lo = 1;
long hi = Math.max(K - 2, 1);
long big = ((K - 2) * (K - 1)) / 2;
long prevmid = -1;
for (int i = 0; i < 10000; i++) {
long mid = (lo + hi) / 2;
// K = 5
// Start = K-2;
// 1 = K-2;
// 2 = K-3... etc.
long tmp = ((K - 2 - mid) * (K - 2 - mid + 1)) / 2;
//System.out.println(mid + " " + big + " " + tmp);
if (K + big - tmp > N) {
hi = mid;
} else if (K + big - tmp < N) {
lo = mid;
if (prevmid == mid)
lo++;
lo = Math.min(lo, hi);
prevmid = mid;
} else {
lo = mid;
break;
}
}
out.println((long) lo + 1);
}
sc.close();
out.close();
}
}
| logn | 287_B. Pipeline | CODEFORCES |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.Vector;
/**
* Created with IntelliJ IDEA.
* User: horikawa
* Date: 3/23/13
* Time: 1:29 AM
* To change this template use File | Settings | File Templates.
*/
public class B {
public static void main (String[] argv) {
Scanner in = new Scanner(System.in);
long n = in.nextLong();
long k = in.nextLong();
long max = ((k*(k-1))/2L)+1L;
long ans = -1;
if (n == 1) {
System.out.println(0);
return;
}
if (max < n) {
ans = -1;
} else if (max == n) {
ans = k-1;
} else {
if (k >= n) {
ans = 1;
} else {
long low = 1;
long high = k-1;
while (high > low+1) {
long mid = (low+high)/2;
long sum = (((mid+(k-1)) * (k-mid)) / 2) + 1;
if (sum >= n) {
low = mid;
} else {
high = mid;
}
}
ans = (k - low);
}
}
System.out.println(ans);
return;
}
}
| logn | 287_B. Pipeline | CODEFORCES |
import java.io.PrintWriter;
import java.util.Scanner;
public class B {
public static void main(String[] args) {
doIt();
}
static void doIt() {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
long n = sc.nextLong();
long k = sc.nextLong();
long msum = (k - 1) * k / 2 + 1;
long u = k;
long l = 0;
long m = (u + l) / 2;
while(l < u){
m = (u + l) / 2 + (u + l) % 2;
long sum = (m - 1) * m / 2;
if(n <= msum - sum) l = m;
else u = m - 1;
}
m = (u + l) / 2 + (u + l) % 2;
if(msum - (m - 1) * m / 2 < n) System.out.println(-1);
else System.out.println(k - m);
}
}
| logn | 287_B. Pipeline | CODEFORCES |
import java.util.Scanner;
import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
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;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, Scanner in, PrintWriter out) {
long n=in.nextLong();
long k=in.nextInt();
if(n==1){
out.println(0);
return;
}
long max=k*(k-1)/2+1;
if(max<n){
out.println("-1");
return;
}
long low=1,high=k-1;
long ans=k-1;
while (low<=high){
long mid=(low+high)/2;
long val=mid*mid-mid*(2*k-1)+2*n-2;
if(val>0){
low=mid+1;
}
else {
ans=mid;
high=mid-1;
}
}
out.println(ans);
}
}
| logn | 287_B. Pipeline | 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 P287B{
Scanner sc=new Scanner(System.in);
int INF=1<<28;
double EPS=1e-9;
long n, k;
void run(){
n=sc.nextLong();
k=sc.nextLong();
solve();
}
void solve(){
long left=-1, right=k+1;
for(; right-left>1;){
long m=(left+right)/2;
long lb=k*(k+1)/2-(k-m)*(k-m+1)/2-(m-1);
if(lb>=n){
right=m;
}else{
left=m;
}
}
// debug(left, right);
println(""+(right>k?-1:right));
}
void println(String s){
System.out.println(s);
}
void print(String s){
System.out.print(s);
}
void debug(Object... os){
System.err.println(deepToString(os));
}
public static void main(String[] args){
Locale.setDefault(Locale.US);
new P287B().run();
}
}
| logn | 287_B. Pipeline | CODEFORCES |
/**
* Created with IntelliJ IDEA.
* User: yuantian
* Date: 3/24/13
* Time: 2:18 AM
* Copyright (c) 2013 All Right Reserved, http://github.com/tyuan73
*/
import java.util.*;
public class Pipeline {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
long n = in.nextLong();
long k = in.nextLong();
if (n == 1) {
System.out.println(0);
return;
}
if (k >= n) {
System.out.println(1);
return;
}
long total = (k + 2) * (k - 1) / 2 - (k - 2);
if (total < n) {
System.out.println(-1);
return;
}
int i = 2, j = (int) k;
while (i <= j) {
int m = (i + j) / 2;
total = (k + m) * (k - m + 1) / 2 - (k - m);
if (total == n) {
System.out.println(k - m + 1);
return;
}
if (total < n)
j = m - 1;
else
i = m + 1;
}
System.out.println(k-i+2);
}
}
| logn | 287_B. Pipeline | CODEFORCES |
import java.util.Scanner;
public class b {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long n = sc.nextLong() - 1, k = sc.nextLong() - 1;
int a = 0;
if ((k + 1) * k / 2 < n) {
System.out.println(-1);
return;
}
while (n > 0 && k > 0) {
long min = go(n, k);
a += (k - min + 1);
n -= (k + min) * (k - min + 1) / 2;
k = Math.min(min - 1, n);
}
if (n == 0)
System.out.println(a);
else
System.out.println(-1);
}
static long go(long n, long k) {
long low = 1, high = k;
while (low + 1 < high) {
long mid = (low + high) / 2;
if ((k + mid) * (k - mid + 1) / 2 <= n) {
high = mid;
} else
low = mid;
}
return high;
}
}
| logn | 287_B. Pipeline | CODEFORCES |
import java.util.Scanner;
public class Pipeline {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long n = sc.nextLong();
long k = sc.nextLong();
sc.close();
if (k * (k - 1) / 2 + 1 < n) {
System.out.println(-1);
} else {
long l = -1, r = k;
while (r - l > 1) {
long m = (r + l) / 2;
if (cantidadPosible(k, m) >= n) {
r = m;
} else {
l = m;
}
}
System.out.println(r);
}
}
private static long cantidadPosible(long k, long usadas) {
return (k * (k - 1) / 2 + 1 - (k - usadas) * (k - usadas - 1) / 2);
}
}
| logn | 287_B. Pipeline | CODEFORCES |
import java.math.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
long n = scan.nextLong();
long k = scan.nextLong();
long total = k * (k - 1) / 2 + 1;
if (total < n) {
System.out.println(-1);
return;
}
long left = total - n;
long low = 1;
long high = k - 1;
while (low < high) {
long mid = (low + high) / 2;
long temp = mid * (mid + 1) / 2;
if (temp < left) {
low = mid + 1;
} else {
high = mid;
}
}
long temp = low * (low + 1) / 2;
if (temp == left) {
System.out.println(k - 1 - low);
} else {
System.out.println(k - low);
}
}
}
| logn | 287_B. Pipeline | CODEFORCES |
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Scanner;
import java.util.ArrayList;
public class Main {
static int d[][];
static int N;
static boolean used[];
static class point
{
int x = 0;
int y = 0;
}
static point dats[];
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
long n = scan.nextLong();
long k = scan.nextLong();
if(n==1)
{
System.out.print("0");
return;
}
if(n<=k)
{
System.out.print("1");
return;
}
long d = 9-4*(2*n-k*k+k);
if(d<0)
{
System.out.print("-1");
return;
}
double a = ((3+Math.sqrt(d)) / 2) ;
if(a>=1)
System.out.println(Math.max(2, k-(long)a+1));
else
System.out.println(-1);
}
}
| logn | 287_B. Pipeline | CODEFORCES |
import java.math.BigInteger;
import java.util.Scanner;
public class B {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long n = sc.nextLong();
long k = sc.nextLong();
if (n == 1) {
System.out.println(0);
} else if (n <= k) {
System.out.println(1);
} else {
n--;
k--;
BigInteger K = BigInteger.valueOf(k);
BigInteger N = BigInteger.valueOf(n);
BigInteger high = BigInteger.valueOf(k + 1);
BigInteger low = BigInteger.valueOf(1);
BigInteger mid;
while (low.compareTo(high) < 0) {
mid = low.add(high.subtract(low).shiftRight(1));
BigInteger elemCnt = K.subtract(mid).add(BigInteger.ONE);
BigInteger sum = elemCnt.multiply(
mid.shiftLeft(1).add(elemCnt.subtract(BigInteger.ONE)))
.shiftRight(1);
if (sum.compareTo(N) > 0) {
low = mid.add(BigInteger.valueOf(1));
} else {
high = mid;
}
}
BigInteger elemCnt = K.subtract(low).add(BigInteger.ONE);
BigInteger sum = elemCnt.multiply(
low.shiftLeft(1).add(elemCnt.subtract(BigInteger.ONE)))
.shiftRight(1);
BigInteger rem = N.subtract(sum);
if (rem.equals(BigInteger.ZERO)) {
System.out.println(elemCnt);
} else if (rem.compareTo(low) < 0) {
System.out.println(elemCnt.add(BigInteger.ONE));
} else {
System.out.println(-1);
}
}
}
}
| logn | 287_B. Pipeline | CODEFORCES |
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.PrintWriter;
import java.util.Scanner;
public class B176 {
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedInputStream(System.in));
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
long n = in.nextLong() - 1;
long k = in.nextLong() - 1;
if (k * (k + 1) / 2 < n) out.println(-1);
else if (n == 0) out.println(0);
else if (n < k) out.println(1);
else {
long t = binSearch(n, k, 1, k);
long ans = k - t + 1;
if (k * (k + 1) / 2 - t * (t - 1) / 2 != n) ans++;
out.println(ans);
}
out.close();
}
private static long binSearch(long n, long k, long from, long to) {
if (from == to) return from;
long mid = (from + to) / 2;
if (k * (k + 1) / 2 - mid * (mid - 1) / 2 > n) return binSearch(n, k, mid + 1, to);
else return binSearch(n, k, from, mid);
}
}
| logn | 287_B. Pipeline | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class Main {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
String[] param = br.readLine().split(" ");
long n = Long.parseLong(param[0])-1;
long k = Long.parseLong(param[1])-1;
long max = k*(k+1)/2;
long answer;
if (n > max) answer = -1;
else {
long margin = max - n;
long m = Math.max(0,(long)Math.floor((1.0+Math.sqrt(1+8*margin))/2.0)-1);
long min = m*(m+1)/2;
while (min <= margin) { m++; min = m*(m+1)/2; }
answer = k - m + 1;
}
pw.println(answer);
pw.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
return;
}
}
} | logn | 287_B. Pipeline | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author George Marcus
*/
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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, InputReader in, PrintWriter out) {
long N = in.nextLong();
long K = in.nextLong();
if(N == 1) {
out.println(0);
return;
}
if(N <= K) {
out.println(1);
return;
}
long st = 1;
long dr = K - 1;
long m;
long ans = -1;
while(st <= dr) {
m = (st + dr) / 2;
if(get(m, K) <= N) {
ans = m;
st = m + 1;
}
else dr = m - 1;
}
N -= get(ans, K);
if(ans == -1 || (ans == K - 1 && N > 0) ) {
out.println(-1);
return;
}
if(N > 0)
ans++;
out.println(ans);
}
private long get(long p, long K) {
long sum = (K - p + 1 + K) * p / 2;
long extra = p - 1;
return sum - extra;
}
}
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 nextLong() {
return Long.parseLong(nextString());
}
public String nextString() {
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;
}
}
| logn | 287_B. Pipeline | CODEFORCES |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.Scanner;
/**
*
* @author 111
*/
public class JavaApplication4 {
/**
* @param args the command line arguments
*/
static long k, n, ans;
static private long binsearch(long l, long r)
{
if(l==r) return l;
long m=(l+r)/2;
long res=(m*(k+k-m+1)/2);
if(res>=n)
return binsearch(l, m);
else
return binsearch(m+1, r);
}
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
n=in.nextLong();
k=in.nextLong();
n--;
k--;
if(k*(k+1)/2<n)
ans=-1;
else
ans=binsearch(0, k);
System.out.println(ans);
}
}
| logn | 287_B. Pipeline | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class B {
/**
* @param args
* @throws IOException
* @throws NumberFormatException
*/
public static void main(String[] args) throws NumberFormatException,
IOException {
Scanner sc = new Scanner(System.in);
long n = sc.nextLong(), k = sc.nextLong();
// BufferedReader rd = new BufferedReader(new
// InputStreamReader(System.in));
// StringTokenizer t = new StringTokenizer(rd.readLine(), " ");
// int n = Integer.parseInt(rd.readLine());
if (n == 1) {
System.out.println(0);
return;
}
if (n <= k) {
System.out.println(1);
return;
}
long seg = (((k + 1) * (k) / 2) - 1);
seg += (2 - k);
if (seg < n) {
System.out.println(-1);
return;
}
// long sum = k;
// long out = 0l;
long s = 1, f = k;
long mid = (s + f) / 2;
while (s + 1 < f) {
long seg_m = (((mid + k - 1) * (k - mid) / 2));
// seg += (2 - mid);
// long sum_m = seg - seg_m;
if (seg_m >= n - 1) {
// if (n - mid < out || out == 0) {
// out = n - mid - 1;
// }
s = mid;
} else
f = mid;
mid = (s + f) / 2;
}
// for (long i = k - 1; sum < n && i >= 2; i--) {
// sum += i - 1;
// out++;
// // if (sum >= n)
// // break;
// }
System.out.println(k - s);
}
}
| logn | 287_B. Pipeline | CODEFORCES |
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class PipelineRedo {
public static void main(String[] args){
FastScanner sc = new FastScanner();
long n = sc.nextLong() - 1;
long k = sc.nextInt() - 1;
if(n==0){
System.out.println(0);
return;
}else if(n <= k){
System.out.println(1);
return;
}else if(n > k*(k+1)/2){
System.out.println(-1);
return;
}
//n > k, and there exists a subset (1..k) = n
//goal : sum( subset of (1...k) ) = n
//obs: if exists a soln, it's always possible to push everything to the right-> t + left...k
//so that t + left...k = n, so we just have to find the smallest left such that left..k <= n
long rightSum = k*(k+1)/2;
long lo = 1;
long hi = k;
while(lo < hi){
long mid = lo + (hi-lo+1)/2;
long val = rightSum - mid*(mid-1)/2;
if(val <= n){
hi = mid -1;
}else{
lo = mid;
}
}
//now lo points to the greatest left for which left..k > n
//so lo+1 points to the smallest left for which left..k <= n
//we still have an extra 't' to the left
if(rightSum - (lo+1)*(lo)/2 == n){
System.out.println(k - (lo+1) + 1);
}else{
System.out.println(1 + (k - (lo+1) + 1));
}
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
| logn | 287_B. Pipeline | CODEFORCES |
import java.io.*;
import java.util.*;
public class B
{
public static void main(String [] args) throws IOException
{
Scanner in = new Scanner(System.in);
long n = in.nextLong();
long k = in.nextLong();
if(n == 1)
{
System.out.println(0);
return;
}
if(n <= k)
{
System.out.println(1);
return;
}
long lb = 2, ub = k;
long sum = ((k)*(k-1))/2;
if(sum+1 < n)
{
System.out.println(-1);
return;
}
while(ub - lb > 1)
{
long mid = (lb+ub)/2;
long s = ((mid-1)*(mid-2))/2;
if(n - (sum-s+1) < 0)
lb = mid;
else
ub = mid;
}
long rem = n - (sum - ((ub-1)*(ub-2))/2 + 1);
long res = k - ub + 1;
if(rem == 0)
{
System.out.println(res);
return;
}
rem++;
if(!(rem >= 2 && rem < ub))
{
System.out.println(-1);
return;
}
System.out.println(res+1);
}
} | logn | 287_B. Pipeline | CODEFORCES |
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;
public class palin {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(System.out);
Scanner scan = new Scanner(System.in);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
}
class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
long n = in.nextLong() - 1;
long k = in.nextLong() - 1;
if (n == 0) {
out.print("0");
} else {
if (k >= n) {
out.print("1");
} else {
if (k * (k + 1) / 2 < n) {
out.print("-1");
} else {
long t = binsearch(n, k, 1, k);
long ans = k - t + 1;
if (k * (k + 1) / 2 - t * (t - 1) / 2 != n)
ans++;
System.out.println(ans);
}
}
}
}
public static long binsearch(long n, long k, long from, long to) {
if (from == to) {
return from;
}
long mid = (from + to) / 2;
if ((k * (k + 1)) / 2 - (mid * (mid - 1)) / 2 > n)
return binsearch(n, k, mid + 1, to);
else
return binsearch(n, k, from, mid);
}
}
class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
st = null;
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
} | logn | 287_B. Pipeline | CODEFORCES |
import java.io.*;
import java.math.BigInteger;
import java.util.StringTokenizer;
public class B implements Runnable {
// leave empty to read from stdin/stdout
private static final String TASK_NAME_FOR_IO = "";
// file names
private static final String FILE_IN = TASK_NAME_FOR_IO + ".in";
private static final String FILE_OUT = TASK_NAME_FOR_IO + ".out";
BufferedReader in;
PrintWriter out;
StringTokenizer tokenizer = new StringTokenizer("");
public static void main(String[] args) {
new Thread(new B()).start();
}
private void solve() throws IOException {
long n = nextLong();
long k = nextLong();
n--;
k--;
long answer = 0;
while (n > 0 && k >= 1) {
if (k > 2000) {
long step1000 = (k + (k - 999)) * 500;
if (n - step1000 >= 0) {
n -= step1000;
answer += 1000;
k -= 1000;
continue;
}
}
if (n - k >= 0) {
n -= k;
answer++;
}
k--;
k = Math.min(n, k);
}
if (n == 0) {
out.println(answer);
} else {
out.println(-1);
}
}
public void run() {
long timeStart = System.currentTimeMillis();
boolean fileIO = TASK_NAME_FOR_IO.length() > 0;
try {
if (fileIO) {
in = new BufferedReader(new FileReader(FILE_IN));
out = new PrintWriter(new FileWriter(FILE_OUT));
} else {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
}
solve();
in.close();
out.close();
} catch (IOException e) {
throw new IllegalStateException(e);
}
long timeEnd = System.currentTimeMillis();
if (fileIO) {
System.out.println("Time spent: " + (timeEnd - timeStart) + " ms");
}
}
private String nextToken() throws IOException {
while (!tokenizer.hasMoreTokens()) {
String line = in.readLine();
if (line == null) {
return null;
}
tokenizer = new StringTokenizer(line);
}
return tokenizer.nextToken();
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private BigInteger nextBigInt() throws IOException {
return new BigInteger(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
} | logn | 287_B. Pipeline | CODEFORCES |
import java.math.BigInteger;
import java.util.Scanner;
public class ehsan
{
public static BigInteger f(BigInteger m,BigInteger n){
BigInteger s,l;
s=n.multiply(m.add(BigInteger.valueOf(1)));
l=m.multiply(m.add(BigInteger.valueOf(1)));
l=l.divide(BigInteger.valueOf(2));
s=s.subtract(l);
s=s.subtract(m);
return s;
}
public static BigInteger bs(BigInteger a,BigInteger b,BigInteger n,BigInteger d){
BigInteger c,e;
c=a.add(b);
c=c.divide(BigInteger.valueOf(2));
e=f(c,n);
if(e.equals(d))
return c.add(BigInteger.valueOf(1));
if(a.equals(b.add(BigInteger.valueOf(-1))))
return b.add(BigInteger.valueOf(1));
if(e.compareTo(d)>0)
return bs(a,c,n,d);
return bs(c,b,n,d);
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
BigInteger bi1 = sc.nextBigInteger();
BigInteger bi2 = sc.nextBigInteger();
BigInteger i,n=bi2;
BigInteger i2=BigInteger.valueOf(1);
BigInteger sum=BigInteger.valueOf(0);
if(bi1.compareTo(bi2)<0){
System.out.println(0);
return;
}
else if( bi1.compareTo(bi2) == 0 )
{
System.out.println(1);
return;
}
bi2=((n.multiply(n.add(BigInteger.valueOf(1)))).divide(BigInteger.valueOf(2))).subtract(n.subtract(BigInteger.valueOf(1)));
if(bi1.compareTo(bi2)>0)
System.out.println(-1);
else{
System.out.println(bs(BigInteger.valueOf(0),n.add(BigInteger.valueOf(-2)),n,bi1));
}
}
} | logn | 287_B. Pipeline | CODEFORCES |
import java.util.Scanner;
public class B {
/**
* @param args
*/
public static void main(String[] args) {
Pipes pipes = new Pipes();
pipes.solve();
pipes.print();
}
}
class Pipes {
Pipes() {
Scanner scr = new Scanner(System.in);
n = scr.nextLong();
k = scr.nextLong();
}
long bs(long nb, long nk) {
long left = 2;
long ls = (nk - left + 1) * (nk + left) / 2 - (nk - left);
long right = nk;
long rs = nk;
if (nb > ls) {
return -1;
}
long mid = left;
while (rs < ls){
mid = (left + right)/2;
long ms = (nk - mid + 1) * (nk + mid) / 2 - (nk - mid);
if (nb > ms) {
right = mid;
rs = ms;
}
else if (nb < ms){
left = mid+1;
ls = (nk - left + 1) * (nk + left) / 2 - (nk - left);
}
else {
left = mid;
break;
}
}
return left;
}
void solve() {
long nn = n;
long kk = k;
ans = 0;
long ps = 1;
long add;
if (n == 1) {
ans = 0;
return;
}
nn = n - (ps - 1);
while (nn > kk){
add = bs(nn, kk);
if (add == -1) {
ans = -1;
return;
}
else {
ans = ans + (kk - add + 1);
}
long addn = (kk - add + 1) * (kk + add) / 2 - (kk - add);
ps = ps - 1 + addn;
if (ps == n)
return;
nn = nn - (ps - 1);
kk = add - 1;
}
if (nn > 0) {
ans++;
}
}
void print() {
System.out.println(ans);
}
long ans;
long n;
long k;
}
| logn | 287_B. Pipeline | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class B {
static long n, k;
static long sum(long mid) {
long tmpSum = k * (k + 1) / 2;
long nsum = (mid - 1) * (mid) / 2;
return tmpSum - nsum;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
StringTokenizer sc = new StringTokenizer(br.readLine());
n = Long.parseLong(sc.nextToken()) - 1;
k = Long.parseLong(sc.nextToken()) - 1;
if (n == 0)
out.println(0);
else if (sum(1) < n)
out.println(-1);
else {
long lo = 1;
long hi = k;
long mid;
while (lo < hi) {
mid = (lo + hi) / 2;
long sum = sum(mid);
if (n - sum < 0)
lo = mid + 1;
else if (n - sum < mid) {
hi = mid;
} else
hi = mid - 1;
}
out.println((k - lo + 1) + (n - sum(lo) == 0 ? 0 : 1));
}
br.close();
out.close();
}
}
| logn | 287_B. Pipeline | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
public class B {
public static BufferedReader in;
public static PrintWriter out;
public static void main(String[] args) throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
boolean showLineError = true;
if (showLineError) {
solve();
out.close();
} else {
try {
solve();
} catch (Exception e) {
} finally {
out.close();
}
}
}
static void debug(Object... os) {
out.println(Arrays.deepToString(os));
}
private static void solve() throws IOException {
String[] line = in.readLine().split(" ");
long n = Long.parseLong(line[0]) - 1;
long k = Long.parseLong(line[1]) - 1;
if (f(1, k) < n) {
out.println(-1);
return;
}
if (n == 0) {
out.println(0);
return;
}
long lo = 0l;
long hi = k;
while (lo + 1l < hi) {
long m = (lo + hi) / 2l;
long f = f(k - m + 1, k);
if (f < n) {
lo = m;
} else {
hi = m;
}
}
out.println(hi);
}
private static long f(long lo, long hi) {
return (lo + hi) * (hi - lo + 1l) / 2l;
}
} | logn | 287_B. Pipeline | CODEFORCES |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
//package pipeline;
import java.util.Scanner;
/**
*
* @author admin
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner scan=new Scanner(System.in);
long n=scan.nextLong(),k=scan.nextLong();
if(n>((k-2)*(k-1))/2+k){
System.out.println("-1");
}
else if(n==1){
System.out.println("0");
}
else if(n<=k&&n>1){
System.out.println("1");
}
else{
n-=k;
long start=k-2;
long x;
long left=1,right=k-2;
// System.out.println(left+" "+right);
while(left<=right){
x=(left+right)/2;
// System.out.println(x);
if(n>cumSum(x, start)){
left=x+1;
// System.out.println("if");
}
else if(n<cumSum(x-1, start)){
right=x-1;
// System.out.println("else if");
}
else{
System.out.println(1+x);
break;
}
}
}
}
public static long cumSum(long x,long start){
return (x*(2*start+1-x))/2;
}
}
| logn | 287_B. Pipeline | CODEFORCES |
import java.io.*;
import java.util.*;
public class Solution {
public static void main (String[] args) throws IOException {
boolean online = "true".equals(System.getProperty("ONLINE_JUDGE"));
if (online) {
in = new InputReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
else {
in = new InputReader(new FileReader("input.txt"));
out = new PrintWriter(new File("output.txt"));
}
new Solution().run();
out.close();
}
long sum (int x) {
return x * 1l * (x+1) / 2;
}
int bins (long n, int k) {
int l = 1,
r = k;
while (l < r) {
int w = (l+r)/2;
long s = sum(k) - sum(w-1);
if (s == n)
return w;
if (s < n)
r = w;
else
l = w+1;
}
return l;
}
private void run () {
long n = in.nextLong();
int k = in.nextInt();
if (n == 1) {
out.println(0);
return;
}
if (1 + sum(k-1) < n) {
out.println(-1);
return;
}
int c = bins(n-1,k-1);
if (1 + sum(k-1) - sum(c-1) == n)
out.println(k-c);
else
out.println(k-c+1);
}
private static InputReader in;
private static PrintWriter out;
}
class InputReader {
public InputReader (Reader r) {
buff = new BufferedReader(r);
try {
str = new StringTokenizer(buff.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
public String next () {
while (!str.hasMoreTokens())
try {
str = new StringTokenizer(buff.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return str.nextToken();
}
public int nextInt () {
return Integer.parseInt(this.next());
}
public long nextLong () {
return Long.parseLong(this.next());
}
private static BufferedReader buff;
private static StringTokenizer str;
} | logn | 287_B. Pipeline | CODEFORCES |
import java.util.*;
import java.math.*;
import java.io.*;
public class Main
{
public static void main(String args[]) throws IOException
{
Scanner c=new Scanner(System.in);
PrintWriter out=new PrintWriter(System.out);
long N=c.nextLong()-1;
long K=c.nextLong()-1;
long tot=(K*(K+1))/2;
//System.out.println(tot);
if(N>tot)
{
System.out.println(-1);
return;
}
long lo=1;
long hi=K;
while(hi-lo>=10)
{
long mid=(hi+lo)/2;
//maximum outlets using mid pipes
long sum=(mid*(mid-1))/2;
long left=mid*K-sum;
if(left>=N)
hi=mid+1;
else
lo=mid-1;
}
for(int num=(int)lo-1000;num<lo+1000;num++)
{
if(num>=0)
{
long sum=((long)num*(num-1))/2;
long left=(long)num*K-sum;
if(left>=N)
{
System.out.println(num);
return;
}
}
}
out.close();
}
}
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 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 char readCharacter()
{
int c=read();
while (isSpaceChar(c))
c=read();
return (char) c;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
| logn | 287_B. Pipeline | CODEFORCES |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
long k;
private void solve() throws IOException {
long n = nl();
k = nl();
if (n == 1) {
prln(0);
return;
}
if (n <= k) {
prln(1);
return;
}
long l = 1, r = k - 1;
long mid = (l + r + 1) / 2;
long old = -1;
while (old != mid) {
old = mid;
if (take(mid) >= n)
r = mid;
if (take(mid) < n)
l = mid;
mid = (l + r + 1) / 2;
}
if (mid >= k || mid <= 0) {
prln(-1);
return;
}
if (take(mid) == n) {
prln(mid);
return;
}
if (mid == k - 1)
prln(-1);
else
if (take(mid) < n)
prln(mid + 1);
else
prln(mid);
}
long take(long t) {
return k * t - t * (t - 1) / 2 - (t - 1);
}
public static void main(String[] args) {
new Main().run();
}
public void run() {
try {
if (isFileIO) {
pw = new PrintWriter(new File("output.out"));
br = new BufferedReader(new FileReader("input.in"));
} else {
pw = new PrintWriter(System.out);
br = new BufferedReader(new InputStreamReader(System.in));
}
solve();
pw.close();
br.close();
} catch (IOException e) {
System.err.println("IO Error");
}
}
private int[] nia(int n) throws IOException {
int arr[] = new int[n];
for (int i = 0; i < n; ++i)
arr[i] = Integer.parseInt(nextToken());
return arr;
}
private int[] niam1(int n) throws IOException {
int arr[] = new int[n];
for (int i = 0; i < n; ++i)
arr[i] = Integer.parseInt(nextToken()) - 1;
return arr;
}
private long[] nla(int n) throws IOException {
long arr[] = new long[n];
for (int i = 0; i < n; ++i)
arr[i] = Long.parseLong(nextToken());
return arr;
}
private void pr(Object o) {
pw.print(o);
}
private void prln(Object o) {
pw.println(o);
}
private void prln() {
pw.println();
}
int ni() throws IOException {
return Integer.parseInt(nextToken());
}
long nl() throws IOException {
return Long.parseLong(nextToken());
}
double nd() throws IOException {
return Double.parseDouble(nextToken());
}
private String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(br.readLine());
}
return tokenizer.nextToken();
}
// private void qsort(int a[]) {
// Random rand = new Random(271828182l);
// qsort(a, 0, a.length, rand);
// }
//
// private void qsort(int a[], int l, int r, Random rand) {
// if (r - l <= 1)
// return;
//
// if (r - l == 2) {
// if (a[r - 1] < a[l]) {
// int t = a[r - 1];
// a[r - 1] = a[l];
// a[l] = t;
// }
//
// return;
// }
//
// int x = a[rand.nextInt(r - l) + l];
// int i = l, j = r - 1;
// 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;
// }
// }
//
// qsort(a, l, j + 1, rand);
// qsort(a, i, r, rand);
// }
private BufferedReader br;
private StringTokenizer tokenizer;
private PrintWriter pw;
private final boolean isFileIO = false;
} | logn | 287_B. Pipeline | CODEFORCES |
import java.util.*;
import java.math.*;
public class B2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
BigInteger n = new BigInteger(scan.next());
BigInteger k = new BigInteger(scan.next());
BigInteger a = k.subtract(bi(1));
BigInteger lim = k.multiply(a).divide(bi(2));
lim = lim.add(bi(1));
//System.out.println("lim: "+lim);
if (n.compareTo(lim)>0){
System.out.println(-1);
}
else {
if (n.equals(1)){
System.out.println(0);
}
else {
BigInteger remain2 = lim.subtract(n).add(bi(1));
remain2 = remain2.multiply(bi(2));
//System.out.println(remain2);
double temp = remain2.doubleValue();
//System.out.println(temp);
long flr = (long)Math.sqrt(temp);
//System.out.println(flr);
BigInteger flr2 = bi(flr);
BigInteger rnd2 = remain2.subtract(flr2.multiply(flr2));
long rnd = remain2.longValue()-flr*flr;
//System.out.println("rnd "+rnd);
/*
if (rnd<=flr){
System.out.println(k.intValue()-flr);
}
else {
System.out.println(k.intValue()-(flr+1));
}
*/
if (rnd2.compareTo(flr2)<=0){
System.out.println(k.subtract(flr2) );
}
else {
System.out.println(k.subtract(flr2.add(bi(1) ) ) );
}
}
}
}
public static BigInteger bi(int n1){
return new BigInteger(""+n1);
}
public static BigInteger bi(long n1){
return new BigInteger(""+n1);
}
}
| logn | 287_B. Pipeline | 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.