exec_outcome stringclasses 1 value | code_uid stringlengths 32 32 | file_name stringclasses 111 values | prob_desc_created_at stringlengths 10 10 | prob_desc_description stringlengths 63 3.8k | prob_desc_memory_limit stringclasses 18 values | source_code stringlengths 117 65.5k | lang_cluster stringclasses 1 value | prob_desc_sample_inputs stringlengths 2 802 | prob_desc_time_limit stringclasses 27 values | prob_desc_sample_outputs stringlengths 2 796 | prob_desc_notes stringlengths 4 3k ⌀ | lang stringclasses 5 values | prob_desc_input_from stringclasses 3 values | tags listlengths 0 11 | src_uid stringlengths 32 32 | prob_desc_input_spec stringlengths 28 2.37k ⌀ | difficulty int64 -1 3.5k ⌀ | prob_desc_output_spec stringlengths 17 1.47k ⌀ | prob_desc_output_to stringclasses 3 values | hidden_unit_tests stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED | 659584700e80f3e5e87c13609545655a | train_003.jsonl | 1365348600 | There are n lights aligned in a row. These lights are numbered 1 to n from left to right. Initially some of the lights are switched on. Shaass wants to switch all the lights on. At each step he can switch a light on (this light should be switched off at that moment) if there's at least one adjacent light which is already switched on. He knows the initial state of lights and he's wondering how many different ways there exist to switch all the lights on. Please find the required number of ways modulo 1000000007 (109 + 7). | 256 megabytes | import java.io.File;
import java.io.FileNotFoundException;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Random;
import java.util.Scanner;
public class CF178D2C implements CodeforcesSolver {
long mod = 1000000007;
CombinationNumberTableWithModular<Int64> cn = new CombinationNumberTableWithModular<Int64>(Int64.ONE, new Int64(mod), new MemoizationFactory(new JavaHashMapFactory()));
Sort sort = new QuickSort();
public void solve(Scanner in) {
int n = in.nextInt();
int m = in.nextInt();
DynamicArray<Integer> initialLights = DynamicArray.create();
for(int i : Range.get(m))
initialLights.addToLast(in.nextInt());
sort.sort(initialLights);
DynamicArray<Integer> spaces = extractSpaces(n, initialLights);
long res = 1;
int remain = n-m;
for(int size : spaces) {
long combi = cn.calc(remain, size).toPrimitive();
res = (res * combi) % mod;
remain -= size;
}
for(int i : Range.get(1, m-1))
for(int j : Range.get(spaces.get(i)-1))
res = (res * 2) % mod;
System.out.println(res);
}
private DynamicArray<Integer> extractSpaces(int n, DynamicArray<Integer> initialLights) {
DynamicArray<Integer> r = DynamicArray.create();
int start = 1;
for(int p : initialLights) {
r.addToLast(p-start);
start = p+1;
}
r.addToLast(n-start+1);
return r;
}
public static void main(String[] args) throws Exception {
CodeforcesSolverLauncher.launch(new CodeforcesSolverFactory() {
public CodeforcesSolver create() {
return new CF178D2C();
}
}, "C1.in", "C2.in", "C3.in");
}
}
class MemoizationFactory {
private MapFactory mapFactory;
public MemoizationFactory(MapFactory mapFactory) {
this.mapFactory = mapFactory;
}
public <I, V> Memoization<I, V> create(ItemCalculator<I, V> calc) {
return new Memoization<I, V>(mapFactory, calc);
}
}
interface MapFactory {
<K,V> Map<K,V> create();
}
interface Map<K, V> extends Container<Entry<K, V>> {
void clear();
void put(K key, V value);
void remove(K key);
boolean containsKey(K key);
V get(K key);
Iterable<V> values();
Iterable<K> keys();
}
interface Container<T> extends Iterable<T> {
int size();
boolean isEmpty();
}
interface Entry<K, V> {
K getKey();
V getValue();
void setValue(V v);
}
interface ItemCalculator<I, V> {
V calc(I index, SubItem<I, V> sub);
}
interface SubItem<I, V> {
V get(I index);
}
class Memoization<I, V> {
private ItemCalculator<I, V> calc;
private Map<I, V> table;
// TODO factory�� ��Ŭ������ ����.
Memoization(MapFactory mapFactory, ItemCalculator<I, V> calc) {
this.calc = calc;
this.table = mapFactory.create();
}
public V get(I index) {
V v = table.get(index);
if(v == null) {
v = calc.calc(index, subItem);
table.put(index, v);
}
return v;
}
private SubItem<I, V> subItem = new SubItem<I, V>() {
public V get(I index) {
return Memoization.this.get(index);
}
};
}
interface CodeforcesSolver {
void solve(Scanner in);
}
interface CodeforcesSolverFactory {
CodeforcesSolver create();
}
class CodeforcesSolverLauncher {
public static void launch(CodeforcesSolverFactory factory, String... inputFilePath) throws FileNotFoundException {
if(System.getProperty("ONLINE_JUDGE", "false").equals("true")) {
factory.create().solve(new Scanner(System.in));
} else {
for(String path : inputFilePath) {
factory.create().solve(new Scanner(new File(path)));
System.out.println();
}
}
}
}
class Range {
public static Iterable<Integer> get(int len) {
return IntSequenceIterable.create(0, 1, len);
}
public static Iterable<Integer> get(int from, int size) {
return IntSequenceIterable.create(from, 1, size);
}
}
class IntSequenceIterable {
public static Iterable<Integer> create(final int from, final int step, final int size) {
return new Iterable<Integer>() {
public Iterator<Integer> iterator() {
return new AbstractIterator<Integer>() {
int nextIndex = 0;
int nextValue = from;
public boolean hasNext() {
return nextIndex < size;
}
public Integer next() {
int r = nextValue;
nextIndex++;
nextValue += step;
return r;
}
};
}
};
}
}
abstract class AbstractIterator<T> implements Iterator<T> {
public final void remove() {
throw new UnsupportedOperationException();
}
}
class DynamicArray<T> extends AbstractReadableArray<T> implements StaticArray<T> {
public static <T> DynamicArray<T> create() {
return new DynamicArray<T>();
}
private T[] a;
private int asize;
@SuppressWarnings("unchecked")
private void init(int cap) {
asize = 0;
a = (T[])new Object[Math.max(1, cap)];
}
public DynamicArray() {
init(1);
}
public DynamicArray(int initialCapacity) {
init(initialCapacity);
}
public T get(int index) {
return a[index];
}
public void set(int index, T value) {
a[index] = value;
}
public int size() {
return asize;
}
public void clear() {
asize = 0;
}
@SuppressWarnings("unchecked")
public void reserve(int size) {
if(a.length < size) {
T[] ta = (T[])new Object[size];
for(int i=0;i<a.length;i++)
ta[i] = a[i];
a = ta;
}
}
@SuppressWarnings("unchecked")
public void addToLast(T value) {
if(a.length == asize) {
T[] ta = (T[])new Object[asize*2];
for(int i=0;i<asize;i++)
ta[i] = a[i];
a =ta;
}
a[asize++] = value;
}
public void addToLastAll(Iterable<? extends T> values) {
for(T v : values)
addToLast(v);
}
public T removeLast() {
T r = last();
a[--asize] = null;
return r;
}
public boolean equals(Object obj) {
return StrictEqualityChecker.isEquals(this, obj, new EqualityChecker<DynamicArray<T>>() {
public boolean isEquals(DynamicArray<T> o1, DynamicArray<T> o2) {
if(o1.size() != o2.size())
return false;
for(int i=0;i<o1.size();i++)
if(!o1.get(i).equals(o2.get(i)))
return false;
return true;
}
});
}
public int hashCode() {
int r = 0;
for(int i=0;i<size();i++)
r ^= Int32Hash.hash(get(i).hashCode());
return r;
}
}
interface EqualityChecker<T> {
boolean isEquals(T o1, T o2);
}
class Int32Hash {
public static int hash(int key) {
key = ~key + (key << 15); // key = (key << 15) - key - 1;
key = key ^ (key >>> 12);
key = key + (key << 2);
key = key ^ (key >>> 4);
key = key * 2057; // key = (key + (key << 3)) + (key << 11);
key = key ^ (key >>> 16);
return key;
}
}
class StrictEqualityChecker {
@SuppressWarnings("unchecked")
public static <T> boolean isEquals(T me, Object you, EqualityChecker<T> ec) {
if(me == you)
return true;
if(you == null)
return false;
if(you.getClass() != me.getClass())
return false;
return ec.isEquals(me, (T)you);
}
}
abstract class AbstractReadableArray<T> extends AbstractContainer<T> implements ReadableArray<T> {
public final boolean isEmpty() {
return size() == 0;
}
public final T last() {
return get(size()-1);
}
public final T first() {
return get(0);
}
public final Iterator<T> iterator() {
return new AbstractIterator<T>() {
int p = 0;
public boolean hasNext() {
return p < size();
}
public T next() {
return get(p++);
}
};
}
}
abstract class AbstractContainer<T> implements Container<T> {
public final String toString() {
StringBuilder sb = new StringBuilder();
sb.append('(');
boolean first = true;
for(T v : this) {
if(first)
first = false;
else
sb.append(',');
sb.append(v);
}
sb.append(')');
return sb.toString();
}
}
interface ReadableArray<T> extends Container<T> {
T get(int index);
T last();
T first();
}
interface StaticArray<T> extends ReadableArray<T>{
void set(int index, T value);
}
class JavaHashMapFactory implements MapFactory {
public <K, V> Map<K, V> create() {
return new MapWrapperForJavaMap<K, V>(new HashMap<K, V>());
}
}
class MapWrapperForJavaMap<K, V> implements Map<K, V> {
private final java.util.Map<K,V> map;
public MapWrapperForJavaMap(java.util.Map<K,V> map) {
this.map = map;
}
public boolean containsKey(K key) {
return map.containsKey(key);
}
public V get(K key) {
return map.get(key);
}
public Iterable<K> keys() {
return map.keySet();
}
public void put(K key, V value) {
map.put(key, value);
}
public Iterable<V> values() {
return map.values();
}
public void clear() {
map.clear();
}
public boolean isEmpty() {
return map.isEmpty();
}
public Iterator<Entry<K, V>> iterator() {
return ConvertedDataIterator.create(map.entrySet().iterator(), new DataConverter<java.util.Map.Entry<K,V>, Entry<K,V>>() {
public Entry<K, V> convert(java.util.Map.Entry<K, V> e) {
return new EntryWrapper<K, V>(e);
}
});
}
public int size() {
return map.size();
}
public void remove(K key) {
map.remove(key);
}
public String toString() {
return map.toString();
}
private static class EntryWrapper<K, V> implements Entry<K, V>, EqualityChecker<EntryWrapper<K,V>> {
private java.util.Map.Entry<K, V> e;
private EntryWrapper(java.util.Map.Entry<K, V> e) {
this.e = e;
}
public K getKey() {
return e.getKey();
}
public V getValue() {
return e.getValue();
}
public void setValue(V v) {
e.setValue(v);
}
public boolean equals(Object obj) {
return StrictEqualityChecker.isEquals(this, obj, this);
}
public boolean isEquals(EntryWrapper<K, V> o1, EntryWrapper<K, V> o2) {
return o1.getKey().equals(o2.getKey()) && o1.getValue().equals(o2.getValue());
}
public int hashCode() {
return PairHash.hash(getKey().hashCode(), getValue().hashCode());
}
}
}
class ConvertedDataIterator {
public static <T1, T2> Iterator<T2> create(final Iterator<T1> outerIterator, final DataConverter<T1, T2> extractor) {
return new AbstractIterator<T2>() {
public boolean hasNext() {
return outerIterator.hasNext();
}
public T2 next() {
return extractor.convert(outerIterator.next());
}
};
}
}
interface DataConverter<T1, T2> {
T2 convert(T1 v);
}
class PairHash {
public static int hash(int h1, int h2) {
return Int64Hash.hash6432shift((((long) h1) << 32) | h2);
}
}
class Int64Hash {
public static int hash6432shift(long key) {
// from http://www.concentric.net/~ttwang/tech/inthash.htm
key = (~key) + (key << 18); // key = (key << 18) - key - 1;
key = key ^ (key >>> 31);
key = key * 21; // key = (key + (key << 2)) + (key << 4);
key = key ^ (key >>> 11);
key = key + (key << 6);
key = key ^ (key >>> 22);
return (int) key;
}
}
class CombinationNumberTableWithModular<T extends Int<T>> {
private Memoization<Index2D, T> mem;
public CombinationNumberTableWithModular(final T one, final T mod, MemoizationFactory mf) {
mem = mf.create(new ItemCalculator<Index2D, T>() {
public T calc(Index2D index, SubItem<Index2D, T> sub) {
int a = index.i1;
int b = index.i2;
if(b==0 || a==b) {
return one;
} else {
T sub1 = sub.get(new Index2D(a-1,b-1));
T sub2 = sub.get(new Index2D(a-1,b));
return sub1.plus(sub2).mod(mod);
}
}
});
}
public T calc(int a, int b) {
if(b > a/2)
return calc(a, a-b);
return mem.get(new Index2D(a,b));
}
}
class Index2D implements EqualityChecker<Index2D>{
public final int i1;
public final int i2;
public Index2D(int i, int j) {
this.i1 = i;
this.i2 = j;
}
public boolean equals(Object obj) {
return StrictEqualityChecker.isEquals(this, obj, this);
}
public boolean isEquals(Index2D o1, Index2D o2) {
return o1.i1 == o2.i1 && o1.i2 == o2.i2;
}
public int hashCode() {
return PairHash.hash(i1, i2);
}
public String toString() {
return "("+i1+","+i2 +")";
}
}
interface Int<T extends Int<T>> extends Multiplicative<T> {
T mod(T v);
T floorDivide(T v);
double toDouble();
}
interface Multiplicative<T extends Multiplicative<T>> extends Additive<T> { // �̸��ٲٱ� Multipliable
T times(T a);
T getOne();
T get(int v);
boolean isOne();
}
interface Additive<T extends Additive<T>> extends Number<T> { // TODO �̸��ٲٱ� Addable
T plus(T v);
T minus(T v);
T getAddInvert();
T getZero();
boolean isPositive();
boolean isZero();
boolean isNegative();
int getSign();
}
interface Number<T> extends Comparable<T> {
}
class Int64 implements Int<Int64>, EqualityChecker<Int64> {
// TODO ���ڴ�� valueOf �����ϱ�. ij�ñ���߰�.
private final long v;
public Int64(long v) {
this.v = v;
}
public Int64 plus(Int64 t) {
return new Int64(v + t.v);
}
public Int64 minus(Int64 t) {
return new Int64(v - t.v);
}
public long toPrimitive() {
return v;
}
public Int64 getAddInvert() {
return new Int64(-v);
}
public int compareTo(Int64 o) {
if(v > o.v)
return 1;
else if(v < o.v)
return -1;
return 0;
}
public String toString() {
return Long.toString(v);
}
public Int64 getZero() {
return ZERO;
}
public Int64 getOne() {
return ONE;
}
public boolean isOne() {
return v == 1;
}
public Int64 times(Int64 a) {
return new Int64(v * a.v);
}
public Int64 floorDivide(Int64 o) {
return new Int64(v / o.v);
}
public Int64 mod(Int64 o) {
return new Int64(v % o.v);
}
public double toDouble() {
return v;
}
public boolean equals(Object obj) {
return StrictEqualityChecker.isEquals(this, obj, this);
}
public boolean isEquals(Int64 o1, Int64 o2) {
return o1.v == o2.v;
}
public int hashCode() {
return Int64Hash.hash6432shift(v);
}
public int getSign() {
if(v > 0)
return 1;
else if(v < 0)
return -1;
return 0;
}
public final Int64 get(int v) {
return new Int64(v);
}
public final boolean isPositive() {
return v > 0;
}
public final boolean isNegative() {
return v < 0;
}
public final boolean isZero() {
return v == 0;
}
static final public Int64 ZERO = new Int64(0);
static final public Int64 ONE = new Int64(1);
}
class QuickSort extends AbstractSort {
private static Random RANDOM = new Random();
// TODO �ʹ� ������� ���Ʈ�� ����.
public <T> void sort(StaticArray<T> list, int start, int end, Comparator<T> comparator) {
if(start < end) {
ArraySwapper.swap(list, start, RANDOM.nextInt(end-start) + start + 1);
int pos = start;
for(int i=start+1;i<=end;i++) {
int c = comparator.compare(list.get(i), list.get(start));
if(c < 0 || c == 0 && i%2==0)
ArraySwapper.swap(list, i,++pos);
}
ArraySwapper.swap(list, start, pos);
sort(list, start,pos-1, comparator);
sort(list, pos+1, end, comparator);
}
}
}
class ArraySwapper {
public static <T> void swap(StaticArray<T> a, int p1, int p2) {
T t = a.get(p1);
a.set(p1, a.get(p2));
a.set(p2, t);
}
public static <T> void swap(T[] a, int p1, int p2) {
swap(new StaticArrayUsingArray<T>(a), p1, p2);
}
}
class StaticArrayUsingArray<T> extends AbstractReadableArray<T> implements StaticArray<T> {
final private T[] a;
final private int start;
final private int end;
public StaticArrayUsingArray(T[] a) {
this.a = a;
start = 0;
end = a.length-1;
}
public StaticArrayUsingArray(T[] a, int start, int end) {
this.a = a;
this.start = start;
this.end = end;
}
public StaticArrayUsingArray(T[] a, int n) {
this.a = a;
this.start = 0;
this.end = n-1;
}
public T get(int arg0) {
return a[start+arg0];
}
public void set(int arg0, T arg1) {
a[start+arg0] = arg1;
}
public int size() {
return end-start+1;
}
}
abstract class AbstractSort implements Sort {
// TODO �̷���Ӱ�� ��ֹ���..
public abstract <T> void sort(StaticArray<T> a, int start, int end, Comparator<T> comparator);
public <T extends Comparable<T>> void sort(StaticArray<T> a) {
sort(a, 0, a.size()-1);
}
public <T> void sort(StaticArray<T> a, Comparator<T> comparator) {
sort(a, 0, a.size()-1, comparator);
}
public <T extends Comparable<T>> void sort(StaticArray<T> a, int start, int end) {
sort(a, start, end, new DefaultComparator<T>());
}
}
class DefaultComparator<T> implements Comparator<T> {
// TODO extends Comparable<T>�� �°� ���ڴ�.
@SuppressWarnings("unchecked")
public int compare(T arg0, T arg1) {
return ((Comparable<T>)arg0).compareTo(arg1);
}
}
interface Sort {
// TODO �ھ ����� ��ƿ�� ����
<T> void sort(StaticArray<T> a, int start, int end, Comparator<T> comparator);
<T> void sort(StaticArray<T> a, Comparator<T> comparator);
<T extends Comparable<T>> void sort(StaticArray<T> a);
<T extends Comparable<T>> void sort(StaticArray<T> a, int start, int end);
}
| Java | ["3 1\n1", "4 2\n1 4", "11 2\n4 8"] | 1 second | ["1", "2", "6720"] | null | Java 7 | standard input | [
"combinatorics",
"number theory"
] | 14da0cdf2939c796704ec548f49efb87 | The first line of the input contains two integers n and m where n is the number of lights in the sequence and m is the number of lights which are initially switched on, (1 ≤ n ≤ 1000, 1 ≤ m ≤ n). The second line contains m distinct integers, each between 1 to n inclusive, denoting the indices of lights which are initially switched on. | 1,900 | In the only line of the output print the number of different possible ways to switch on all the lights modulo 1000000007 (109 + 7). | standard output | |
PASSED | b5bd236ea94546687c6fe9e959dd84b2 | train_003.jsonl | 1365348600 | There are n lights aligned in a row. These lights are numbered 1 to n from left to right. Initially some of the lights are switched on. Shaass wants to switch all the lights on. At each step he can switch a light on (this light should be switched off at that moment) if there's at least one adjacent light which is already switched on. He knows the initial state of lights and he's wondering how many different ways there exist to switch all the lights on. Please find the required number of ways modulo 1000000007 (109 + 7). | 256 megabytes | import java.io.File;
import java.io.FileNotFoundException;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Random;
import java.util.Scanner;
public class CF178D2C implements CodeforcesSolver {
long M = 1000000007;
CombinationNumberTableWithModular<Int64> cn = new CombinationNumberTableWithModular<Int64>(Int64.ONE, new Int64(M), new MemoizationFactory(new JavaHashMapFactory()));
Sort sort = new QuickSort();
public void solve(Scanner in) {
int n = in.nextInt();
int m = in.nextInt();
DynamicArray<Integer> a = DynamicArray.create();
for(int i : Range.get(m))
a.addToLast(in.nextInt());
sort.sort(a);
DynamicArray<Integer> sizes = DynamicArray.create();
int pre = 1;
for(int p : a) {
sizes.addToLast(p-pre);
pre = p+1;
}
sizes.addToLast(n-pre+1);
long r = 1;
int remain = n-m;
for(int v : sizes) {
r = (r * cn.get(remain, v).toPrimitive()) % M;
remain -= v;
}
for(int i : Range.get(1, m-1))
for(int j : Range.get(sizes.get(i)-1))
r = (r * 2) % M;
System.out.println(r);
}
public static void main(String[] args) throws Exception {
CodeforcesSolverLauncher.launch(new CodeforcesSolverFactory() {
public CodeforcesSolver create() {
return new CF178D2C();
}
}, "C1.in", "C2.in", "C3.in");
}
}
class MemoizationFactory {
private MapFactory mapFactory;
public MemoizationFactory(MapFactory mapFactory) {
this.mapFactory = mapFactory;
}
public <I, V> Memoization<I, V> create(ItemCalculator<I, V> calc) {
return new Memoization<I, V>(mapFactory, calc);
}
}
interface MapFactory {
<K,V> Map<K,V> create();
}
interface Map<K, V> extends Container<Entry<K, V>> {
void clear();
void put(K key, V value);
void remove(K key);
boolean containsKey(K key);
V get(K key);
Iterable<V> values();
Iterable<K> keys();
}
interface Container<T> extends Iterable<T> {
int size();
boolean isEmpty();
}
interface Entry<K, V> {
K getKey();
V getValue();
void setValue(V v);
}
interface ItemCalculator<I, V> {
V calc(I index, SubItem<I, V> sub);
}
interface SubItem<I, V> {
V get(I index);
}
class Memoization<I, V> {
private ItemCalculator<I, V> calc;
private Map<I, V> table;
// TODO factory? ?????? ??.
Memoization(MapFactory mapFactory, ItemCalculator<I, V> calc) {
this.calc = calc;
this.table = mapFactory.create();
}
public V get(I index) {
V v = table.get(index);
if(v == null) {
v = calc.calc(index, subItem);
table.put(index, v);
}
return v;
}
private SubItem<I, V> subItem = new SubItem<I, V>() {
public V get(I index) {
return Memoization.this.get(index);
}
};
}
interface CodeforcesSolver {
void solve(Scanner in);
}
interface CodeforcesSolverFactory {
CodeforcesSolver create();
}
class CodeforcesSolverLauncher {
public static void launch(CodeforcesSolverFactory factory, String... inputFilePath) throws FileNotFoundException {
if(System.getProperty("ONLINE_JUDGE", "false").equals("true")) {
factory.create().solve(new Scanner(System.in));
} else {
for(String path : inputFilePath) {
factory.create().solve(new Scanner(new File(path)));
System.out.println();
}
}
}
}
class Range {
public static Iterable<Integer> get(int len) {
return IntSequenceIterable.create(0, 1, len);
}
public static Iterable<Integer> get(int from, int size) {
return IntSequenceIterable.create(from, 1, size);
}
}
class IntSequenceIterable {
public static Iterable<Integer> create(final int from, final int step, final int size) {
return new Iterable<Integer>() {
public Iterator<Integer> iterator() {
return new AbstractIterator<Integer>() {
int nextIndex = 0;
int nextValue = from;
public boolean hasNext() {
return nextIndex < size;
}
public Integer next() {
int r = nextValue;
nextIndex++;
nextValue += step;
return r;
}
};
}
};
}
}
abstract class AbstractIterator<T> implements Iterator<T> {
public final void remove() {
throw new UnsupportedOperationException();
}
}
class DynamicArray<T> extends AbstractReadableArray<T> implements StaticArray<T> {
public static <T> DynamicArray<T> create() {
return new DynamicArray<T>();
}
private T[] a;
private int asize;
@SuppressWarnings("unchecked")
private void init(int cap) {
asize = 0;
a = (T[])new Object[Math.max(1, cap)];
}
public DynamicArray() {
init(1);
}
public DynamicArray(int initialCapacity) {
init(initialCapacity);
}
public T get(int index) {
return a[index];
}
public void set(int index, T value) {
a[index] = value;
}
public int size() {
return asize;
}
public void clear() {
asize = 0;
}
@SuppressWarnings("unchecked")
public void reserve(int size) {
if(a.length < size) {
T[] ta = (T[])new Object[size];
for(int i=0;i<a.length;i++)
ta[i] = a[i];
a = ta;
}
}
@SuppressWarnings("unchecked")
public void addToLast(T value) {
if(a.length == asize) {
T[] ta = (T[])new Object[asize*2];
for(int i=0;i<asize;i++)
ta[i] = a[i];
a =ta;
}
a[asize++] = value;
}
public void addToLastAll(Iterable<? extends T> values) {
for(T v : values)
addToLast(v);
}
public T removeLast() {
T r = last();
a[--asize] = null;
return r;
}
public boolean equals(Object obj) {
return StrictEqualityChecker.isEquals(this, obj, new EqualityChecker<DynamicArray<T>>() {
public boolean isEquals(DynamicArray<T> o1, DynamicArray<T> o2) {
if(o1.size() != o2.size())
return false;
for(int i=0;i<o1.size();i++)
if(!o1.get(i).equals(o2.get(i)))
return false;
return true;
}
});
}
public int hashCode() {
int r = 0;
for(int i=0;i<size();i++)
r ^= Int32Hash.hash(get(i).hashCode());
return r;
}
}
interface EqualityChecker<T> {
boolean isEquals(T o1, T o2);
}
class Int32Hash {
public static int hash(int key) {
key = ~key + (key << 15); // key = (key << 15) - key - 1;
key = key ^ (key >>> 12);
key = key + (key << 2);
key = key ^ (key >>> 4);
key = key * 2057; // key = (key + (key << 3)) + (key << 11);
key = key ^ (key >>> 16);
return key;
}
}
class StrictEqualityChecker {
@SuppressWarnings("unchecked")
public static <T> boolean isEquals(T me, Object you, EqualityChecker<T> ec) {
if(me == you)
return true;
if(you == null)
return false;
if(you.getClass() != me.getClass())
return false;
return ec.isEquals(me, (T)you);
}
}
abstract class AbstractReadableArray<T> extends AbstractContainer<T> implements ReadableArray<T> {
public final boolean isEmpty() {
return size() == 0;
}
public final T last() {
return get(size()-1);
}
public final T first() {
return get(0);
}
public final Iterator<T> iterator() {
return new AbstractIterator<T>() {
int p = 0;
public boolean hasNext() {
return p < size();
}
public T next() {
return get(p++);
}
};
}
}
abstract class AbstractContainer<T> implements Container<T> {
public final String toString() {
StringBuilder sb = new StringBuilder();
sb.append('(');
boolean first = true;
for(T v : this) {
if(first)
first = false;
else
sb.append(',');
sb.append(v);
}
sb.append(')');
return sb.toString();
}
}
interface ReadableArray<T> extends Container<T> {
T get(int index);
T last();
T first();
}
interface StaticArray<T> extends ReadableArray<T>{
void set(int index, T value);
}
class JavaHashMapFactory implements MapFactory {
public <K, V> Map<K, V> create() {
return new MapWrapperForJavaMap<K, V>(new HashMap<K, V>());
}
}
class MapWrapperForJavaMap<K, V> implements Map<K, V> {
private final java.util.Map<K,V> map;
public MapWrapperForJavaMap(java.util.Map<K,V> map) {
this.map = map;
}
public boolean containsKey(K key) {
return map.containsKey(key);
}
public V get(K key) {
return map.get(key);
}
public Iterable<K> keys() {
return map.keySet();
}
public void put(K key, V value) {
map.put(key, value);
}
public Iterable<V> values() {
return map.values();
}
public void clear() {
map.clear();
}
public boolean isEmpty() {
return map.isEmpty();
}
public Iterator<Entry<K, V>> iterator() {
return ConvertedDataIterator.create(map.entrySet().iterator(), new DataConverter<java.util.Map.Entry<K,V>, Entry<K,V>>() {
public Entry<K, V> convert(java.util.Map.Entry<K, V> e) {
return new EntryWrapper<K, V>(e);
}
});
}
public int size() {
return map.size();
}
public void remove(K key) {
map.remove(key);
}
public String toString() {
return map.toString();
}
private static class EntryWrapper<K, V> implements Entry<K, V>, EqualityChecker<EntryWrapper<K,V>> {
private java.util.Map.Entry<K, V> e;
private EntryWrapper(java.util.Map.Entry<K, V> e) {
this.e = e;
}
public K getKey() {
return e.getKey();
}
public V getValue() {
return e.getValue();
}
public void setValue(V v) {
e.setValue(v);
}
public boolean equals(Object obj) {
return StrictEqualityChecker.isEquals(this, obj, this);
}
public boolean isEquals(EntryWrapper<K, V> o1, EntryWrapper<K, V> o2) {
return o1.getKey().equals(o2.getKey()) && o1.getValue().equals(o2.getValue());
}
public int hashCode() {
return PairHash.hash(getKey().hashCode(), getValue().hashCode());
}
}
}
class ConvertedDataIterator {
public static <T1, T2> Iterator<T2> create(final Iterator<T1> outerIterator, final DataConverter<T1, T2> extractor) {
return new AbstractIterator<T2>() {
public boolean hasNext() {
return outerIterator.hasNext();
}
public T2 next() {
return extractor.convert(outerIterator.next());
}
};
}
}
interface DataConverter<T1, T2> {
T2 convert(T1 v);
}
class PairHash {
public static int hash(int h1, int h2) {
return Int64Hash.hash6432shift((((long) h1) << 32) | h2);
}
}
class Int64Hash {
public static int hash6432shift(long key) {
// from http://www.concentric.net/~ttwang/tech/inthash.htm
key = (~key) + (key << 18); // key = (key << 18) - key - 1;
key = key ^ (key >>> 31);
key = key * 21; // key = (key + (key << 2)) + (key << 4);
key = key ^ (key >>> 11);
key = key + (key << 6);
key = key ^ (key >>> 22);
return (int) key;
}
}
class CombinationNumberTableWithModular<T extends Int<T>> {
private Memoization<Index2D, T> mem;
public CombinationNumberTableWithModular(final T one, final T mod, MemoizationFactory mf) {
mem = mf.create(new ItemCalculator<Index2D, T>() {
public T calc(Index2D index, SubItem<Index2D, T> sub) {
int a = index.i1;
int b = index.i2;
if(b==0 || a==b) {
return one;
} else {
T sub1 = sub.get(new Index2D(a-1,b-1));
T sub2 = sub.get(new Index2D(a-1,b));
return sub1.plus(sub2).mod(mod);
}
}
});
}
public T get(int a, int b) {
if(b > a/2)
return get(a, a-b);
return mem.get(new Index2D(a,b));
}
}
class Index2D implements EqualityChecker<Index2D>{
public final int i1;
public final int i2;
public Index2D(int i, int j) {
this.i1 = i;
this.i2 = j;
}
public boolean equals(Object obj) {
return StrictEqualityChecker.isEquals(this, obj, this);
}
public boolean isEquals(Index2D o1, Index2D o2) {
return o1.i1 == o2.i1 && o1.i2 == o2.i2;
}
public int hashCode() {
return PairHash.hash(i1, i2);
}
public String toString() {
return "("+i1+","+i2 +")";
}
}
interface Int<T extends Int<T>> extends Multiplicative<T> {
T mod(T v);
T floorDivide(T v);
double toDouble();
}
interface Multiplicative<T extends Multiplicative<T>> extends Additive<T> { // ????? Multipliable
T times(T a);
T getOne();
T get(int v);
boolean isOne();
}
interface Additive<T extends Additive<T>> extends Number<T> { // TODO ????? Addable
T plus(T v);
T minus(T v);
T getAddInvert();
T getZero();
boolean isPositive();
boolean isZero();
boolean isNegative();
int getSign();
}
interface Number<T> extends Comparable<T> {
}
class Int64 implements Int<Int64>, EqualityChecker<Int64> {
// TODO ????? valueOf ????. ??????.
private final long v;
public Int64(long v) {
this.v = v;
}
public Int64 plus(Int64 t) {
return new Int64(v + t.v);
}
public Int64 minus(Int64 t) {
return new Int64(v - t.v);
}
public long toPrimitive() {
return v;
}
public Int64 getAddInvert() {
return new Int64(-v);
}
public int compareTo(Int64 o) {
if(v > o.v)
return 1;
else if(v < o.v)
return -1;
return 0;
}
public String toString() {
return Long.toString(v);
}
public Int64 getZero() {
return ZERO;
}
public Int64 getOne() {
return ONE;
}
public boolean isOne() {
return v == 1;
}
public Int64 times(Int64 a) {
return new Int64(v * a.v);
}
public Int64 floorDivide(Int64 o) {
return new Int64(v / o.v);
}
public Int64 mod(Int64 o) {
return new Int64(v % o.v);
}
public double toDouble() {
return v;
}
public boolean equals(Object obj) {
return StrictEqualityChecker.isEquals(this, obj, this);
}
public boolean isEquals(Int64 o1, Int64 o2) {
return o1.v == o2.v;
}
public int hashCode() {
return Int64Hash.hash6432shift(v);
}
public int getSign() {
if(v > 0)
return 1;
else if(v < 0)
return -1;
return 0;
}
public final Int64 get(int v) {
return new Int64(v);
}
public final boolean isPositive() {
return v > 0;
}
public final boolean isNegative() {
return v < 0;
}
public final boolean isZero() {
return v == 0;
}
static final public Int64 ZERO = new Int64(0);
static final public Int64 ONE = new Int64(1);
}
class QuickSort extends AbstractSort {
private static Random RANDOM = new Random();
// TODO ?? ???? ???? ??.
public <T> void sort(StaticArray<T> list, int start, int end, Comparator<T> comparator) {
if(start < end) {
ArraySwapper.swap(list, start, RANDOM.nextInt(end-start) + start + 1);
int pos = start;
for(int i=start+1;i<=end;i++) {
int c = comparator.compare(list.get(i), list.get(start));
if(c < 0 || c == 0 && i%2==0)
ArraySwapper.swap(list, i,++pos);
}
ArraySwapper.swap(list, start, pos);
sort(list, start,pos-1, comparator);
sort(list, pos+1, end, comparator);
}
}
}
class ArraySwapper {
public static <T> void swap(StaticArray<T> a, int p1, int p2) {
T t = a.get(p1);
a.set(p1, a.get(p2));
a.set(p2, t);
}
public static <T> void swap(T[] a, int p1, int p2) {
swap(new StaticArrayUsingArray<T>(a), p1, p2);
}
}
class StaticArrayUsingArray<T> extends AbstractReadableArray<T> implements StaticArray<T> {
final private T[] a;
final private int start;
final private int end;
public StaticArrayUsingArray(T[] a) {
this.a = a;
start = 0;
end = a.length-1;
}
public StaticArrayUsingArray(T[] a, int start, int end) {
this.a = a;
this.start = start;
this.end = end;
}
public StaticArrayUsingArray(T[] a, int n) {
this.a = a;
this.start = 0;
this.end = n-1;
}
public T get(int arg0) {
return a[start+arg0];
}
public void set(int arg0, T arg1) {
a[start+arg0] = arg1;
}
public int size() {
return end-start+1;
}
}
abstract class AbstractSort implements Sort {
// TODO ?????? ????..
public abstract <T> void sort(StaticArray<T> a, int start, int end, Comparator<T> comparator);
public <T extends Comparable<T>> void sort(StaticArray<T> a) {
sort(a, 0, a.size()-1);
}
public <T> void sort(StaticArray<T> a, Comparator<T> comparator) {
sort(a, 0, a.size()-1, comparator);
}
public <T extends Comparable<T>> void sort(StaticArray<T> a, int start, int end) {
sort(a, start, end, new DefaultComparator<T>());
}
}
class DefaultComparator<T> implements Comparator<T> {
// TODO extends Comparable<T>? ??? ???.
@SuppressWarnings("unchecked")
public int compare(T arg0, T arg1) {
return ((Comparable<T>)arg0).compareTo(arg1);
}
}
interface Sort {
// TODO ??? ??? ??? ??
<T> void sort(StaticArray<T> a, int start, int end, Comparator<T> comparator);
<T> void sort(StaticArray<T> a, Comparator<T> comparator);
<T extends Comparable<T>> void sort(StaticArray<T> a);
<T extends Comparable<T>> void sort(StaticArray<T> a, int start, int end);
}
| Java | ["3 1\n1", "4 2\n1 4", "11 2\n4 8"] | 1 second | ["1", "2", "6720"] | null | Java 7 | standard input | [
"combinatorics",
"number theory"
] | 14da0cdf2939c796704ec548f49efb87 | The first line of the input contains two integers n and m where n is the number of lights in the sequence and m is the number of lights which are initially switched on, (1 ≤ n ≤ 1000, 1 ≤ m ≤ n). The second line contains m distinct integers, each between 1 to n inclusive, denoting the indices of lights which are initially switched on. | 1,900 | In the only line of the output print the number of different possible ways to switch on all the lights modulo 1000000007 (109 + 7). | standard output | |
PASSED | be724b6f76fec186734b7cc8d647a8bb | train_003.jsonl | 1365348600 | There are n lights aligned in a row. These lights are numbered 1 to n from left to right. Initially some of the lights are switched on. Shaass wants to switch all the lights on. At each step he can switch a light on (this light should be switched off at that moment) if there's at least one adjacent light which is already switched on. He knows the initial state of lights and he's wondering how many different ways there exist to switch all the lights on. Please find the required number of ways modulo 1000000007 (109 + 7). | 256 megabytes | import java.io.File;
import java.io.FileNotFoundException;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Random;
import java.util.Scanner;
public class CF178D2C implements CodeforcesSolver {
long M = 1000000007;
CombinationNumberTableWithModular<Int64> cn = new CombinationNumberTableWithModular<Int64>(Int64.ONE, new Int64(M), new MemoizationFactory(new JavaHashMapFactory()));
Sort sort = new QuickSort();
@Override
public void solve(Scanner in) {
int n = in.nextInt();
int m = in.nextInt();
DynamicArray<Integer> a = DynamicArray.create();
for(int i : Range.get(m))
a.addToLast(in.nextInt());
sort.sort(a);
DynamicArray<Integer> sizes = DynamicArray.create();
int pre = 1;
for(int p : a) {
sizes.addToLast(p-pre);
pre = p+1;
}
sizes.addToLast(n-pre+1);
long r = 1;
int remain = n-m;
for(int v : sizes) {
r = (r * cn.get(remain, v).toPrimitive()) % M;
remain -= v;
}
for(int i : Range.get(1, m-1))
for(int j : Range.get(sizes.get(i)-1))
r = (r * 2) % M;
System.out.println(r);
}
public static void main(String[] args) throws Exception {
CodeforcesSolverLauncher.launch(new CodeforcesSolverFactory() {
@Override
public CodeforcesSolver create() {
return new CF178D2C();
}
}, "C3.in");
}
}
class MemoizationFactory {
private MapFactory mapFactory;
public MemoizationFactory(MapFactory mapFactory) {
this.mapFactory = mapFactory;
}
public <I, V> Memoization<I, V> create(ItemCalculator<I, V> calc) {
return new Memoization<I, V>(mapFactory, calc);
}
}
interface MapFactory {
<K,V> Map<K,V> create();
}
interface Map<K, V> extends Container<Entry<K, V>> {
void clear();
void put(K key, V value);
void remove(K key);
boolean containsKey(K key);
V get(K key);
Iterable<V> values();
Iterable<K> keys();
}
interface Container<T> extends Iterable<T> {
int size();
boolean isEmpty();
}
interface Entry<K, V> {
K getKey();
V getValue();
void setValue(V v);
}
interface ItemCalculator<I, V> {
V calc(I index, SubItem<I, V> sub);
}
interface SubItem<I, V> {
V get(I index);
}
class Memoization<I, V> {
private ItemCalculator<I, V> calc;
private Map<I, V> table;
Memoization(MapFactory mapFactory, ItemCalculator<I, V> calc) {
this.calc = calc;
this.table = mapFactory.create();
}
public V get(I index) {
V v = table.get(index);
if(v == null) {
v = calc.calc(index, subItem);
table.put(index, v);
}
return v;
}
private SubItem<I, V> subItem = new SubItem<I, V>() {
public V get(I index) {
return Memoization.this.get(index);
}
};
}
interface CodeforcesSolver {
void solve(Scanner in);
}
interface CodeforcesSolverFactory {
CodeforcesSolver create();
}
class CodeforcesSolverLauncher {
public static void launch(CodeforcesSolverFactory factory, String... inputFilePath) throws FileNotFoundException {
if(System.getProperty("ONLINE_JUDGE", "false").equals("true")) {
factory.create().solve(new Scanner(System.in));
} else {
for(String path : inputFilePath) {
factory.create().solve(new Scanner(new File(path)));
System.out.println();
}
}
}
}
class Range {
public static Iterable<Integer> get(int len) {
return IntSequenceIterable.create(0, 1, len);
}
public static Iterable<Integer> get(int from, int size) {
return IntSequenceIterable.create(from, 1, size);
}
}
class IntSequenceIterable {
public static Iterable<Integer> create(final int from, final int step, final int size) {
return new Iterable<Integer>() {
@Override
public Iterator<Integer> iterator() {
return new AbstractIterator<Integer>() {
int nextIndex = 0;
int nextValue = from;
@Override
public boolean hasNext() {
return nextIndex < size;
}
@Override
public Integer next() {
int r = nextValue;
nextIndex++;
nextValue += step;
return r;
}
};
}
};
}
}
abstract class AbstractIterator<T> implements Iterator<T> {
@Override
public final void remove() {
throw new UnsupportedOperationException();
}
}
class DynamicArray<T> extends AbstractReadableArray<T> implements StaticArray<T> {
public static <T> DynamicArray<T> create() {
return new DynamicArray<T>();
}
private T[] a;
private int asize;
@SuppressWarnings("unchecked")
private void init(int cap) {
asize = 0;
a = (T[])new Object[Math.max(1, cap)];
}
public DynamicArray() {
init(1);
}
public DynamicArray(int initialCapacity) {
init(initialCapacity);
}
public T get(int index) {
return a[index];
}
public void set(int index, T value) {
a[index] = value;
}
public int size() {
return asize;
}
public void clear() {
asize = 0;
}
@SuppressWarnings("unchecked")
public void reserve(int size) {
if(a.length < size) {
T[] ta = (T[])new Object[size];
for(int i=0;i<a.length;i++)
ta[i] = a[i];
a = ta;
}
}
@SuppressWarnings("unchecked")
public void addToLast(T value) {
if(a.length == asize) {
T[] ta = (T[])new Object[asize*2];
for(int i=0;i<asize;i++)
ta[i] = a[i];
a =ta;
}
a[asize++] = value;
}
public void addToLastAll(Iterable<? extends T> values) {
for(T v : values)
addToLast(v);
}
public T removeLast() {
T r = last();
a[--asize] = null;
return r;
}
@Override
public boolean equals(Object obj) {
return StrictEqualityChecker.isEquals(this, obj, new EqualityChecker<DynamicArray<T>>() {
@Override
public boolean isEquals(DynamicArray<T> o1, DynamicArray<T> o2) {
if(o1.size() != o2.size())
return false;
for(int i=0;i<o1.size();i++)
if(!o1.get(i).equals(o2.get(i)))
return false;
return true;
}
});
}
@Override
public int hashCode() {
int r = 0;
for(int i=0;i<size();i++)
r ^= Int32Hash.hash(get(i).hashCode());
return r;
}
}
interface EqualityChecker<T> {
boolean isEquals(T o1, T o2);
}
class Int32Hash {
public static int hash(int key) {
key = ~key + (key << 15); // key = (key << 15) - key - 1;
key = key ^ (key >>> 12);
key = key + (key << 2);
key = key ^ (key >>> 4);
key = key * 2057; // key = (key + (key << 3)) + (key << 11);
key = key ^ (key >>> 16);
return key;
}
}
class StrictEqualityChecker {
@SuppressWarnings("unchecked")
public static <T> boolean isEquals(T me, Object you, EqualityChecker<T> ec) {
if(me == you)
return true;
if(you == null)
return false;
if(you.getClass() != me.getClass())
return false;
return ec.isEquals(me, (T)you);
}
}
abstract class AbstractReadableArray<T> extends AbstractContainer<T> implements ReadableArray<T> {
@Override
public final boolean isEmpty() {
return size() == 0;
}
@Override
public final T last() {
return get(size()-1);
}
@Override
public final T first() {
return get(0);
}
@Override
public final Iterator<T> iterator() {
return new AbstractIterator<T>() {
int p = 0;
public boolean hasNext() {
return p < size();
}
public T next() {
return get(p++);
}
};
}
}
abstract class AbstractContainer<T> implements Container<T> {
@Override
public final String toString() {
StringBuilder sb = new StringBuilder();
sb.append('(');
boolean first = true;
for(T v : this) {
if(first)
first = false;
else
sb.append(',');
sb.append(v);
}
sb.append(')');
return sb.toString();
}
}
interface ReadableArray<T> extends Container<T> {
T get(int index);
T last();
T first();
}
interface StaticArray<T> extends ReadableArray<T>{
void set(int index, T value);
}
class JavaHashMapFactory implements MapFactory {
@Override
public <K, V> Map<K, V> create() {
return new MapWrapperForJavaMap<K, V>(new HashMap<K, V>());
}
}
class MapWrapperForJavaMap<K, V> implements Map<K, V> {
private final java.util.Map<K,V> map;
public MapWrapperForJavaMap(java.util.Map<K,V> map) {
this.map = map;
}
public boolean containsKey(K key) {
return map.containsKey(key);
}
public V get(K key) {
return map.get(key);
}
public Iterable<K> keys() {
return map.keySet();
}
public void put(K key, V value) {
map.put(key, value);
}
public Iterable<V> values() {
return map.values();
}
public void clear() {
map.clear();
}
public boolean isEmpty() {
return map.isEmpty();
}
public Iterator<Entry<K, V>> iterator() {
return ConvertedDataIterator.createx(map.entrySet().iterator(), new DataConverter<java.util.Map.Entry<K,V>, Entry<K,V>>() {
@Override
public Entry<K, V> convert(java.util.Map.Entry<K, V> e) {
return new EntryWrapper<K, V>(e);
}
});
}
public int size() {
return map.size();
}
public void remove(K key) {
map.remove(key);
}
@Override
public String toString() {
return map.toString();
}
private static class EntryWrapper<K, V> implements Entry<K, V>, EqualityChecker<EntryWrapper<K,V>> {
private java.util.Map.Entry<K, V> e;
private EntryWrapper(java.util.Map.Entry<K, V> e) {
this.e = e;
}
@Override
public K getKey() {
return e.getKey();
}
@Override
public V getValue() {
return e.getValue();
}
@Override
public void setValue(V v) {
e.setValue(v);
}
@Override
public boolean equals(Object obj) {
return StrictEqualityChecker.isEquals(this, obj, this);
}
@Override
public boolean isEquals(EntryWrapper<K, V> o1, EntryWrapper<K, V> o2) {
return o1.getKey().equals(o2.getKey()) && o1.getValue().equals(o2.getValue());
}
@Override
public int hashCode() {
return PairHash.hash(getKey().hashCode(), getValue().hashCode());
}
}
}
class ConvertedDataIterator {
public static <T1, T2> Iterator<T2> createx(final Iterator<T1> outerIterator, final DataConverter<T1, T2> extractor) {
return new AbstractIterator<T2>() {
@Override
public boolean hasNext() {
return outerIterator.hasNext();
}
@Override
public T2 next() {
return extractor.convert(outerIterator.next());
}
};
}
}
interface DataConverter<T1, T2> {
T2 convert(T1 v);
}
class PairHash {
public static int hash(int h1, int h2) {
return Int64Hash.hash6432shift((((long) h1) << 32) | h2);
}
}
class Int64Hash {
public static int hash6432shift(long key) {
// from http://www.concentric.net/~ttwang/tech/inthash.htm
key = (~key) + (key << 18); // key = (key << 18) - key - 1;
key = key ^ (key >>> 31);
key = key * 21; // key = (key + (key << 2)) + (key << 4);
key = key ^ (key >>> 11);
key = key + (key << 6);
key = key ^ (key >>> 22);
return (int) key;
}
}
class CombinationNumberTableWithModular<T extends Int<T>> {
private Memoization<Index2D, T> mem;
public CombinationNumberTableWithModular(final T one, final T mod, MemoizationFactory mf) {
mem = mf.create(new ItemCalculator<Index2D, T>() {
@Override
public T calc(Index2D index, SubItem<Index2D, T> sub) {
int a = index.i1;
int b = index.i2;
if(b==0 || a==b) {
return one;
} else {
T sub1 = sub.get(new Index2D(a-1,b-1));
T sub2 = sub.get(new Index2D(a-1,b));
return sub1.plus(sub2).mod(mod);
}
}
});
}
public T get(int a, int b) {
if(b > a/2)
return get(a, a-b);
return mem.get(new Index2D(a,b));
}
}
class Index2D implements EqualityChecker<Index2D>{
public final int i1;
public final int i2;
public Index2D(int i, int j) {
this.i1 = i;
this.i2 = j;
}
@Override
public boolean equals(Object obj) {
return StrictEqualityChecker.isEquals(this, obj, this);
}
@Override
public boolean isEquals(Index2D o1, Index2D o2) {
return o1.i1 == o2.i1 && o1.i2 == o2.i2;
}
@Override
public int hashCode() {
return PairHash.hash(i1, i2);
}
@Override
public String toString() {
return "("+i1+","+i2 +")";
}
}
interface Int<T extends Int<T>> extends Multiplicative<T> {
T mod(T v);
T floorDivide(T v);
double toDouble();
}
interface Multiplicative<T extends Multiplicative<T>> extends Additive<T> {
T times(T a);
T getOne();
T get(int v);
boolean isOne();
}
interface Additive<T extends Additive<T>> extends Number<T> {
T plus(T v);
T minus(T v);
T getAddInvert();
T getZero();
boolean isPositive();
boolean isZero();
boolean isNegative();
int getSign();
}
interface Number<T> extends Comparable<T> {
}
class Int64 implements Int<Int64>, EqualityChecker<Int64> {
private final long v;
public Int64(long v) {
this.v = v;
}
@Override
public Int64 plus(Int64 t) {
return new Int64(v + t.v);
}
@Override
public Int64 minus(Int64 t) {
return new Int64(v - t.v);
}
public long toPrimitive() {
return v;
}
@Override
public Int64 getAddInvert() {
return new Int64(-v);
}
@Override
public int compareTo(Int64 o) {
if(v > o.v)
return 1;
else if(v < o.v)
return -1;
return 0;
}
@Override
public String toString() {
return Long.toString(v);
}
@Override
public Int64 getZero() {
return ZERO;
}
@Override
public Int64 getOne() {
return ONE;
}
@Override
public boolean isOne() {
return v == 1;
}
@Override
public Int64 times(Int64 a) {
return new Int64(v * a.v);
}
@Override
public Int64 floorDivide(Int64 o) {
return new Int64(v / o.v);
}
@Override
public Int64 mod(Int64 o) {
return new Int64(v % o.v);
}
public double toDouble() {
return v;
}
@Override
public boolean equals(Object obj) {
return StrictEqualityChecker.isEquals(this, obj, this);
}
@Override
public boolean isEquals(Int64 o1, Int64 o2) {
return o1.v == o2.v;
}
@Override
public int hashCode() {
return Int64Hash.hash6432shift(v);
}
@Override
public int getSign() {
if(v > 0)
return 1;
else if(v < 0)
return -1;
return 0;
}
@Override
public final Int64 get(int v) {
return new Int64(v);
}
@Override
public final boolean isPositive() {
return v > 0;
}
@Override
public final boolean isNegative() {
return v < 0;
}
@Override
public final boolean isZero() {
return v == 0;
}
static final public Int64 ZERO = new Int64(0);
static final public Int64 ONE = new Int64(1);
}
class QuickSort extends AbstractSort {
@Override
public <T> void sort(StaticArray<T> list, int start, int end, Comparator<T> comparator) {
if(start < end) {
ArraySwapper.swap(list, start, random.nextInt(end-start) + start + 1);
int pos = start;
for(int i=start+1;i<=end;i++) {
int c = comparator.compare(list.get(i), list.get(start));
if(c < 0 || c == 0 && i%2==0)
ArraySwapper.swap(list, i,++pos);
}
ArraySwapper.swap(list, start, pos);
sort(list, start,pos-1, comparator);
sort(list, pos+1, end, comparator);
}
}
static private Random random = new Random();
}
class ArraySwapper {
public static <T> void swap(StaticArray<T> a, int p1, int p2) {
T t = a.get(p1);
a.set(p1, a.get(p2));
a.set(p2, t);
}
public static <T> void swap(T[] a, int p1, int p2) {
swap(new StaticArrayUsingArray<T>(a), p1, p2);
}
}
class StaticArrayUsingArray<T> extends AbstractReadableArray<T> implements StaticArray<T> {
final private T[] a;
final private int start;
final private int end;
public StaticArrayUsingArray(T[] a) {
this.a = a;
start = 0;
end = a.length-1;
}
public StaticArrayUsingArray(T[] a, int start, int end) {
this.a = a;
this.start = start;
this.end = end;
}
public StaticArrayUsingArray(T[] a, int n) {
this.a = a;
this.start = 0;
this.end = n-1;
}
@Override
public T get(int arg0) {
return a[start+arg0];
}
@Override
public void set(int arg0, T arg1) {
a[start+arg0] = arg1;
}
@Override
public int size() {
return end-start+1;
}
}
abstract class AbstractSort implements Sort {
public abstract <T> void sort(StaticArray<T> a, int start, int end, Comparator<T> comparator);
@Override
public <T extends Comparable<T>> void sort(StaticArray<T> a) {
sort(a, 0, a.size()-1);
}
@Override
public <T> void sort(StaticArray<T> a, Comparator<T> comparator) {
sort(a, 0, a.size()-1, comparator);
}
@Override
public <T extends Comparable<T>> void sort(StaticArray<T> a, int start, int end) {
sort(a, start, end, new DefaultComparator<T>());
}
}
class DefaultComparator<T> implements Comparator<T> {
@SuppressWarnings("unchecked")
public int compare(T arg0, T arg1) {
return ((Comparable<T>)arg0).compareTo(arg1);
}
}
interface Sort {
<T> void sort(StaticArray<T> a, int start, int end, Comparator<T> comparator);
<T> void sort(StaticArray<T> a, Comparator<T> comparator);
<T extends Comparable<T>> void sort(StaticArray<T> a);
<T extends Comparable<T>> void sort(StaticArray<T> a, int start, int end);
}
| Java | ["3 1\n1", "4 2\n1 4", "11 2\n4 8"] | 1 second | ["1", "2", "6720"] | null | Java 7 | standard input | [
"combinatorics",
"number theory"
] | 14da0cdf2939c796704ec548f49efb87 | The first line of the input contains two integers n and m where n is the number of lights in the sequence and m is the number of lights which are initially switched on, (1 ≤ n ≤ 1000, 1 ≤ m ≤ n). The second line contains m distinct integers, each between 1 to n inclusive, denoting the indices of lights which are initially switched on. | 1,900 | In the only line of the output print the number of different possible ways to switch on all the lights modulo 1000000007 (109 + 7). | standard output | |
PASSED | 74f7e541fdc13f571b7b8f151895dfa2 | train_003.jsonl | 1365348600 | There are n lights aligned in a row. These lights are numbered 1 to n from left to right. Initially some of the lights are switched on. Shaass wants to switch all the lights on. At each step he can switch a light on (this light should be switched off at that moment) if there's at least one adjacent light which is already switched on. He knows the initial state of lights and he's wondering how many different ways there exist to switch all the lights on. Please find the required number of ways modulo 1000000007 (109 + 7). | 256 megabytes | import java.io.IOException;
import java.util.Arrays;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Mahmoud Aladdin
*/
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();
}
}
class TaskC {
public void solve(int testNumber, InputReader jin, PrintWriter jout) {
int n = jin.int32();
int m = jin.int32();
int[] on = IOUtils.read1DIntArray(jin, m);
Arrays.sort(on);
long numPerm = modFact(n - m);
numPerm *= modInverse(modFact(on[0] - 1));
numPerm %= MOD;
numPerm *= modInverse(modFact(n - on[m - 1]));
numPerm %= MOD;
for(int i = 1; i < m; i++) {
int diff = on[i] - 1 - on[i - 1];
if(diff == 0) continue;
long div = modInverse(modFact(diff));
long exp = modPow(2, diff - 1);
long tResult = ((div % MOD) * (exp % MOD)) % MOD;
numPerm *= tResult % MOD;
numPerm %= MOD;
}
jout.println(numPerm);
}
private long modInverse(long num) {
return modPow(num, MOD - 2);
}
private long modPow(long base, long exp) {
if(exp == 0) return 1;
long result = (exp & 1) == 0? 1 : base;
long tExp = exp >> 1;
long tResult = modPow(base, tExp);
tResult = (tResult * tResult) % MOD;
return ((result % MOD) * (tResult % MOD)) % MOD;
}
public static final long MOD = (long)1e9+7;
public long modFact(int n) {
if(n == 0) return 1;
return ((n % MOD) * (modFact(n - 1) % MOD)) % MOD;
}
}
class InputReader {
private static final int bufferMaxLength = 1024;
private InputStream in;
private byte[] buffer;
private int currentBufferSize;
private int currentBufferTop;
private static final String tokenizers = " \t\r\f\n";
public InputReader(InputStream stream) {
this.in = stream;
buffer = new byte[bufferMaxLength];
currentBufferSize = 0;
currentBufferTop = 0;
}
private boolean refill() {
try {
this.currentBufferSize = this.in.read(this.buffer);
this.currentBufferTop = 0;
} catch(Exception e) {}
return this.currentBufferSize > 0;
}
public String line() {
StringBuffer tok = new StringBuffer();
Byte first;
while((first = readChar()) != null) {
tok.append((char)first.byteValue());
if((char)first.byteValue() == '\n')
break;
}
return tok.toString();
}
public Byte readChar() {
if(currentBufferTop < currentBufferSize) {
return this.buffer[this.currentBufferTop++];
} else {
if(!this.refill()) {
return null;
} else {
return readChar();
}
}
}
public String token() {
StringBuffer tok = new StringBuffer();
Byte first;
while((first = readChar()) != null && (tokenizers.indexOf((char) first.byteValue()) != -1));
if(first == null) return null;
tok.append((char)first.byteValue());
while((first = readChar()) != null && (tokenizers.indexOf((char) first.byteValue()) == -1)) {
tok.append((char)first.byteValue());
}
return tok.toString();
}
public String next() {
return token();
}
public Integer int32() throws NumberFormatException {
String tok = token();
return tok == null? null : Integer.parseInt(tok);
}
public Long int64() throws NumberFormatException {
String tok = token();
return tok == null? null : Long.parseLong(tok);
}
}
class IOUtils {
public static int[] read1DIntArray(InputReader in, int size) {
int[] arr = new int[size];
for(int i = 0; i < size; i++) {
arr[i] = in.int32();
}
return arr;
}
public static int[][] read2DIntArray(InputReader in, int rowSize, int colSize) {
int[][] arr = new int[rowSize][];
for(int i = 0; i < rowSize; i++) {
arr[i] = IOUtils.read1DIntArray(in, colSize);
}
return arr;
}
}
| Java | ["3 1\n1", "4 2\n1 4", "11 2\n4 8"] | 1 second | ["1", "2", "6720"] | null | Java 7 | standard input | [
"combinatorics",
"number theory"
] | 14da0cdf2939c796704ec548f49efb87 | The first line of the input contains two integers n and m where n is the number of lights in the sequence and m is the number of lights which are initially switched on, (1 ≤ n ≤ 1000, 1 ≤ m ≤ n). The second line contains m distinct integers, each between 1 to n inclusive, denoting the indices of lights which are initially switched on. | 1,900 | In the only line of the output print the number of different possible ways to switch on all the lights modulo 1000000007 (109 + 7). | standard output | |
PASSED | 5d68dad1fe942ca15f49aee64e9c7973 | train_003.jsonl | 1365348600 | There are n lights aligned in a row. These lights are numbered 1 to n from left to right. Initially some of the lights are switched on. Shaass wants to switch all the lights on. At each step he can switch a light on (this light should be switched off at that moment) if there's at least one adjacent light which is already switched on. He knows the initial state of lights and he's wondering how many different ways there exist to switch all the lights on. Please find the required number of ways modulo 1000000007 (109 + 7). | 256 megabytes |
import java.io.InputStream;
import java.io.PrintStream;
import java.util.Scanner;
/**
* @author Abhimanyu Singh
*
*/
public class ShaassAndLights {
static final int MOD = 1000000007;
static int mod(int a) {
return a % MOD;
}
static int mul(int a, int b) {
long a1 = a % MOD;
long b1 = b % MOD;
return (int) ((a1 * b1) % MOD);
}
static int add(int a, int b) {
long a1 = a % MOD;
long b1 = b % MOD;
return (int) ((a1 + b1) % MOD);
}
static int inv(int a) {
a = a % MOD;
// fermat theorem a^(p-1) = 1 MOD
// a* a^(p-2) = 1 => a^-1 = a^(p-2)
return fastPowerMod(a, MOD - 2);
}
static int div(int x, int y) {
// "x/y"
return mul(x, inv(y));
}
static int fastPowerMod(int base, int exponent) {
int ans = 1;
while (exponent > 0) {
if ((exponent & 1) != 0) {
ans = mul(ans, base);
}
exponent = exponent >> 1;
base = mul(base, base);
}
return ans;
}
static int factorialMod(int n) {
int ans = 1;
for (int i = 1; i <= n; i++) {
ans = mul(ans, i);
}
return ans;
}
private InputStream input;
private PrintStream output;
private Scanner inputSc;
public ShaassAndLights(InputStream input, PrintStream output) {
this.input = input;
this.output = output;
init();
}
private void init() {
inputSc = new Scanner(input);
}
static int lineToInt(String line) {
return Integer.parseInt(line);
}
public void solve() {
solveTestCase(1);
}
private void solveTestCase(int testN) {
int n = inputSc.nextInt();
int m = inputSc.nextInt();
boolean on[] = new boolean[n];
for (int i = 0; i < m; i++) {
int onI = inputSc.nextInt();
on[onI - 1] = true;
}
boolean found = false;
int count = 0;
boolean onWasThere = false;
int groupCount[] = new int[n];
boolean twoSided[] = new boolean[n];
int gc = 0;
for (int i = 0; i < n; i++) {
if (on[i]) {
if (found) {
groupCount[gc] = count;
count = 0;
if (onWasThere) {
twoSided[gc] = true;
}
found = false;
gc++;
}
onWasThere = true;
} else {
if (found) {
count++;
} else {
found = true;
count = 1;
}
}
}
if (found) {
groupCount[gc] = count;
count = 0;
found = false;
gc++;
}
int total = 0;
for (int i = 0; i < gc; i++) {
total += groupCount[i];
}
int ans = factorialMod(total);
for (int i = 0; i < gc; i++) {
if (twoSided[i]) {
ans = mul(ans, fastPowerMod(2, groupCount[i] - 1));
}
}
for (int i = 0; i < gc; i++) {
ans = div(ans, factorialMod(groupCount[i]));
}
output.println(ans);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
ShaassAndLights sal = new ShaassAndLights(System.in, System.out);
sal.solve();
}
}
| Java | ["3 1\n1", "4 2\n1 4", "11 2\n4 8"] | 1 second | ["1", "2", "6720"] | null | Java 7 | standard input | [
"combinatorics",
"number theory"
] | 14da0cdf2939c796704ec548f49efb87 | The first line of the input contains two integers n and m where n is the number of lights in the sequence and m is the number of lights which are initially switched on, (1 ≤ n ≤ 1000, 1 ≤ m ≤ n). The second line contains m distinct integers, each between 1 to n inclusive, denoting the indices of lights which are initially switched on. | 1,900 | In the only line of the output print the number of different possible ways to switch on all the lights modulo 1000000007 (109 + 7). | standard output | |
PASSED | 442aa04fb57d79081df0e683ddec1e96 | train_003.jsonl | 1365348600 | There are n lights aligned in a row. These lights are numbered 1 to n from left to right. Initially some of the lights are switched on. Shaass wants to switch all the lights on. At each step he can switch a light on (this light should be switched off at that moment) if there's at least one adjacent light which is already switched on. He knows the initial state of lights and he's wondering how many different ways there exist to switch all the lights on. Please find the required number of ways modulo 1000000007 (109 + 7). | 256 megabytes | import java.io.IOException;
import java.util.ArrayList;
import java.util.InputMismatchException;
public class ShaassAndLights {
public static final int MOD = 1000000007;
public static final long[] POW2 = new long[1001];
public static final long[][] COMBOS = computeCombinations(2001);
static {
POW2[0] = 1;
for (int i = 1; i < POW2.length; i++) {
POW2[i] = (2 * POW2[i - 1]) % MOD;
}
}
public static void main(String[] args) {
FasterScanner sc = new FasterScanner();
int N = sc.nextInt();
int M = sc.nextInt();
boolean[] on = new boolean[N + 1];
for (int i = 0; i < M; i++) {
int A = sc.nextInt();
on[A] = true;
}
ArrayList<Integer> lst = new ArrayList<Integer>();
ArrayList<Long> way = new ArrayList<Long>();
int sofar = 0;
for (int i = 1; i <= N + 1; i++) {
if (i > N || on[i]) {
if (sofar > 0) {
lst.add(sofar);
way.add(POW2[sofar - 1]);
}
sofar = 0;
} else {
sofar++;
}
}
if (lst.size() == 0) {
System.out.println(1);
return;
}
if (!on[1]) {
way.set(0, 1L);
}
if (!on[N]) {
way.set(way.size() - 1, 1L);
}
long cnt = way.get(0);
int sum = lst.get(0);
for (int i = 1; i < way.size(); i++) {
int len = lst.get(i);
long mult = (COMBOS[sum + len][sum] * way.get(i)) % MOD;
cnt = (cnt * mult) % MOD;
sum += len;
}
System.out.println(cnt);
}
/**
* Computes all the combinations (i.e. Pascal's triangle) for the given levels.
* For example, combos[n][k] = (n choose k).
*/
public static long[][] computeCombinations(int n) {
long[][] combos = new long[n + 1][n + 1];
combos[0][0] = 1;
for (int r = 1; r <= n; r++) {
combos[r][0] = 1;
for (int c = 1; c <= r; c++) {
combos[r][c] = (combos[r - 1][c - 1] + combos[r - 1][c]) % MOD;
}
}
return combos;
}
public static class FasterScanner {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = System.in.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String 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;
}
}
} | Java | ["3 1\n1", "4 2\n1 4", "11 2\n4 8"] | 1 second | ["1", "2", "6720"] | null | Java 7 | standard input | [
"combinatorics",
"number theory"
] | 14da0cdf2939c796704ec548f49efb87 | The first line of the input contains two integers n and m where n is the number of lights in the sequence and m is the number of lights which are initially switched on, (1 ≤ n ≤ 1000, 1 ≤ m ≤ n). The second line contains m distinct integers, each between 1 to n inclusive, denoting the indices of lights which are initially switched on. | 1,900 | In the only line of the output print the number of different possible ways to switch on all the lights modulo 1000000007 (109 + 7). | standard output | |
PASSED | 2ddc52d35f55ab3a5e3e1c4ad4898b10 | train_003.jsonl | 1365348600 | There are n lights aligned in a row. These lights are numbered 1 to n from left to right. Initially some of the lights are switched on. Shaass wants to switch all the lights on. At each step he can switch a light on (this light should be switched off at that moment) if there's at least one adjacent light which is already switched on. He knows the initial state of lights and he's wondering how many different ways there exist to switch all the lights on. Please find the required number of ways modulo 1000000007 (109 + 7). | 256 megabytes | import java.io.*;
import java.util.*;
public class C {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
static final int MOD = 1000000007;
void solve() throws IOException {
int n = nextInt();
int m = nextInt();
boolean[] lit = new boolean[n];
for (int i = 0; i < m; i++) {
int pos = nextInt() - 1;
lit[pos] = true;
}
int st2 = 0;
ArrayList<Integer> lens = new ArrayList<>();
for (int i = 0; i < n; ) {
if (lit[i]) {
i++;
continue;
}
int j = i;
while (j < n && !lit[j])
j++;
lens.add(j - i);
if (i != 0 && j != n)
st2 += j - i - 1;
i = j;
}
int sum = n - m;
int[] fact = new int[n + 1];
int[] invFact = new int[n + 1];
fact[0] = invFact[0] = 1;
for (int i = 1; i <= n; i++) {
fact[i] = (int)((long)fact[i - 1] * i % MOD);
invFact[i] = pow(fact[i], MOD - 2);
}
int res = (int)((long)fact[sum] * pow(2, st2) % MOD);
for (int x : lens)
res = (int)((long)res * invFact[x] % MOD);
out.println(res);
}
int pow(int a, int b) {
int res = 1;
while (b != 0) {
if ((b & 1) == 1) {
res = (int)((long)res * a % MOD);
}
a = (int)((long)a * a % MOD);
b >>= 1;
}
return res;
}
C() 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 C();
}
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());
}
} | Java | ["3 1\n1", "4 2\n1 4", "11 2\n4 8"] | 1 second | ["1", "2", "6720"] | null | Java 7 | standard input | [
"combinatorics",
"number theory"
] | 14da0cdf2939c796704ec548f49efb87 | The first line of the input contains two integers n and m where n is the number of lights in the sequence and m is the number of lights which are initially switched on, (1 ≤ n ≤ 1000, 1 ≤ m ≤ n). The second line contains m distinct integers, each between 1 to n inclusive, denoting the indices of lights which are initially switched on. | 1,900 | In the only line of the output print the number of different possible ways to switch on all the lights modulo 1000000007 (109 + 7). | standard output | |
PASSED | f5dc199f6f905b4a2db2e12cdab2b1bc | train_003.jsonl | 1365348600 | There are n lights aligned in a row. These lights are numbered 1 to n from left to right. Initially some of the lights are switched on. Shaass wants to switch all the lights on. At each step he can switch a light on (this light should be switched off at that moment) if there's at least one adjacent light which is already switched on. He knows the initial state of lights and he's wondering how many different ways there exist to switch all the lights on. Please find the required number of ways modulo 1000000007 (109 + 7). | 256 megabytes | import java.util.*;
import java.io.BufferedInputStream;
import java.util.Arrays;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.CharArrayWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.io.InputStreamReader;
import java.math.*;
import java.awt.print.PrinterAbortException;
import java.io.*;
public class Main {
/**
* written by: Amirhossein ---- Shamir14
*/
public static int MAX = 1001;
public static BigInteger fact[];
public static int Fast_pow(long a, long l, long m){
long ans;
ans = 1;
while(l != 0){
if((l % 2) == 1)
ans = (ans * a) % m;
a = (a * a) % m;
l /= 2;
}
return (int)ans;
}
public static void main(String[] args) throws FileNotFoundException{
Scanner sc = new Scanner(System.in);
//InputStream is;
//Scanner sc = new Scanner("input.in");
//is = new ByteArrayInputStream(line.getBytes());
//ss = new Scanner(new InputStreamReader(is));
//PrintWriter pw = new PrintWriter(output.out);
int i, n, m, MOD = 1000000007, temp;
long Ans;
Integer space[];
BigInteger ans;
fact = new BigInteger[MAX];
fact[0] = BigInteger.ONE;
for(i = 1; i < MAX; i++)
fact[i] = fact[i - 1].multiply(BigInteger.valueOf(i));
n = sc.nextInt(); m = sc.nextInt();
space = new Integer[m + 2];
space[0] = 0;
for(i = 1; i <= m; i++){
space[i] = sc.nextInt();
}
space[m + 1] = n + 1;
Arrays.sort(space);
temp = 0;
for(i = 2; i <= m; i++)
if(space[i] - space[i - 1] > 1)
temp++;
//System.out.println(temp);
/*for(i = 0; i < m + 2; i++)
System.out.print(space[i] + " ");
System.out.println("");
*/
ans = fact[n - m];
//System.out.println(ans);
for(i = 1; i < m + 2; i++){
if(space[i] - space[i - 1] - 1 >= 0)
ans = ans.divide(fact[space[i] - space[i - 1] - 1]);
//System.out.print(ans + " ");
}
// System.out.println("");
ans = ans.mod(BigInteger.valueOf(MOD));
Ans = ans.intValue();
//System.out.println("DD :D : " + Ans);
// System.out.println(space[m] - space[1] + 1 - m - temp + " " + Fast_pow(2, space[m] - space[1] + 1 - m - temp, MOD));
Ans = (Ans * Fast_pow(2, space[m] - space[1] + 1 - m - temp, MOD)) % MOD;
System.out.println(Ans);
//pw.close();
}
}
| Java | ["3 1\n1", "4 2\n1 4", "11 2\n4 8"] | 1 second | ["1", "2", "6720"] | null | Java 7 | standard input | [
"combinatorics",
"number theory"
] | 14da0cdf2939c796704ec548f49efb87 | The first line of the input contains two integers n and m where n is the number of lights in the sequence and m is the number of lights which are initially switched on, (1 ≤ n ≤ 1000, 1 ≤ m ≤ n). The second line contains m distinct integers, each between 1 to n inclusive, denoting the indices of lights which are initially switched on. | 1,900 | In the only line of the output print the number of different possible ways to switch on all the lights modulo 1000000007 (109 + 7). | standard output | |
PASSED | 849a28a50965c60f2a8099ccde386637 | train_003.jsonl | 1365348600 | There are n lights aligned in a row. These lights are numbered 1 to n from left to right. Initially some of the lights are switched on. Shaass wants to switch all the lights on. At each step he can switch a light on (this light should be switched off at that moment) if there's at least one adjacent light which is already switched on. He knows the initial state of lights and he's wondering how many different ways there exist to switch all the lights on. Please find the required number of ways modulo 1000000007 (109 + 7). | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Locale;
import java.util.StringTokenizer;
public class C {
private static final long MOD = (long) (1e9 + 7.5);
private long[][] calc(int n) {
long[][] c = new long[n + 1][n + 1];
c[0][0] = 1;
for (int i = 0; i <= n; i++) {
c[i][0] = 1;
for (int j = 1; j <= i; j++) {
c[i][j] = (c[i - 1][j] + c[i - 1][j - 1]) % MOD;
}
}
return c;
}
private long[] pow2(int n) {
long[] pow = new long[n];
pow[0] = 1;
for (int i = 1; i < n; i++) {
pow[i] = (pow[i - 1] * 2) % MOD;
}
return pow;
}
private void solve() throws IOException {
int n = nextInt();
long[][] c = calc(n);
long[] pow2 = pow2(n);
int m = nextInt();
int[] a = new int[m];
for (int i = 0; i < m; i++) {
a[i] = nextInt();
}
Arrays.sort(a);
int k = n - m;
long res = c[k][a[0] - 1];
k -= a[0] - 1;
res = (res * c[k][n - a[m - 1]]) % MOD;
k -= n - a[m - 1];
for (int i = 1; i < a.length; i++) {
int len = a[i] - a[i - 1] - 1;
if (len != 0) {
res = (((res * c[k][len]) % MOD) * pow2[len - 1]) % MOD;
k -= len;
}
}
println(res);
}
private String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
private int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(nextToken());
}
private double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private void print(Object o) {
writer.print(o);
}
private void println(Object o) {
writer.println(o);
}
private void printf(String format, Object... o) {
writer.printf(format, o);
}
public static void main(String[] args) {
long time = System.currentTimeMillis();
Locale.setDefault(Locale.US);
new C().run();
System.err.printf("%.3f\n", 1e-3 * (System.currentTimeMillis() - time));
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
private void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(13);
}
}
} | Java | ["3 1\n1", "4 2\n1 4", "11 2\n4 8"] | 1 second | ["1", "2", "6720"] | null | Java 7 | standard input | [
"combinatorics",
"number theory"
] | 14da0cdf2939c796704ec548f49efb87 | The first line of the input contains two integers n and m where n is the number of lights in the sequence and m is the number of lights which are initially switched on, (1 ≤ n ≤ 1000, 1 ≤ m ≤ n). The second line contains m distinct integers, each between 1 to n inclusive, denoting the indices of lights which are initially switched on. | 1,900 | In the only line of the output print the number of different possible ways to switch on all the lights modulo 1000000007 (109 + 7). | standard output | |
PASSED | 97a151e2906860578d23da8899107eae | train_003.jsonl | 1365348600 | There are n lights aligned in a row. These lights are numbered 1 to n from left to right. Initially some of the lights are switched on. Shaass wants to switch all the lights on. At each step he can switch a light on (this light should be switched off at that moment) if there's at least one adjacent light which is already switched on. He knows the initial state of lights and he's wondering how many different ways there exist to switch all the lights on. Please find the required number of ways modulo 1000000007 (109 + 7). | 256 megabytes | import java.util.Scanner;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.math.BigDecimal;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Fish <lyhypacm@gmail.com>
*/
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();
}
}
class TaskC {
private static final long MOD = 1000000007;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int m = in.nextInt();
long[] p = new long[n + 1];
p[0] = 1;
for (int i = 1; i <= n; ++i)
p[i] = p[i - 1] * i % MOD;
int[] a = new int[m];
for (int i = 0; i < m; ++i) {
a[i] = in.nextInt();
}
Arrays.sort(a);
long ret = p[n - m];
for (int i = 1; i < m; ++i) {
if (a[i] - a[i - 1] > 1) {
ret *= Numeric.exp(p[a[i] - a[i - 1] - 1], MOD - 2, MOD);
ret %= MOD;
ret *= Numeric.exp(2, a[i] - a[i - 1] - 2, MOD);
ret %= MOD;
}
}
ret *= Numeric.exp(p[a[0] - 1], MOD - 2, MOD);
ret %= MOD;
ret *= Numeric.exp(p[n - a[m - 1]], MOD - 2, MOD);
ret %= MOD;
out.println(ret);
}
}
class InputReader {
private Scanner scanner;
public InputReader(InputStream inputStream) {
scanner = new Scanner(new BufferedReader(new InputStreamReader(inputStream)));
}
public int nextInt() {
return scanner.nextInt();
}
public long nextLong() {
return scanner.nextLong();
}
public String next() {
return scanner.next();
}
public BigInteger nextBigInteger() {
return scanner.nextBigInteger();
}
public BigDecimal nextBigDecimal() {
return scanner.nextBigDecimal();
}
public double nextDouble() {
return scanner.nextDouble();
}
public boolean hasNext() {
return scanner.hasNext();
}
}
class OutputWriter {
private PrintWriter printWriter;
public OutputWriter(OutputStream outputStream) {
printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
printWriter = new PrintWriter(writer);
}
public <T> void print(T object) {
printWriter.print(object);
}
public <T> void println(T object) {
printWriter.println(object);
}
public void println() {
printWriter.println();
}
public void close() {
printWriter.close();
}
}
class Numeric {
public static long exp(long x, long k, long MOD) {
long result = 1;
x %= MOD;
while (k > 0) {
if ((k & 1) != 0)
result = result * x % MOD;
x = x * x % MOD;
k >>= 1;
}
return result;
}
public static int sqrt(int n) {
int ret = Math.max(0, (int) Math.sqrt(n) - 2);
while (ret * ret <= n)
++ret;
return ret - 1;
}
}
| Java | ["3 1\n1", "4 2\n1 4", "11 2\n4 8"] | 1 second | ["1", "2", "6720"] | null | Java 7 | standard input | [
"combinatorics",
"number theory"
] | 14da0cdf2939c796704ec548f49efb87 | The first line of the input contains two integers n and m where n is the number of lights in the sequence and m is the number of lights which are initially switched on, (1 ≤ n ≤ 1000, 1 ≤ m ≤ n). The second line contains m distinct integers, each between 1 to n inclusive, denoting the indices of lights which are initially switched on. | 1,900 | In the only line of the output print the number of different possible ways to switch on all the lights modulo 1000000007 (109 + 7). | standard output | |
PASSED | a55f3446e809ecfa72e207ec7802135c | train_003.jsonl | 1365348600 | There are n lights aligned in a row. These lights are numbered 1 to n from left to right. Initially some of the lights are switched on. Shaass wants to switch all the lights on. At each step he can switch a light on (this light should be switched off at that moment) if there's at least one adjacent light which is already switched on. He knows the initial state of lights and he's wondering how many different ways there exist to switch all the lights on. Please find the required number of ways modulo 1000000007 (109 + 7). | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
static long pow(long base, int exp)
{
long res = 1;
while(exp > 0)
{
if(exp % 2 == 1)
res = res * base % mod;
base = base * base % mod;
exp /= 2;
}
return res;
}
static long modFact(long n)
{
long res = 1;
while(n > 0)
res = res * n-- % mod;
return res;
}
static long modInvFact(long n)
{
long res = 1;
while(n > 0)
res = res * pow(n--,mod-2) % mod;
return res;
}
static final int mod = (int)1e9+7;
static void zap() throws IOException {
int n = nextInt();
int m = nextInt();
int[] ind = new int[m];
for(int i=0;i<m;i++)
ind[i] = nextInt()-1;
Arrays.sort(ind);
long ways = modFact(n-m);
ways = ways * (modInvFact(ind[0]-0) * modInvFact(n-1-ind[m-1]) % mod) % mod;
for(int i=1;i<ind.length;i++)
ways = ways * modInvFact(ind[i]-ind[i-1]-1) % mod;
for(int i=1;i<ind.length;i++)
ways = ways * pow(2, Math.max(ind[i]-ind[i-1]-2, 0)) % mod;
out.println((mod + ways) % mod);
}
static BufferedReader br;
static StringTokenizer st;
static PrintWriter out;
public static void main(String[] args) throws IOException {
InputStream input = System.in;
//InputStream input = new FileInputStream("fileIn.in");
br = new BufferedReader(new InputStreamReader(input));
out = new PrintWriter(System.out);
//out = new PrintWriter(new FileOutputStream("fileOut.out"));
zap();
out.close();
}
static long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
static double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
static int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
static String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = br.readLine();
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
} | Java | ["3 1\n1", "4 2\n1 4", "11 2\n4 8"] | 1 second | ["1", "2", "6720"] | null | Java 7 | standard input | [
"combinatorics",
"number theory"
] | 14da0cdf2939c796704ec548f49efb87 | The first line of the input contains two integers n and m where n is the number of lights in the sequence and m is the number of lights which are initially switched on, (1 ≤ n ≤ 1000, 1 ≤ m ≤ n). The second line contains m distinct integers, each between 1 to n inclusive, denoting the indices of lights which are initially switched on. | 1,900 | In the only line of the output print the number of different possible ways to switch on all the lights modulo 1000000007 (109 + 7). | standard output | |
PASSED | 01111f5df0943d704cda138f0b5ae277 | train_003.jsonl | 1365348600 | There are n lights aligned in a row. These lights are numbered 1 to n from left to right. Initially some of the lights are switched on. Shaass wants to switch all the lights on. At each step he can switch a light on (this light should be switched off at that moment) if there's at least one adjacent light which is already switched on. He knows the initial state of lights and he's wondering how many different ways there exist to switch all the lights on. Please find the required number of ways modulo 1000000007 (109 + 7). | 256 megabytes |
import java.util.*;
import java.io.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
import static java.lang.Math.*;
public class C {
int INF = 1 << 28;
//long INF = 1L << 62;
double EPS = 1e-10;
long MOD = (long)1e9+7;
long cmb[][];
long pow[];
void run() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), m = sc.nextInt();
long sum = 1;
int cur = 0;
int all = n - m;
culc(n);
int[] a = new int[m];
for(int i=0;i<m;i++) a[i] = sc.nextInt();
sort(a);
for(int i=0;i<m;i++) {
int x = a[i]-cur-1;
// debug(cur, x, all);
sum = (sum*cmb[all][x]) % MOD;
if(cur != 0 && x!=0) {
sum = (sum*pow[x-1]) % MOD;
}
cur += x+1;
all -= x;
}
System.out.println(sum);
}
void culc(int n) {
cmb = new long[n+1][n+1]; for(int i=0;i<=n;i++) cmb[i][0] = 1;
pow = new long[n+1];pow[0] = 1;
for(int i=1;i<=n;i++) for(int j=1;j<=i;j++) {
cmb[i][j] = (cmb[i-1][j-1]+cmb[i-1][j])%MOD;
}
for(int i=1;i<=n;i++) pow[i] = pow[i-1]*2%MOD;
// debug(cmb);
}
void debug(Object... os) {
System.err.println(Arrays.deepToString(os));
}
public static void main(String[] args) {
new C().run();
}
}
| Java | ["3 1\n1", "4 2\n1 4", "11 2\n4 8"] | 1 second | ["1", "2", "6720"] | null | Java 7 | standard input | [
"combinatorics",
"number theory"
] | 14da0cdf2939c796704ec548f49efb87 | The first line of the input contains two integers n and m where n is the number of lights in the sequence and m is the number of lights which are initially switched on, (1 ≤ n ≤ 1000, 1 ≤ m ≤ n). The second line contains m distinct integers, each between 1 to n inclusive, denoting the indices of lights which are initially switched on. | 1,900 | In the only line of the output print the number of different possible ways to switch on all the lights modulo 1000000007 (109 + 7). | standard output | |
PASSED | 5ded51707f1fef5a2b2ed5a3af47bbff | train_003.jsonl | 1365348600 | There are n lights aligned in a row. These lights are numbered 1 to n from left to right. Initially some of the lights are switched on. Shaass wants to switch all the lights on. At each step he can switch a light on (this light should be switched off at that moment) if there's at least one adjacent light which is already switched on. He knows the initial state of lights and he's wondering how many different ways there exist to switch all the lights on. Please find the required number of ways modulo 1000000007 (109 + 7). | 256 megabytes | /* Codeforces Template */
import java.io.*;
import java.math.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.fill;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.sort;
public class Main {
static long initTime;
static final Random rnd = new Random(7777L);
static boolean writeLog = false;
public static void main(String[] args) throws IOException {
initTime = System.currentTimeMillis();
try {
writeLog = "true".equals(System.getProperty("LOCAL_RUN_7777"));
} catch (SecurityException e) {}
new Thread(null, new Runnable() {
public void run() {
try {
try {
if (new File("input.txt").exists())
System.setIn(new FileInputStream("input.txt"));
} catch (SecurityException e) {}
long prevTime = System.currentTimeMillis();
new Main().run();
log("Total time: " + (System.currentTimeMillis() - prevTime) + " ms");
log("Memory status: " + memoryStatus());
} catch (IOException e) {
e.printStackTrace();
}
}
}, "1", 1L << 24).start();
}
void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
in.close();
}
/***************************************************************
* Solution
**************************************************************/
long mod = 1000000007L;
BigInteger MOD = BigInteger.valueOf(mod);
void solve() throws IOException {
int n = nextInt();
int m = nextInt();
int min = n + 1;
int max = -1;
boolean[] a = new boolean [n];
for (int i = 0; i < m; i++) {
int x = nextInt() - 1;
min = min(min, x);
max = max(max, x);
a[x] = true;
}
List<Item> ranges = new ArrayList<Main.Item>();
if (min > 0)
ranges.add(new Item(min, 1L % mod));
if (max < n)
ranges.add(new Item(n - max - 1, 1L % mod));
for (int i = 0; i + 1 < n; i++) {
if (a[i] && !a[i + 1]) {
int j = i + 1;
for (; j + 1 < n && !a[j + 1]; j++);
if (j + 1 >= n) break;
ranges.add(new Item(j - i, powMod(2L, j - i - 1, mod)));
i = j;
}
}
// System.err.println(ranges);
long ans = f(n - m);
for (Item r : ranges) {
ans = ans * r.ways % mod;
ans = ans * modInverse(f(r.len), mod) % mod;
}
out.println(ans);
}
long f(int n) {
long ret = 1L % mod;
for (int i = 1; i <= n; i++)
ret = ret * i % mod;
return ret;
}
long modInverse(long x, long mod) {
return BigInteger.valueOf(x).modInverse(MOD).longValue();
}
long powMod(long base, long deg, long mod) {
return BigInteger.valueOf(base).modPow(BigInteger.valueOf(deg), BigInteger.valueOf(mod)).longValue();
}
class Item {
int len;
long ways;
Item(int len, long ways) {
this.len = len;
this.ways = ways;
}
@Override
public String toString() {
return len + " " + ways;
}
}
/***************************************************************
* Input
**************************************************************/
BufferedReader in;
PrintWriter out;
StringTokenizer st = new StringTokenizer("");
String nextToken() throws IOException {
while (!st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
int[] nextIntArray(int size) throws IOException {
int[] ret = new int [size];
for (int i = 0; i < size; i++)
ret[i] = nextInt();
return ret;
}
long[] nextLongArray(int size) throws IOException {
long[] ret = new long [size];
for (int i = 0; i < size; i++)
ret[i] = nextLong();
return ret;
}
double[] nextDoubleArray(int size) throws IOException {
double[] ret = new double [size];
for (int i = 0; i < size; i++)
ret[i] = nextDouble();
return ret;
}
String nextLine() throws IOException {
st = new StringTokenizer("");
return in.readLine();
}
boolean EOF() throws IOException {
while (!st.hasMoreTokens()) {
String s = in.readLine();
if (s == null)
return true;
st = new StringTokenizer(s);
}
return false;
}
/***************************************************************
* Output
**************************************************************/
void printRepeat(String s, int count) {
for (int i = 0; i < count; i++)
out.print(s);
}
void printArray(int[] array) {
if (array == null || array.length == 0)
return;
for (int i = 0; i < array.length; i++) {
if (i > 0) out.print(' ');
out.print(array[i]);
}
out.println();
}
void printArray(long[] array) {
if (array == null || array.length == 0)
return;
for (int i = 0; i < array.length; i++) {
if (i > 0) out.print(' ');
out.print(array[i]);
}
out.println();
}
void printArray(double[] array) {
if (array == null || array.length == 0)
return;
for (int i = 0; i < array.length; i++) {
if (i > 0) out.print(' ');
out.print(array[i]);
}
out.println();
}
void printArray(double[] array, String spec) {
if (array == null || array.length == 0)
return;
for (int i = 0; i < array.length; i++) {
if (i > 0) out.print(' ');
out.printf(Locale.US, spec, array[i]);
}
out.println();
}
void printArray(Object[] array) {
if (array == null || array.length == 0)
return;
boolean blank = false;
for (Object x : array) {
if (blank) out.print(' '); else blank = true;
out.print(x);
}
out.println();
}
@SuppressWarnings("rawtypes")
void printCollection(Collection collection) {
if (collection == null || collection.isEmpty())
return;
boolean blank = false;
for (Object x : collection) {
if (blank) out.print(' '); else blank = true;
out.print(x);
}
out.println();
}
/***************************************************************
* Utility
**************************************************************/
static String memoryStatus() {
return (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() >> 20) + "/" + (Runtime.getRuntime().totalMemory() >> 20) + " MB";
}
static void checkMemory() {
System.err.println(memoryStatus());
}
static long prevTimeStamp = Long.MIN_VALUE;
static void updateTimer() {
prevTimeStamp = System.currentTimeMillis();
}
static long elapsedTime() {
return (System.currentTimeMillis() - prevTimeStamp);
}
static void checkTimer() {
System.err.println(elapsedTime() + " ms");
}
static void chk(boolean f) {
if (!f) throw new RuntimeException("Assert failed");
}
static void chk(boolean f, String format, Object ... args) {
if (!f) throw new RuntimeException(String.format(format, args));
}
static void log(String format, Object ... args) {
if (writeLog) System.err.println(String.format(Locale.US, format, args));
}
}
| Java | ["3 1\n1", "4 2\n1 4", "11 2\n4 8"] | 1 second | ["1", "2", "6720"] | null | Java 7 | standard input | [
"combinatorics",
"number theory"
] | 14da0cdf2939c796704ec548f49efb87 | The first line of the input contains two integers n and m where n is the number of lights in the sequence and m is the number of lights which are initially switched on, (1 ≤ n ≤ 1000, 1 ≤ m ≤ n). The second line contains m distinct integers, each between 1 to n inclusive, denoting the indices of lights which are initially switched on. | 1,900 | In the only line of the output print the number of different possible ways to switch on all the lights modulo 1000000007 (109 + 7). | standard output | |
PASSED | 4b23e68c067dfe5f3540a8b23c249550 | train_003.jsonl | 1365348600 | There are n lights aligned in a row. These lights are numbered 1 to n from left to right. Initially some of the lights are switched on. Shaass wants to switch all the lights on. At each step he can switch a light on (this light should be switched off at that moment) if there's at least one adjacent light which is already switched on. He knows the initial state of lights and he's wondering how many different ways there exist to switch all the lights on. Please find the required number of ways modulo 1000000007 (109 + 7). | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class Contest178 {
public static void main(String[] args) throws IOException {
new Contest178().run();
}
class Book {
public int t;
public int w;
public Book(int _t, int _w) {
t = _t;
w = _w;
}
}
class Cmp implements Comparator<Book> {
public int compare(Book b1, Book b2) {
return b1.w < b2.w ? -1 : (b2.w > b1.w ? 1 : 0);
}
}
BigInteger fact[];
public void solve() throws IOException {
int n = nextInt();
int m = nextInt();
int en[] = new int[m];
for(int i = 0; i < m; ++i)
en[i] = nextInt();
Arrays.sort(en);
int left = en[0] - 1;
int right = n - en[m - 1];
ArrayList<Integer> inner = new ArrayList<Integer>();
for(int i = 0; i + 1 < m; ++i)
if(en[i] + 1 != en[i + 1])
inner.add(en[i + 1] - en[i] - 1);
fact = new BigInteger[n + 1];
fact[0] = BigInteger.ONE;
for(int i = 1; i < fact.length; ++i)
fact[i] = fact[i - 1].multiply(BigInteger.valueOf(i));
BigInteger res = fact[n - m];
res = res.divide(fact[left]);
res = res.divide(fact[right]);
for(int cur : inner)
res = res.divide(fact[cur]);
for(int cur : inner)
res = res.multiply(BigInteger.valueOf(2).pow(cur - 1));
res = res.mod(BigInteger.valueOf(1000000007));
out.println(res);
}
/*
public void solve() throws IOException {
int n = nextInt();
Book books[] = new Book[n];
int full_t = 0;
for(int i = 0; i < n; ++i) {
int t = nextInt();
int w = nextInt();
books[i] = new Book(t, w);
full_t += t;
}
Arrays.sort(books, new Cmp());
int cur_t = full_t;
int cur_w = 0;
int res_t = cur_t;
int ptr = 0;
while(true) {
cur_t -= books[ptr].t;
cur_w += books[ptr].w;
++ptr;
if(cur_w <= cur_t)
res_t = Math.min(res_t, cur_t);
if(cur_w > cur_t || ptr == n)
break;
}
out.println(res_t);
}
*/
BufferedReader br;
StringTokenizer in;
PrintWriter out;
String nextToken() throws IOException {
while( in == null || !in.hasMoreTokens() ) {
in = new StringTokenizer(br.readLine());
}
return in.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
void run() throws IOException {
boolean oj = System.getProperty( "ONLINE_JUDGE" ) != null;
Reader reader = new InputStreamReader( oj ? System.in : new FileInputStream("input.txt"));
Writer writer = new OutputStreamWriter( oj ? System.out : new FileOutputStream("output.txt"));
br = new BufferedReader(reader);
out = new PrintWriter(writer);
solve();
out.close();
}
} | Java | ["3 1\n1", "4 2\n1 4", "11 2\n4 8"] | 1 second | ["1", "2", "6720"] | null | Java 7 | standard input | [
"combinatorics",
"number theory"
] | 14da0cdf2939c796704ec548f49efb87 | The first line of the input contains two integers n and m where n is the number of lights in the sequence and m is the number of lights which are initially switched on, (1 ≤ n ≤ 1000, 1 ≤ m ≤ n). The second line contains m distinct integers, each between 1 to n inclusive, denoting the indices of lights which are initially switched on. | 1,900 | In the only line of the output print the number of different possible ways to switch on all the lights modulo 1000000007 (109 + 7). | standard output | |
PASSED | 4721b0604dbe87363bf0bcb7dff91fc6 | train_003.jsonl | 1365348600 | There are n lights aligned in a row. These lights are numbered 1 to n from left to right. Initially some of the lights are switched on. Shaass wants to switch all the lights on. At each step he can switch a light on (this light should be switched off at that moment) if there's at least one adjacent light which is already switched on. He knows the initial state of lights and he's wondering how many different ways there exist to switch all the lights on. Please find the required number of ways modulo 1000000007 (109 + 7). | 256 megabytes | import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.SortedSet;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main
{
/********************************************** a list of common variables **********************************************/
private MyScanner scan = new MyScanner();
private PrintWriter out = new PrintWriter(System.out);
private final double PI = Math.acos(-1.0);
private final int SIZEN = (int)(1e5);
private final long MOD = (int)(1e9 + 7);
private final long MODH = 10000000007L, BASE = 10007;
private final int[] DX = {0, 1, 0, -1}, DY = {-1, 0, 1, 0};
private ArrayList<Integer>[] edge;
public void foo()
{
int n = scan.nextInt();
int m = scan.nextInt();
int[] a = new int[m];
for(int i = 0;i < m;++i)
{
a[i] = scan.nextInt();
}
Arrays.sort(a);
long x = 1;
for(int i = 1;i <= n - m;++i)
{
x = x * i % MOD;
}
long y = 1;
for(int i = 1;i < a[0];++i)
{
y = y * i % MOD;
}
for(int i = 0;i < m - 1;++i)
{
for(int j = 1;j < a[i + 1] - a[i] - 1;++j)
{
y = y * j % MOD;
x = x * 2 % MOD;
}
if(a[i + 1] > a[i] + 1)
{
y = y * (a[i + 1] - a[i] - 1) % MOD;
}
}
for(int i = 1;i <= n - a[m - 1];++i)
{
y = y * i % MOD;
}
y = quickMod(y, MOD - 2);
long ans = x * y % MOD;
out.println(ans);
}
public static void main(String[] args)
{
Main m = new Main();
m.foo();
m.out.close();
}
/********************************************** a list of common algorithms **********************************************/
/**
* 1---Get greatest common divisor
* @param a : first number
* @param b : second number
* @return greatest common divisor
*/
public long gcd(long a, long b)
{
return 0 == b ? a : gcd(b, a % b);
}
/**
* 2---Get the distance from a point to a line
* @param x1 the x coordinate of one endpoint of the line
* @param y1 the y coordinate of one endpoint of the line
* @param x2 the x coordinate of the other endpoint of the line
* @param y2 the y coordinate of the other endpoint of the line
* @param x the x coordinate of the point
* @param y the x coordinate of the point
* @return the distance from a point to a line
*/
public double getDist(long x1, long y1, long x2, long y2, long x, long y)
{
long a = y2 - y1;
long b = x1 - x2;
long c = y1 * (x2 - x1) - x1 * (y2 - y1);
return Math.abs(a * x + b * y + c) / Math.sqrt(a * a + b * b);
}
/**
* 3---Get the distance from one point to a segment (not a line)
* @param x1 the x coordinate of one endpoint of the segment
* @param y1 the y coordinate of one endpoint of the segment
* @param x2 the x coordinate of the other endpoint of the segment
* @param y2 the y coordinate of the other endpoint of the segment
* @param x the x coordinate of the point
* @param y the y coordinate of the point
* @return the distance from one point to a segment (not a line)
*/
public double ptToSeg(long x1, long y1, long x2, long y2, long x, long y)
{
double cross = (x2 - x1) * (x - x1) + (y2 - y1) * (y - y1);
if(cross <= 0)
{
return (x - x1) * (x - x1) + (y - y1) * (y - y1);
}
double d = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
if(cross >= d)
{
return (x - x2) * (x - x2) + (y - y2) * (y - y2);
}
double r = cross / d;
double px = x1 + (x2 - x1) * r;
double py = y1 + (y2 - y1) * r;
return (x - px) * (x - px) + (y - py) * (y - py);
}
/**
* 4---KMP match, i.e. kmpMatch("abcd", "bcd") = 1, kmpMatch("abcd", "bfcd") = -1.
* @param t: String to match.
* @param p: String to be matched.
* @return if can match, first index; otherwise -1.
*/
public int kmpMatch(char[] t, char[] p)
{
int n = t.length;
int m = p.length;
int[] next = new int[m + 1];
next[0] = -1;
int j = -1;
for(int i = 1;i < m;++i)
{
while(j >= 0 && p[i] != p[j + 1])
{
j = next[j];
}
if(p[i] == p[j + 1])
{
++j;
}
next[i] = j;
}
j = -1;
for(int i = 0;i < n;++i)
{
while(j >= 0 && t[i] != p[j + 1])
{
j = next[j];
}
if(t[i] == p[j + 1])
{
++j;
}
if(j == m - 1)
{
return i - m + 1;
}
}
return -1;
}
/**
* 5---Get the hash code of a String
* @param s: input string
* @return hash code
*/
public long hash(String s)
{
long key = 0, t = 1;
for(int i = 0;i < s.length();++i)
{
key = (key + s.charAt(i) * t) % MODH;
t = t * BASE % MODH;
}
return key;
}
/**
* 6---Get x ^ n % MOD quickly.
* @param x: base
* @param n: times
* @return x ^ n % MOD
*/
public long quickMod(long x, long n)
{
long ans = 1;
while(n > 0)
{
if(1 == n % 2)
{
ans = ans * x % MOD;
}
x = x * x % MOD;
n >>= 1;
}
return ans;
}
class MyScanner
{
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
BufferedInputStream bis = new BufferedInputStream(System.in);
public int read()
{
if (-1 == numChars)
{
throw new InputMismatchException();
}
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = bis.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
{
return -1;
}
}
return buf[curChar++];
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
{
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c & 15;
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
{
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
m /= 10;
res += (c & 15) * m;
c = read();
}
}
return res * sgn;
}
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();
}
private boolean isSpaceChar(int c)
{
return ' ' == c || '\n' == c || '\r' == c || '\t' == c || -1 == c;
}
}
} | Java | ["3 1\n1", "4 2\n1 4", "11 2\n4 8"] | 1 second | ["1", "2", "6720"] | null | Java 7 | standard input | [
"combinatorics",
"number theory"
] | 14da0cdf2939c796704ec548f49efb87 | The first line of the input contains two integers n and m where n is the number of lights in the sequence and m is the number of lights which are initially switched on, (1 ≤ n ≤ 1000, 1 ≤ m ≤ n). The second line contains m distinct integers, each between 1 to n inclusive, denoting the indices of lights which are initially switched on. | 1,900 | In the only line of the output print the number of different possible ways to switch on all the lights modulo 1000000007 (109 + 7). | standard output | |
PASSED | ef811b4b0e367ef34a3c41f51c22ebd8 | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class cf605_3_4 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
int a[] = new int[n];
int left[] = new int[n];
int right[] = new int[n];
for(int i=0;i<n;i++) {
a[i] = sc.nextInt();
left[i]=1;
right[i] = 1;
}
for(int i=n-2;i>=0;i--) {
if(a[i] < a[i+1]) {
right[i] = right[i+1]+1;
}
}
for(int i=1;i<n;i++) {
if(a[i] > a[i-1]) {
left[i] = left[i-1]+1;
}
}
int ans=0;
for(int i=0;i<n;i++) {
ans = Math.max(ans, left[i]);
}
for(int i=1;i<n-1;i++) {
if(a[i-1] < a[i+1]) {
ans = Math.max(ans, left[i-1]+right[i+1]);
}
}
System.out.println(ans);
sc.close();
out.close();
}
}
| Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | 6f9d407a2f3d3a9902447f14f2e672a3 | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.util.*;
public class rc{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in) ;
int n = sc.nextInt();
int[] arr = new int[n];
for(int i=0; i<n; i++)
arr[i] = sc.nextInt();
int[] r = new int[n];
int[] l = new int[n];
r[0] = 1;
l[n-1] = 1;
int max=1;
for(int i=1; i<n; i++){
if(arr[i-1]<arr[i])
r[i] += r[i-1]+1;
else
r[i] = 1;
max = Math.max(max,r[i]);
}
for(int i=n-2; i>=0; --i){
if(arr[i]<arr[i+1])
l[i] += l[i+1]+1;
else
l[i] = 1;
max = Math.max(max, l[i]);
}
for(int i=1; i<n-1; i++){
if(arr[i-1]<arr[i+1])
max = Math.max(max, r[i-1]+l[i+1]);
}
System.out.println(max);
}
} | Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | e82cc6c16c01179eb06281b8fd394d20 | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static class pair implements Comparable<pair>{
int x;
int y;
public pair(int x, int y){
this.x=x;
this.y=y;
}
public int compareTo(pair p){
return (x-p.x==0)?y-p.y:x-p.x;
}}
static int n;
static int dp[][];
static int [] arr ;
// public static int solve(int i, int f){
// if(i>=n-1) return 1;
// // if(f>1) return -Integer.MAX_VALUE;
// if(dp[i][f][c]!=-1) return dp[i][f][c];
// if(c==1&&f>1){ return solve(i+1,0,0,0);}
// int take =(arr[i]<arr[i+1])? 1+solve(i+1,0,1):-Integer.MAX_VALUE;
// int leave =(arr[i]>arr[i+1])? solve(i+1,f+1,c):-Integer.MAX_VALUE;
// return dp[i][f][c] = Math.max(take,leave);
// }
static int seg(int[] a, int n)
{
int[] l = new int[n];
int[] r = new int[n + 1];
int ans = 0;
// calculating the l array.
l[0] = 1;
for (int i = 1; i < n; i++)
{
if (a[i] > a[i - 1])
{
l[i] = l[i - 1] + 1;
ans = Math.max(ans, l[i]);
}
else
l[i] = 1;
}
// if (ans != n)
// ++ans;
// calculating the r array.
r[n-1] = 1;
for (int i = n - 2; i > 0; i--)
{
if (a[i] < a[i+1])
r[i] = r[i + 1] + 1;
else
r[i] = 1;
}
// updating the answer.
for (int i = n - 2; i > 0; i--)
{
if (a[i + 1] - a[i - 1] > 0){
// System.out.println(ans+" "+i+" "+l[i-1] +" "+r[i+1]);
// if(a[i+1]>a[i]) r[i+1]--;
ans = Math.max(ans, l[i - 1] +r[i + 1]); }
else ans = Math.max(ans,1);
}
return Math.max(ans, r[0]);
}
public static void main(String[] args) throws IOException,InterruptedException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
// String s = br.readLine();
// char[] arr=s.toCharArray();
// ArrayList<Integer> arrl = new ArrayList<Integer>();
// TreeSet<Integer> ts1 = new TreeSet<Integer>();
// HashSet<Integer> h = new HashSet<Integer>();
// HashMap<Integer, Integer> map= new HashMap<>();
// PriorityQueue<String> pQueue = new PriorityQueue<String>();
// LinkedList<String> object = new LinkedList<String>();
// StringBuilder str = new StringBuilder();
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
arr = new int [n];
st = new StringTokenizer(br.readLine());
boolean f = true;
arr[0]= Integer.parseInt(st.nextToken());
for(int i=1; i<n; i++){
arr[i]= Integer.parseInt(st.nextToken());
if(arr[i]>arr[i-1]) f = false;
}
//dp = new int [n+1][2];
//for(int i=0; i<=n; i++){
// Arrays.fill(dp[i],-1);
//}
//int ans = solve(0,0);
out.println(Math.max(1,seg(arr,n)));
out.flush();
}
} | Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | 91174f608172f72ab763d4d2c08a6c0e | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static class pair implements Comparable<pair>{
int x;
int y;
public pair(int x, int y){
this.x=x;
this.y=y;
}
public int compareTo(pair p){
return (x-p.x==0)?y-p.y:x-p.x;
}}
static int n;
static int dp[][];
static int [] arr ;
// public static int solve(int i, int f){
// if(i>=n-1) return 1;
// // if(f>1) return -Integer.MAX_VALUE;
// if(dp[i][f][c]!=-1) return dp[i][f][c];
// if(c==1&&f>1){ return solve(i+1,0,0,0);}
// int take =(arr[i]<arr[i+1])? 1+solve(i+1,0,1):-Integer.MAX_VALUE;
// int leave =(arr[i]>arr[i+1])? solve(i+1,f+1,c):-Integer.MAX_VALUE;
// return dp[i][f][c] = Math.max(take,leave);
// }
static int seg(int[] a, int n)
{
int[] l = new int[n];
int[] r = new int[n + 1];
int ans = 0;
// calculating the l array.
l[0] = 1;
for (int i = 1; i < n; i++)
{
if (a[i] > a[i - 1])
{
l[i] = l[i - 1] + 1;
}
else
l[i] = 1;
ans = Math.max(ans, l[i]);
}
// if (ans != n)
// ++ans;
// calculating the r array.
r[n-1] = 1;
for (int i = n - 2; i > 0; i--)
{
if (a[i] < a[i+1])
r[i] = r[i + 1] + 1;
else
r[i] = 1;
}
// updating the answer.
for (int i = n - 2; i > 0; i--)
{
if (a[i + 1] - a[i - 1] > 0){
// System.out.println(ans+" "+i+" "+l[i-1] +" "+r[i+1]);
// if(a[i+1]>a[i]) r[i+1]--;
ans = Math.max(ans, l[i - 1] +r[i + 1]); }
}
return Math.max(ans, r[0]);
}
public static void main(String[] args) throws IOException,InterruptedException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
// String s = br.readLine();
// char[] arr=s.toCharArray();
// ArrayList<Integer> arrl = new ArrayList<Integer>();
// TreeSet<Integer> ts1 = new TreeSet<Integer>();
// HashSet<Integer> h = new HashSet<Integer>();
// HashMap<Integer, Integer> map= new HashMap<>();
// PriorityQueue<String> pQueue = new PriorityQueue<String>();
// LinkedList<String> object = new LinkedList<String>();
// StringBuilder str = new StringBuilder();
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
arr = new int [n];
st = new StringTokenizer(br.readLine());
boolean f = true;
arr[0]= Integer.parseInt(st.nextToken());
for(int i=1; i<n; i++){
arr[i]= Integer.parseInt(st.nextToken());
if(arr[i]>arr[i-1]) f = false;
}
//dp = new int [n+1][2];
//for(int i=0; i<=n; i++){
// Arrays.fill(dp[i],-1);
//}
//int ans = solve(0,0);
out.println(seg(arr,n));
out.flush();
}
} | Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | 34bd9104d33b6f2cb6cf46b0c7daa01f | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class practicing {
static class tri {
int l;
int last;
int beg;
public tri(int m, int b,int ma) {
l = m;
last = ma;
beg=b;
}
}
static long pow(long n, int e) {
long res = 1;
while (e-- > 0) {
res *= n;
}
return res;
}
static long abs(long a, long b) {
if (a > b)
return a - b;
return b - a;
}
static boolean pairwiseEq(long a, long b, long c) {
if (a == b || b == c || c == a)
return true;
return false;
}
public static void main(String[] args) throws IOException {
//BufferedReader br = new BufferedReader(new FileReader("folding.in"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
//PrintWriter out = new PrintWriter("folding.out");
PrintWriter out = new PrintWriter(System.out);
int n = Integer.parseInt(br.readLine());
long []a=new long[n];
st=new StringTokenizer(br.readLine());
for (int i = 0; i <n ; i++) {
a[i]=Long.parseLong(st.nextToken());
}
ArrayList<Integer>bP=new ArrayList<>();
ArrayList<tri>sub=new ArrayList<>();
bP.add((0));
long last=a[0];
int beg=0;
for (int i = 1; i <n ; i++) {
if(a[i]>last){
last=a[i];
if(i==n-1) {
sub.add(new tri(n - bP.get(bP.size() - 1), beg,n - 1));
//System.err.println(i + " " + bP.get(bP.size() - 1));
}
}
else {
last=a[i];
sub.add(new tri(i- bP.get(bP.size()-1),beg,i-1));
// System.err.println(i+" "+bP.get(bP.size()-1));
bP.add(i);
beg=i;
if(i==n-1){
sub.add(new tri(1,n-1,n-1));
}
}
}
int lengthinit=sub.get(0).l;
int max=lengthinit;
for (int i = 1; i <sub.size() ; i++) {
if(sub.get(i).beg<n-1&&a[sub.get(i-1).last]<a[sub.get(i).beg+1])
max=Math.max(max,lengthinit+sub.get(i).l-1);
else {
if(sub.get(i-1).last-1>0&&a[sub.get(i-1).last-1]<a[sub.get(i).beg])
max=Math.max(max,lengthinit+sub.get(i).l-1);
}
max=Math.max(max,lengthinit);
lengthinit=sub.get(i).l;
}
max=Math.max(max,lengthinit);
out.println(max);
out.flush();
}
}
| Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | ae67a35fcf31832e18c62b45c89b28b3 | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class cf1 {
static long mod = (long)1e9 + 7;
static long mod1 = 998244353;
static FastScanner f;
static PrintWriter pw = new PrintWriter(System.out);
static Scanner S = new Scanner(System.in);
static long x0; static long y0;
static int inf = (int)(1e9);
static long iinf = (long)(1e18);
static void solve()throws IOException {
int n = f.ni();
int arr[] = inpint(n);
int l[] = new int[n]; Arrays.fill(l, 1);
int r[] = new int[n]; Arrays.fill(r , 1);
int max = 1;
for (int i = 1; i < n; ++i) {
if (arr[i] > arr[i - 1]) l[i] = l[i - 1] + 1;
}
for (int i = n - 2; i >= 0; --i) {
if (arr[i] < arr[i + 1]) r[i] = r[i + 1] + 1;
max = Math.max(max , r[i]);
}
for (int i = 0; i < n - 2; ++i) {
if (arr[i] < arr[i + 2]) {
max = Math.max(max , l[i] + r[i + 2]);
}
}
pn(max);
}
public static void main(String[] args)throws IOException {
init();
int t = 1;
while(t --> 0) {solve();}
pw.flush();
pw.close();
}
/******************************END OF MAIN PROGRAM*******************************************/
public static void init()throws IOException{if(System.getProperty("ONLINE_JUDGE")==null){f=new FastScanner("");}else{f=new FastScanner(System.in);}}
public static class FastScanner {
BufferedReader br;StringTokenizer st;
FastScanner(InputStream stream){try{br=new BufferedReader(new InputStreamReader(stream));}catch(Exception e){e.printStackTrace();}}
FastScanner(String str){try{br=new BufferedReader(new FileReader("!a.txt"));}catch(Exception e){e.printStackTrace();}}
String next(){while(st==null||!st.hasMoreTokens()){try{st=new StringTokenizer(br.readLine());}catch(IOException e){e.printStackTrace();}}return st.nextToken();}
String nextLine()throws IOException{return br.readLine();}int ni(){return Integer.parseInt(next());}long nl(){return Long.parseLong(next());}double nextDouble(){return Double.parseDouble(next());}
}
public static void pn(Object o){pw.println(o);}
public static void p(Object o){pw.print(o);}
public static void pni(Object o){pw.println(o);pw.flush();}
static int gcd(int a,int b){if(b==0)return a;else{return gcd(b,a%b);}}
static long gcd(long a,long b){if(b==0l)return a;else{return gcd(b,a%b);}}
static long lcm(long a,long b){return (a*b/gcd(a,b));}
static long exgcd(long a,long b){if(b==0){x0=1;y0=0;return a;}long temp=exgcd(b,a%b);long t=x0;x0=y0;y0=t-a/b*y0;return temp;}
static long pow(long a,long b){long res=1;while(b>0){if((b&1)==1)res=res*a;b>>=1;a=a*a;}return res;}
static long mpow(long a,long b){long res=1;while(b>0l){if((b&1)==1l)res=((res%mod)*(a%mod))%mod;b>>=1l;a=((a%mod)*(a%mod))%mod;}return res;}
static long mul(long a , long b){return ((a%mod)*(b%mod)%mod);}
static long adp(long a , long b){return ((a%mod)+(b%mod)%mod);}
static int log2(int x){return (int)(Math.log(x)/Math.log(2));}
static boolean isPrime(long n){if(n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(long i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;}
static boolean isPrime(int n){if(n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(int i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;}
static HashSet<Long> factors(long n){HashSet<Long> hs=new HashSet<Long>();for(long i=1;i<=(long)Math.sqrt(n);i++){if(n%i==0){hs.add(i);hs.add(n/i);}}return hs;}
static HashSet<Integer> factors(int n){HashSet<Integer> hs=new HashSet<Integer>();for(int i=1;i<=(int)Math.sqrt(n);i++){if(n%i==0){hs.add(i);hs.add(n/i);}}return hs;}
static HashSet<Long> pf(long n){HashSet<Long> ff=factors(n);HashSet<Long> ans=new HashSet<Long>();for(Long i:ff)if(isPrime(i))ans.add(i);return ans;}
static HashSet<Integer> pf(int n){HashSet<Integer> ff=factors(n);HashSet<Integer> ans=new HashSet<Integer>();for(Integer i:ff)if(isPrime(i))ans.add(i);return ans;}
static int[] inpint(int n){int arr[]=new int[n];for(int i=0;i<n;i++){arr[i]=f.ni();}return arr;}
static long[] inplong(int n){long arr[] = new long[n];for(int i=0;i<n;i++){arr[i]=f.nl();}return arr;}
static boolean ise(int x){return ((x&1)==0);}static boolean ise(long x){return ((x&1)==0);}
static int gnv(char c){return Character.getNumericValue(c);}//No. of integers less than equal to i in ub
static int log(long x){return x==1?0:(1+log(x/2));} static int log(int x){return x==1?0:(1+log(x/2));}
static int upperbound(int a[],int i){int lo=0,hi=a.length-1,mid=0;int count=0;while(lo<=hi){mid=(lo+hi)/2;if(a[mid]<=i){count=mid+1;lo=mid+1;}else hi=mid-1;}return count;}
static void sort(int[] a){ArrayList<Integer> l=new ArrayList<>();for(int i:a)l.add(i);Collections.sort(l);for(int i=0;i<a.length;++i)a[i]=l.get(i);}
static void sort(long[] a){ArrayList<Long> l=new ArrayList<>();for(long i:a)l.add(i);Collections.sort(l);for(int i=0;i<a.length;++i)a[i]=l.get(i);}
static void sort(ArrayList<Integer> a){Collections.sort(a);}//!Precompute fact in ncr()!
static int nextPowerOf2(int n){int count=0;if(n>0&&(n&(n-1))==0)return n;while(n!=0){n>>=1;count += 1;}return 1<<count;}
} | Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | 341bb27cacf2f749853a13105d57b454 | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.util.Scanner;
public class RemoveElement {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[] a = new int[n];
for(int i=0;i<n;i++)
a[i]=input.nextInt();
int[] start = new int[n];
int[] end = new int[n];
end[0]=1;
start[n-1]=1;
int max = 1;
for(int i=1;i<n;i++) {
if(a[i]>a[i-1])
end[i]+=end[i-1]+1;
else
end[i]=1;
max = Math.max(max, end[i]);
}
for(int i=n-2;i>=0;i--) {
if(a[i]<a[i+1])
start[i]+=start[i+1]+1;
else
start[i]=1;
max = Math.max(start[i],max);
}
for(int i=1;i<n-1;i++) {
if(a[i+1]>a[i-1])
max = Math.max(max, end[i-1]+start[i+1]);
}
System.out.println(max);
}
} | Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | 13326ae8da1d3392694fdfbd866d4e5a | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.util.*;
import java.io.*;
import java.io.FileWriter;
import java.math.BigInteger;
import java.math.BigDecimal;
// Solution
public class Main
{
public static void main (String[] argv)
{
new Main();
}
boolean test = false;
final int[][] dirs8 = {{0,1}, {0,-1}, {-1,0}, {1,0}, {1,1},{1,-1},{-1,1},{-1,-1}};
final int[][] dirs4 = {{0,1}, {0,-1}, {-1,0}, {1,0}};
final int MOD = 1000000007; //998244353;
final int WALL = -1;
final int EMPTY = -2;
final int VISITED = 1;
final int FULL = 2;
final int START = 1;
final int END = 0;
int[] fac;
int[] ifac;
int[] rfac;
int[] pow2;
int[] mobius;
int[] sieve;
int[][] factors;
final int UNVISITED = -2;
public Main() {
FastReader in = new FastReader(new BufferedReader(new InputStreamReader(System.in)));
//FastReader in = new FastReader(new BufferedReader(new FileReader("Main.in")));
//int nt = in.nextInt();
int nt = 1;
StringBuilder sb = new StringBuilder();
for (int it = 0; it < nt; it++)
{
//long k = in.nextLong();
int n = in.nextInt();
int[] a = new int[1+n];
for (int i = 1; i <= n; i++) a[i] = in.nextInt();
//dp: longest ending at position i, one removed
//dpf: longest ending at position i, none removed
// dpf[i] = 1 OR 1 + dpf[i-1]
// dp[i] = (1) remove i-1 : 1 OR dpf[i-2] + 1
// (2) Keep i-1 : 1 OR dp[i-1] + 1
if (n == 2)
{
int ans = 1;
if (a[1] < a[2])
ans = 2;
System.out.println(ans);
return;
}
int dpf1 = 1, dpf = 1;
if (a[1] < a[2]) dpf = 2;
int dp = 1;
int ans = dpf;
for (int i = 3; i <= n; i++)
{
int cur_f = 1;
if (a[i] > a[i-1]) {
cur_f = dpf + 1;
}
int cur_dp = 0;
if (a[i] <= a[i-1]) cur_dp = 1;
else cur_dp = 1 + dp;
if (a[i] > a[i-2] && dpf1 + 1 > cur_dp)
cur_dp = dpf1 + 1;
dp = cur_dp;
dpf1 = dpf;
dpf = cur_f;
//System.out.println("i = " + i + " cur_dp = " + cur_dp + " , f = " + cur_f);
if (dp > ans) ans = dp;
if (dpf > ans) ans = dpf;
}
System.out.println(ans);
}
//System.out.println(sb);
}
class Node implements Comparable<Node>{
int lo, hi;
public Node(int lo, int hi)
{
this.lo = lo;
this.hi = hi;
}
@Override
public int compareTo(Node o){
if (lo != o.lo) return lo - o.lo;
return hi - o.hi;
}
}
private long[][] matIdentity(int n)
{
long[][] a = new long[n][n];
for (int i = 0; i < n; i++)
a[i][i] = 1;
return a;
}
private long[][] matPow(long[][] mat0, long p)
{
int n = mat0.length;
long[][] ans = matIdentity(n);
long[][] mat = matCopy(mat0);
while (p > 0)
{
if (p % 2 == 1){
ans = matMul(ans, mat);
}
p /= 2;
mat = matMul(mat, mat);
}
return ans;
}
private long[][] matCopy(long[][] a)
{
int n = a.length;
long[][] b = new long[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
b[i][j] = a[i][j];
return b;
}
private long[][] matMul(long[][] a, long[][] b)
{
int n = a.length;
long[][] c = new long[n][n];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
for (int k = 0; k < n; k++)
c[i][j] = (c[i][j] + a[i][k] * b[k][j]) % MOD;
}
}
return c;
}
private long[] matMul(long[][] a, long[] b)
{
int n = a.length;
long[] c = new long[n];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
c[i] = (c[i] + a[i][j] * b[j]) % MOD;
}
return c;
}
class Mark implements Comparable<Mark> {
int type, h;
long x;
public Mark(int h, long x, int type)
{
this.h = h;
this.x = x;
this.type = type;
}
@Override
public int compareTo(Mark o)
{
if (this.x == o.x) return type - o.type; // let end comes before start
return Long.compare(x, o.x);
}
}
private boolean coLinear(int[] p, int[] q, int[] r)
{
return 1L * (p[1] - r[1]) * (q[0] - r[0]) == 1L * (q[1] - r[1]) * (p[0] - r[0]);
}
private void fill(char[] a, int lo, int c, char letter)
{
//System.out.println("fill " + lo + " " + c + " " + letter);
for (int i = lo; i < lo + c; i++) a[i] = letter;
}
private int cntBitOne(String s){
int c = 0, n = s.length();
for (int i = 0; i < n; i++)
if (s.charAt(i) == '1') c++;
return c;
}
class DSU {
int n;
int[] par;
int[] sz;
int nGroup;
public DSU(int n)
{
this.n = n;
par = new int[n];
sz = new int[n];
for (int i = 0; i < n; i++){
par[i] = i;
sz[i] = 1;
}
nGroup = n;
}
private boolean add(int p, int q) {
int rp = find(p);
int rq = find(q);
if (rq == rp) return false;
if (sz[rp] <= sz[rq]) {
sz[rq] += sz[rp];
par[rp] = rq;
}else {
sz[rp] += sz[rq];
par[rq] = rp;
}
nGroup--;
return true;
}
private int find(int p)
{
int r = p;
while (par[r] != r) r = par[r];
while (r != p) {
int t = par[p];
par[p] = r;
p = t;
}
return r;
}
}
// μ(n) = 1 if n is a square-free positive integer with an even number of prime factors. e.g. 6, 15
// μ(n) = −1 if n is a square-free positive integer with an odd number of prime factors. e.g. 2, 3, 5, 2*3*5
// μ(n) = 0 if n has a squared prime factor. e.g : 2*2, 3*3*5
private void build_pow2_function(int n)
{
pow2 = new int[n+1];
pow2[0] = 1;
for (int i = 1; i <= n; i++) pow2[i] = (int)(1L * pow2[i-1] * 2 % MOD);
}
private void build_fac_function(int n)
{
fac = new int[n+1];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = (int)(1L * fac[i-1] * i % MOD);
}
private void build_ifac_function(int n)
{
ifac = new int[n+1];
ifac[0] = 1;
for (int i = 1; i <= n; i++)
ifac[i] = (int)(1L * ifac[i-1] * inv(i) % MOD);
}
private void build_sieve_function(int n)
{
sieve = new int[n+1];
for (int i = 2; i <= n; i++)
sieve[i] = i;
for (int i = 2; i <= n; i++)
{
if (sieve[i] == i){
for (long j = 1L * i * i; j <= n; j += i)
sieve[(int)j] = i;
}
}
}
private void build_mobius_function(int n)
{
mobius = new int[n+1];
sieve = new int[n+1];
factors = new int[n+1][];
//for (int i = 1; i <= n; i++)factors[i] = new ArrayList<>();
for (int i = 2; i <= n; i++)
sieve[i] = i;
for (int i = 2; i <= n; i++)
{
if (sieve[i] == i){
mobius[i] = -1;
for (long j = 1L * i * i; j <= n; j += i)
sieve[(int)j] = i;
}
}
for (int i = 6; i <= n; i++)
{
if (sieve[i] != i) {
int pre = i / sieve[i];
if (pre % sieve[i] != 0)
mobius[i] = -mobius[pre];
}
}
int[] sz = new int[n+1];
long tot = 0;
for (int i = 2; i <= n; i++)
{
if (mobius[i] != 0)
{
for (int j = i * 2; j <= n; j += i) {
sz[j]++;
tot++;
}
}
}
for (int i = 2; i <= n; i++) {
factors[i] = new int[sz[i]];
sz[i] = 0;
}
for (int i = 2; i <= n; i++)
{
if (mobius[i] != 0)
{
for (int j = i * 2; j <= n; j += i) {
factors[j][sz[j]++] = i;
//factors[j].add(i);
}
}
}
//System.out.println("tot = " + tot);
}
private int[] build_z_function(String s)
{
int n = s.length();
int[] zfun = new int[n];
int l = -1, r = -1;
for (int i = 1; i < n; i++)
{
// Set the start value
if (i <= r)
zfun[i] = Math.min(zfun[i-l], r - i + 1);
while (i + zfun[i] < n && s.charAt(i + zfun[i]) == s.charAt(zfun[i]))
zfun[i]++;
if (i + zfun[i] - 1> r){
l = i;
r = i + zfun[i] - 1;
}
}
if (test)
{
System.out.println("Z-function of " + s);
for (int i = 0; i < n; i++) System.out.print(zfun[i] + " ");
System.out.println();
}
return zfun;
}
class BIT {
int[] bit;
int n;
public BIT(int n){
this.n = n;
bit = new int[n+1];
}
private int query(int p)
{
int sum = 0;
for (; p > 0; p -= (p & (-p)))
sum += bit[p];
return sum;
}
private void add(int p, int val)
{
//System.out.println("add to BIT " + p);
for (; p <= n; p += (p & (-p)))
bit[p] += val;
}
}
private List<Integer> getMinFactor(int sum)
{
List<Integer> factors = new ArrayList<>();
for (int sz = 2; sz <= sum / sz; sz++){
if (sum % sz == 0) {
factors.add(sz);
factors.add(sum / sz);
}
}
if (factors.size() == 0)
factors.add(sum);
return factors;
}
/* Tree class */
class Tree {
int V = 0;
int root = 0;
List<Integer>[] nbs;
int[][] timeRange;
int[] subTreeSize;
int t;
boolean dump = false;
public Tree(int V, int root)
{
if (dump)
System.out.println("build tree with size = " + V + ", root = " + root);
this.V = V;
this.root = root;
nbs = new List[V];
subTreeSize = new int[V];
for (int i = 0; i < V; i++)
nbs[i] = new ArrayList<>();
}
public void doneInput()
{
dfsEuler();
}
public void addEdge(int p, int q)
{
nbs[p].add(q);
nbs[q].add(p);
}
private void dfsEuler()
{
timeRange = new int[V][2];
t = 1;
dfs(root);
}
private void dfs(int node)
{
if (dump)
System.out.println("dfs on node " + node + ", at time " + t);
timeRange[node][0] = t;
for (int next : nbs[node]) {
if (timeRange[next][0] == 0)
{
++t;
dfs(next);
}
}
timeRange[node][1] = t;
subTreeSize[node] = t - timeRange[node][0] + 1;
}
public List<Integer> getNeighbors(int p) {
return nbs[p];
}
public int[] getSubTreeSize(){
return subTreeSize;
}
public int[][] getTimeRange()
{
if (dump){
for (int i = 0; i < V; i++){
System.out.println(i + ": " + timeRange[i][0] + " - " + timeRange[i][1]);
}
}
return timeRange;
}
}
/* segment tree */
class SegTree {
int[] a;
int[] tree;
int[] treeMin;
int[] treeMax;
int[] lazy;
int n;
boolean dump = false;
public SegTree(int n)
{
if (dump)
System.out.println("create segTree with size " + n);
this.n = n;
treeMin = new int[n*4];
treeMax = new int[n*4];
lazy = new int[n*4];
}
public SegTree(int n, int[] a) {
this(n);
this.a = a;
buildTree(1, 0, n-1);
}
private void buildTree(int node, int lo, int hi)
{
if (lo == hi) {
tree[node] = lo;
return;
}
int m = (lo + hi) / 2;
buildTree(node * 2, lo, m);
buildTree(node * 2 + 1, m + 1, hi);
pushUp(node, lo, hi);
}
private void pushUp(int node, int lo, int hi)
{
if (lo >= hi) return;
// note that, if we need to call pushUp on a node, then lazy[node] must be zero.
//the true value is the value + lazy
treeMin[node] = Math.min(treeMin[node * 2] + lazy[node * 2], treeMin[node * 2 + 1] + lazy[node * 2 + 1]);
treeMax[node] = Math.max(treeMax[node * 2] + lazy[node * 2], treeMax[node * 2 + 1] + lazy[node * 2 + 1]);
// add combine fcn
}
private void pushDown(int node, int lo, int hi)
{
if (lazy[node] == 0) return;
int lz = lazy[node];
lazy[node] = 0;
treeMin[node] += lz;
treeMax[node] += lz;
if (lo == hi) return;
int mid = (lo + hi) / 2;
lazy[node * 2] += lz;
lazy[node * 2 + 1] += lz;
}
public int rangeQueryMax(int fr, int to)
{
return rangeQueryMax(1, 0, n-1, fr, to);
}
public int rangeQueryMax(int node, int lo, int hi, int fr, int to)
{
if (lo == fr && hi == to)
return treeMax[node] + lazy[node];
int mid = (lo + hi) / 2;
pushDown(node, lo, hi);
if (to <= mid) {
return rangeQueryMax(node * 2, lo, mid, fr, to);
}else if (fr > mid)
return rangeQueryMax(node * 2 + 1, mid + 1, hi, fr, to);
else {
return Math.max(rangeQueryMax(node * 2, lo, mid, fr, mid),
rangeQueryMax(node * 2 + 1, mid + 1, hi, mid + 1, to));
}
}
public int rangeQueryMin(int fr, int to)
{
return rangeQueryMin(1, 0, n-1, fr, to);
}
public int rangeQueryMin(int node, int lo, int hi, int fr, int to)
{
if (lo == fr && hi == to)
return treeMin[node] + lazy[node];
int mid = (lo + hi) / 2;
pushDown(node, lo, hi);
if (to <= mid) {
return rangeQueryMin(node * 2, lo, mid, fr, to);
}else if (fr > mid)
return rangeQueryMin(node * 2 + 1, mid + 1, hi, fr, to);
else {
return Math.min(rangeQueryMin(node * 2, lo, mid, fr, mid),
rangeQueryMin(node * 2 + 1, mid + 1, hi, mid + 1, to));
}
}
public void rangeUpdate(int fr, int to, int delta){
rangeUpdate(1, 0, n-1, fr, to, delta);
}
public void rangeUpdate(int node, int lo, int hi, int fr, int to, int delta){
pushDown(node, lo, hi);
if (fr == lo && to == hi)
{
lazy[node] = delta;
return;
}
int m = (lo + hi) / 2;
if (to <= m)
rangeUpdate(node * 2, lo, m, fr, to, delta);
else if (fr > m)
rangeUpdate(node * 2 + 1, m + 1, hi, fr, to, delta);
else {
rangeUpdate(node * 2, lo, m, fr, m, delta);
rangeUpdate(node * 2 + 1, m + 1, hi, m + 1, to, delta);
}
// re-set the in-variant
pushUp(node, lo, hi);
}
public int query(int node, int lo, int hi, int fr, int to)
{
if (fr == lo && to == hi)
return tree[node];
int m = (lo + hi) / 2;
if (to <= m)
return query(node * 2, lo, m, fr, to);
else if (fr > m)
return query(node * 2 + 1, m + 1, hi, fr, to);
int lid = query(node * 2, lo, m, fr, m);
int rid = query(node * 2 + 1, m + 1, hi, m + 1, to);
return a[lid] >= a[rid] ? lid : rid;
}
}
private long inv(long v)
{
return pow(v, MOD-2);
}
private long pow(long v, long p)
{
long ans = 1;
while (p > 0)
{
if (p % 2 == 1)
ans = ans * v % MOD;
v = v * v % MOD;
p = p / 2;
}
return ans;
}
private double dist(double x, double y, double xx, double yy)
{
return Math.sqrt((xx - x) * (xx - x) + (yy - y) * (yy - y));
}
private int mod_add(int a, int b) {
int v = a + b;
if (v >= MOD) v -= MOD;
return v;
}
private long overlap(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {
if (x1 > x3) return overlap(x3, y3, x4, y4, x1, y1, x2, y2);
if (x3 > x2 || y4 < y1 || y3 > y2) return 0L;
//(x3, ?, x2, ?)
int yL = Math.max(y1, y3);
int yH = Math.min(y2, y4);
int xH = Math.min(x2, x4);
return f(x3, yL, xH, yH);
}
//return #black cells in rectangle
private long f(int x1, int y1, int x2, int y2) {
long dx = 1L + x2 - x1;
long dy = 1L + y2 - y1;
if (dx % 2 == 0 || dy % 2 == 0 || (x1 + y1) % 2 == 0)
return 1L * dx * dy / 2;
return 1L * dx * dy / 2 + 1;
}
private int distM(int x, int y, int xx, int yy) {
return abs(x - xx) + abs(y - yy);
}
private boolean less(int x, int y, int xx, int yy) {
return x < xx || y > yy;
}
private int mul(int x, int y) {
return (int)(1L * x * y % MOD);
}
private int nBit1(int v) {
int v0 = v;
int c = 0;
while (v != 0) {
++c;
v = v & (v - 1);
}
return c;
}
private long abs(long v) {
return v > 0 ? v : -v;
}
private int abs(int v) {
return v > 0 ? v : -v;
}
private int common(int v) {
int c = 0;
while (v != 1) {
v = (v >>> 1);
++c;
}
return c;
}
private void reverse(char[] a, int i, int j) {
while (i < j) {
swap(a, i++, j--);
}
}
private void swap(char[] a, int i, int j) {
char t = a[i];
a[i] = a[j];
a[j] = t;
}
private int gcd(int x, int y) {
if (y == 0) return x;
return gcd(y, x % y);
}
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 long max(long a, long b) {
return a > b ? a : b;
}
private int min(int a, int b) {
return a > b ? b : a;
}
private long min(long a, long 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 null;
//e.printStackTrace();
}
return str;
}
}
} | Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | b58f0c85613dd203d762b52561a01344 | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes |
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long arr[] = new long[n];
for(int i = 0; i < n; ++i)
arr[i] = sc.nextLong();
int lis[] = new int[n];
int lds[] = new int[n];
Arrays.fill(lis, 1);
Arrays.fill(lds, 1);
int ans = 1;
for(int i = 1; i < n; ++i){
if(arr[i - 1] < arr[i]){
lis[i] = lis[i - 1] + 1;
ans = Math.max(ans, lis[i]);
}
}
for(int i = n - 2; i >= 0; --i){
if(arr[i] < arr[i + 1 ]){
lds[i] = lds[i + 1] + 1;
}
}
// System.out.println("lis");
// for(int a : lis)
// System.out.print(a +", ");
// System.out.println("\nlds");
// for(int a : lds)
// System.out.print(a +", ");
// System.out.println();
// int ans = 1;
if(lis[n - 1] == n)
ans = n;
else{
for(int i = 1; i < n - 1; ++i){
if(arr[i - 1] < arr[i + 1]){
ans = Math.max(ans, lis[i - 1] + lds[i + 1]);
}
}
}
System.out.println(ans);
}
} | Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | 2d11fc32c13ce02f1d067df037d1d476 | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class Solution implements Runnable
{
public static void main(String args[]) throws Exception{new Thread(null, new Solution(),"Main",1<<27).start();}
public void run()
{
InputReader in = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int n=in.nextInt();
int[] arr=new int[n];
for(int i=0;i<n;i++)
arr[i]=in.nextInt();
int max=0;
int temp=1;
int flag=0;
int min=arr[0];
int ind=0;
for(int i=1;i<n-1;i++){
if(arr[i]<=min){
if(flag==0){
if(arr[i+1]>arr[i-1]){
flag=1;
ind=i;
}
else if(i!=1 && arr[i]>arr[i-2]){
flag=1;
min=arr[i];
ind=i;
}
else{
min=arr[i];
max=Math.max(max,temp);
temp=1;
flag=0;
}
}
else{
max=Math.max(max,temp);
temp=i-ind;
if(arr[i+1]>arr[i-1]){
flag=1;
ind=i;
}
else if(i!=1 && arr[i]>arr[i-2]){
flag=1;
min=arr[i];
ind=i;
}
else{
min=arr[i];
max=Math.max(max,temp);
temp=1;
flag=0;
}
}
continue;
}
temp++;
min=arr[i];
}
if(arr[n-1]>min)
temp++;
max=Math.max(max,temp);
w.println(max);
w.flush();
w.close();
}
static class InputReader
{
private InputStream stream;private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream){this.stream = stream;}
public int read(){if (numChars==-1) throw new InputMismatchException();if (curChar >= numChars){curChar = 0;try{numChars = stream.read(buf);}catch (IOException e){throw new InputMismatchException(); }if(numChars <= 0)return -1;}return buf[curChar++];}
public String nextLine(){String str = "";try{str = br.readLine();}catch (IOException e){e.printStackTrace();}return str;}
public int nextInt(){int c = read(); while(isSpaceChar(c))c = read(); int sgn = 1; if (c == '-'){sgn = -1;c = read(); }int res = 0;do{if(c<'0'||c>'9') throw new InputMismatchException();res *= 10;res += c - '0';c = read();}while (!isSpaceChar(c));return res * sgn;}
public long nextLong(){int c = read();while (isSpaceChar(c))c = read();int sgn = 1;if (c == '-'){sgn = -1;c = read();}long res = 0;do{if (c < '0' || c > '9')throw new InputMismatchException();res *= 10;res += c - '0';c = read();}while (!isSpaceChar(c));return res * sgn;}
public double nextDouble(){int c = read();while (isSpaceChar(c))c = read();int sgn = 1;if (c == '-'){sgn = -1;c = read();}double res = 0;while (!isSpaceChar(c) && c != '.'){if (c == 'e' || c == 'E')return res * Math.pow(10, nextInt());if (c < '0' || c > '9')
throw new InputMismatchException();res *= 10;res += c - '0';c = read();}if (c == '.'){c = read();double m = 1;while (!isSpaceChar(c)){if (c == 'e' || c == 'E')return res * Math.pow(10, nextInt());if (c < '0' || c > '9')throw new InputMismatchException();m /= 10;res += (c - '0') * m;c = read();}}return res * sgn;}
public String readString(){int c = read();while (isSpaceChar(c))c = read();StringBuilder res = new StringBuilder();do{res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();}
public boolean isSpaceChar(int c){if (filter != null)return filter.isSpaceChar(c);return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;}
public String next(){return readString();}
public interface SpaceCharFilter{public boolean isSpaceChar(int ch);}
}
public static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a);}
public static long findGCD(long arr[], int n) { long result = arr[0]; for (int i = 1; i < n; i++) result = gcd(arr[i], result);return result; }
static void sortbycolomn(long arr[][], int col)
{
Arrays.sort(arr, new Comparator<long[]>() {
@Override
public int compare(final long[] entry1,final long[] entry2) {
if (entry1[col] > entry2[col])return 1;
else return -1;
}
});
}
} | Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | 825aa6faf1272dccab67617a1aed3a69 | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class p1272D {
public int n;
public int[] a;
public int[][][][] memo;
public int[][][][] memo2;
public int dp(int ind, int usedremove, int dominustwo, int isstart) {
if(ind >= n) {
return 0;
}
if(memo[ind][usedremove][dominustwo][isstart] != -1) {
return memo[ind][usedremove][dominustwo][isstart];
}
if(isstart == 1) {
memo[ind][usedremove][dominustwo][isstart] = 1 + dp(ind + 1, 0, 0, 0);
return memo[ind][usedremove][dominustwo][isstart] ;
}
int offset = 1;
if(dominustwo == 1) {
offset = 2;
}
if(ind - offset < 0) {
memo[ind][usedremove][dominustwo][isstart] = 0 + dp(ind + 1, usedremove, 0, 0);
return memo[ind][usedremove][dominustwo][isstart];
}
if(a[ind] <= a[ind - offset]) {
if(usedremove == 1) {
memo[ind][usedremove][dominustwo][isstart] = 0;
return memo[ind][usedremove][dominustwo][isstart] ;
}
memo[ind][usedremove][dominustwo][isstart] = 0 + dp(ind, 1, 1, 0);
return memo[ind][usedremove][dominustwo][isstart] ;
}
memo[ind][usedremove][dominustwo][isstart] = 1 + dp(ind + 1, usedremove, 0, 0);
if(dominustwo == 1) {
memo[ind][usedremove][dominustwo][isstart]--;
}
return memo[ind][usedremove][dominustwo][isstart] ;
}
public int dp2(int ind, int usedremove, int dominustwo, int isstart) {
if(ind >= n) {
return 0;
}
if(memo2[ind][usedremove][dominustwo][isstart] != -1) {
return memo2[ind][usedremove][dominustwo][isstart];
}
if(isstart == 1) {
memo2[ind][usedremove][dominustwo][isstart] = 1 + dp2(ind + 1, 0, 0, 0);
return memo2[ind][usedremove][dominustwo][isstart] ;
}
int offset = 1;
if(dominustwo == 1) {
offset = 2;
}
if(ind - offset < 0) {
memo2[ind][usedremove][dominustwo][isstart] = 0 + dp2(ind + 1, usedremove, 0, 0);
return memo2[ind][usedremove][dominustwo][isstart];
}
if(a[ind] <= a[ind - offset]) {
if(usedremove == 1) {
memo2[ind][usedremove][dominustwo][isstart] = 0;
return memo2[ind][usedremove][dominustwo][isstart] ;
}
memo2[ind][usedremove][dominustwo][isstart] = 0 + dp2(ind + 1, 1, 1, 0);
return memo2[ind][usedremove][dominustwo][isstart] ;
}
memo2[ind][usedremove][dominustwo][isstart] = 1 + dp2(ind + 1, usedremove, 0, 0);
if(dominustwo == 1) {
//memo[ind][usedremove][dominustwo][isstart]--;
}
return memo2[ind][usedremove][dominustwo][isstart] ;
}
public void realMain() throws Exception {
BufferedReader fin = new BufferedReader(new InputStreamReader(System.in), 1000000);
String in = fin.readLine();
String[] ar = in.split(" ");
n = Integer.parseInt(ar[0]);
a = new int[n];
for(int i = 0; i < n; i++) {
int ret = 0;
boolean dig = false;
for (int ch = 0; (ch = fin.read()) != -1; ) {
if (ch >= '0' && ch <= '9') {
dig = true;
ret = ret * 10 + ch - '0';
} else if (dig) break;
}
a[i] = ret;
}
memo = new int[n][2][2][2];
memo2 = new int[n][2][2][2];
for(int i = 0; i < n; i++) {
memo[i][0][0][0] = -1;
memo[i][0][0][1] = -1;
memo[i][0][1][0] = -1;
memo[i][0][1][1] = -1;
memo[i][1][0][0] = -1;
memo[i][1][0][1] = -1;
memo[i][1][1][0] = -1;
memo[i][1][1][1] = -1;
memo2[i][0][0][0] = -1;
memo2[i][0][0][1] = -1;
memo2[i][0][1][0] = -1;
memo2[i][0][1][1] = -1;
memo2[i][1][0][0] = -1;
memo2[i][1][0][1] = -1;
memo2[i][1][1][0] = -1;
memo2[i][1][1][1] = -1;
}
int max = 0;
for(int i = 0; i < n; i++) {
max = Math.max(max, dp(i, 0, 0, 1));
//System.out.println("memo: " + memo[i][0][0][1]);
}
for(int i = 0; i < n; i++) {
max = Math.max(max, dp2(i, 0, 0, 1));
//System.out.println("memo2: " + memo2[i][0][0][1]);
}
System.out.println(max);
}
public static void main(String[] args) throws Exception {
p1272D a = new p1272D();
a.realMain();
}
} | Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | b6b7500d5815d5445c847d4273ec2bbf | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | // package app;
import java.util.Scanner;
public class App3 {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
int arrayLength = scanner.nextInt();
scanner.nextLine();
int[] list = new int[arrayLength];
for (int i = 0; i < arrayLength; i++) {
list[i] = scanner.nextInt();
}
System.out.println(getMaxSubStrLength(list, arrayLength));
scanner.close();
}
private static int getMaxSubStrLength(int[] list, int arrayLength) {
int maxLength = 0, length = 0;
boolean isOneElementRemoved = false;
int prevNo = list[0];
int currentNo = prevNo;
for (int i = 1; i < arrayLength; i++) {
currentNo = list[i];
if (currentNo > prevNo) {
length++;
prevNo = currentNo;
} else {
if (!isOneElementRemoved && (i >= 2) && (list[i - 2] < currentNo)) {
if (length > 0) {
isOneElementRemoved = true;
prevNo = currentNo;
continue;
}
} else if (!isOneElementRemoved && (i < arrayLength - 1) && list[i - 1] < list[i + 1]) {
if (length > 0) {
isOneElementRemoved = true;
continue;
}
} else {
if (length > maxLength) {
maxLength = length;
}
length = 0;
isOneElementRemoved = false;
prevNo = currentNo;
}
}
}
if (length > maxLength) {
maxLength = length;
}
if (maxLength > 0) {
maxLength++;
}
if (maxLength == 0) {
return 1;
}
return maxLength;
}
} | Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | d3b52cbbd9d710519620c5f708896b2e | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main
{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args)
{
FastReader sc=new FastReader();
int n=sc.nextInt();
int arr[]=new int[n];
int inc[]=new int[n];
int dec[]=new int[n];
for(int i=0;i<n;i++)
arr[i]=sc.nextInt();
int max=1;
inc[0]=1;
int count=1;
for(int i=1;i<n;i++)
{
if(arr[i]>arr[i-1])
{
count++;
inc[i]=count;
if(max<count)
max=count;
}
else
{
count=1;
inc[i]=count;
}
}
dec[n-1]=1;
count=1;
for(int i=n-2;i>-1;i--)
{
if(arr[i]<arr[i+1])
{
count++;
dec[i]=count;
}
else
{
count=1;
dec[i]=count;
}
}
for(int i=2;i<n-1;i++)
{
if(arr[i-1]<arr[i+1])
{
max=Math.max(max,inc[i-1]+dec[i+1]);
}
}
/*for(int x:inc)
System.out.print(x+" ");*/
System.out.println(max);
/*for(int x:dec)
System.out.print(x+" ");*/
}
} | Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | 3b6166fc316d64999a1c26c8c2349b98 | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class aaaaaaaaaaaaaaaa {
public void run() throws Exception {
FastReader file = new FastReader();
int times = file.nextInt();
ArrayList<Integer> x = new ArrayList();
for (int i = 0; i < times; i++) {
x.add(file.nextInt());
}
int[] prefix = new int[times], suffix = new int[times];
prefix[0] = 1;
for (int i = 1; i < times; i++) {
if (x.get(i) > x.get(i - 1)) {
prefix[i] = prefix[i - 1] + 1;
} else
prefix[i] = 1;
}
suffix[times - 1] = 1;
for (int i = times - 2; i >= 0; i--) {
if (x.get(i) < x.get(i + 1)) {
suffix[i] = suffix[i + 1] + 1;
} else
suffix[i] = 1;
}
// System.out.println(Arrays.toString(prefix));
// System.out.println(Arrays.toString(suffix));
int max = Math.max(suffix[0], prefix[prefix.length - 1]);
for (int i = 0; i < times; i++) max = Math.max(max, prefix[i]);
for (int i= 0; i < times; i++) max = Math.max(max, suffix[i]);
for (int i = 1; i < times - 1; i++) {
if (x.get(i - 1) < x.get(i + 1))
max = Math.max(max, prefix[i - 1] + suffix[i + 1]);
}
System.out.println(max);
}
public static void main(String[] args) throws Exception {
new aaaaaaaaaaaaaaaa().run();
}
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;
}
}
}
| Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | a5d9d8f1bbd35735953fe815756b3c4e | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
// written by luchy0120
public class Main {
public static void main(String[] args) throws Exception {
new Main().run();
}
// int get_room(int i,int j){
// return i/3*3 + j/3;
// }
// int a[][] = new int[9][9];
// int space = 0;
//
// boolean vis_row[][] = new boolean[9][10];
// boolean vis_col[][] = new boolean[9][10];
// boolean vis_room[][] = new boolean[9][10];
// int val[][][] =new int[9][9][];
// int prepare[][];
//
// void dfs(int rt){
//
// }
void solve(){
int n = ni();
int a[] = na(n);
int d[] = new int[n];
int d1[] = new int[n];
int ma = 0;
d[0] = 1;
d1[n-1] = 1;
for(int i=1;i<n;++i){
if(a[i]>a[i-1]){
d[i] = d[i-1]+1;
}else{
d[i] = 1;
}
if(a[n-i]>a[n-i-1]){
d1[n-i-1] = d1[n-i]+1;
}else{
d1[n-i-1] = 1;
}
}
for(int i=0;i<n;++i){
ma = Math.max(ma,d[i]);
ma = Math.max(ma,d1[i]);
if(i>=1&&i+1<n&&a[i-1]<a[i+1]){
ma = Math.max(ma,d[i-1]+d1[i+1]);
}
}
println(ma);
}
public static String roundS(double result, int scale){
String fmt = String.format("%%.%df", scale);
return String.format(fmt, result);
}
// void solve() {
//
// for(int i=0;i<9;++i) {
// for (int j = 0; j < 9; ++j) {
// int v = ni();
// a[i][j] = v;
// if(v>0) {
// vis_row[i][v] = true;
// vis_col[j][v] = true;
// vis_room[get_room(i, j)][v] = true;
// }else{
// space++;
// }
// }
// }
//
//
// prepare = new int[space][2];
//
// int p = 0;
//
// for(int i=0;i<9;++i) {
// for (int j = 0; j < 9; ++j) {
// if(a[i][j]==0){
// prepare[p][0] = i;
// prepare[p][1]= j;p++;
// List<Integer> temp =new ArrayList<>();
// for(int k=1;k<=9;++k){
// if(!vis_col[j][k]&&!vis_row[i][k]&&!vis_room[get_room(i,j)][k]){
// temp.add(k);
// }
// }
// int sz = temp.size();
// val[i][j] = new int[sz];
// for(int k=0;k<sz;++k){
// val[i][j][k] = temp.get(k);
// }
// }
// }
// }
// Arrays.sort(prepare,(x,y)->{
// return Integer.compare(val[x[0]][x[1]].length,val[y[0]][y[1]].length);
// });
// dfs(0);
//
//
//
//
//
//
//
//
//
//
// }
InputStream is;
PrintWriter out;
void run() throws Exception {
is = System.in;
out = new PrintWriter(System.out);
solve();
out.flush();
}
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 char ncc() {
int b = readByte();
return (char) b;
}
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 String nline() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b) || b == ' ') {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[][] nm(int n, int m) {
char[][] a = new char[n][];
for (int i = 0; i < n; i++) a[i] = ns(m);
return a;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
private long[] nal(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nl();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) {
}
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') num = (num << 3) + (num << 1) + (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();
}
}
void print(Object obj) {
out.print(obj);
}
void println(Object obj) {
out.println(obj);
}
void println() {
out.println();
}
void printArray(int a[],int from){
int l = a.length;
for(int i=from;i<l;++i){
print(a[i]);
if(i!=l-1){
print(" ");
}
}
println();
}
void printArray(long a[],int from){
int l = a.length;
for(int i=from;i<l;++i){
print(a[i]);
if(i!=l-1){
print(" ");
}
}
println();
}
} | Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | ed50f3ed273510dc31eacc873a7a1dd9 | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes |
import java.util.*;
import java.io.*;
import java.text.*;
public class D1272 {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
}
int[] endat = new int[n];
int[] startat = new int[n];
endat[0] = 1;
int ans = 1;
for (int i = 1; i < startat.length; i++) {
if (arr[i] > arr[i - 1]) {
endat[i] = endat[i - 1] + 1;
} else
endat[i] = 1;
ans = Math.max(ans, endat[i]);
}
startat[arr.length - 1] = 1;
for (int i = arr.length - 2; i >= 0; i--) {
if (arr[i] < arr[i + 1]) {
startat[i] = startat[i + 1] + 1;
} else
startat[i] = 1;
ans = Math.max(ans, startat[i]);
}
for (int i = 1; i < n - 1; i++) {
if (arr[i - 1] < arr[i + 1]) {
ans = Math.max(ans, endat[i - 1] + startat[i + 1]);
}
}
pw.println(ans);
pw.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
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 {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
| Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | 0813cc0ef92244e695be0d803a144245 | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes |
import java.io.*;
import java.math.*;
import java.util.*;
/*
*
10
1 2 3 10 10 4 5 10 6 7
correct: 4
7
5 4 6 7 6 8 9
correct: 5
7
5 4 6 5 7 6 8
correct: 3
11
5 4 6 5 7 6 8 7 9 8 10
correct: 3
*/
public class removeoneelement {
public static void main(String[] args) throws IOException {
FastScanner scan = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = scan.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scan.nextInt();
}
long ans = 1;
int[] streak = new int[n];
Arrays.fill(streak, 1);
boolean[] merge = new boolean[n];
for (int i = 0; i < n; i++) {
if (i == 0)
continue;
if (arr[i] > arr[i-1]) {
streak[i] = streak[i-1] + 1;
ans = Math.max(streak[i], ans);
}
if (i > 0 && i < n-1 && (arr[i] <= arr[i-1] || arr[i] >= arr[i+1]) && arr[i-1] < arr[i+1]) {
merge[i] = true;
//System.out.println(i);
}
}
int index = 0;
int pIndex = 0;
for (int i = 0; i < n; i++) {
if (merge[i]) {
int s = 1;
for (int j = pIndex+1; j < n; j++) {
//System.out.println(i + " " + j + " " + s);
if (j == i) {
continue;
}
if (j-1 == i || arr[j] > arr[j-1]) {
s++;
ans = Math.max(ans, s);
}
else {
s = 1;
}
if (j > i && merge[j])
break;
}
pIndex = index;
index = i;
}
}
//System.out.println(streak);
//ans = Math.max(ans, 0);
out.println(ans);
out.close();
}
public static void shuffle(int[] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int rPos = rgen.nextInt(arr.length);
int temp = arr[i];
arr[i] = arr[rPos];
arr[rPos]=temp;
}
}
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();
}
String nextLine() {
st = null;
try {
return br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
} | Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | ef38425a852acdca3c3b71fa49429a46 | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class RemoveOneElement {
public static void main(String[] args) {
InputReader r = new InputReader(System.in);
int n = r.nextInt();
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++) {
arr[i] = r.nextInt();
}
boolean can = true;
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] >= arr[i + 1])
can = false;
}
if (can) {
System.out.println(n);
return;
}
int res = 0;
int left = 0;
int[] rightArr = new int[arr.length];
for (int i = arr.length - 1; i >= 0; i--) {
if (i + 1 < arr.length && arr[i] < arr[i + 1])
rightArr[i] = rightArr[i + 1] + 1;
else
rightArr[i] = 1;
}
for (int i = 0; i < arr.length; i++) {
int leftNumber = 0;
if (i - 1 >= 0) {
leftNumber = arr[i - 1];
}
int right = i + 1 < arr.length ? rightArr[i + 1] : 0;
int rightNumber = (int) ((1e9) + 10);
if (i + 1 < arr.length) {
rightNumber = arr[i + 1];
}
res = Math.max(res, left);
res = Math.max(res, right);
if (leftNumber < rightNumber) {
res = Math.max(res, left + right);
}
if (leftNumber < arr[i])
left++;
else
left = 1;
}
System.out.println(res);
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public InputReader(FileReader stream) {
reader = new BufferedReader(stream);
tokenizer = null;
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
| Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | 59314ac94d4b9ca1db5cfccc0a63ae25 | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.util.*;
public final class Today {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a[]=new int[n],temp=0;
for(int i=0;i<n;i++) {
a[i]=sc.nextInt();
}
int incf[]=new int[n],max=1;
incf[0]=1;
for(int i=1;i<n;i++) {
if(a[i]>a[i-1])
incf[i]=incf[i-1]+1;
else
incf[i]=1;
if(incf[i]>max) max=incf[i];
}
// System.out.println(Arrays.toString(incf));
int incb[]=new int[n];
incb[n-1]=1;
for(int i=n-2;i>=0;i--) {
if(a[i]<a[i+1])
incb[i]=incb[i+1]+1;
else
incb[i]=1;
}
// System.out.println(Arrays.toString(incb));
for(int i=1;i<n-1;i++) {
if(a[i+1]>a[i-1]) {
temp=incf[i-1]+incb[i+1];
if(temp>max)
max=temp;
}
}
System.out.println(max);
}
} | Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | bc5574e277cfe3d7461bb7054f949687 | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
int n = Integer.parseInt(br.readLine());
int[] a = new int[n];
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < a.length; i++) {
a[i]= Integer.parseInt(st.nextToken());
}
ArrayList<Integer> arr = new ArrayList<Integer>();
TreeSet<Integer> breakpnts = new TreeSet<Integer>();
int count=0;
for (int i = 0; i < a.length; i++) {
if(0<i && a[i]<=a[i-1])
{
arr.add(count);
count=0;
breakpnts.add(i-1);
}
count++;
if(i==a.length-1)
{
arr.add(count);
count=0;
}
}
//System.out.println(arr);
int[] length = new int[n];
int indx=0;
int max=0;
for (int i = 0; i < length.length; i++) {
int num=arr.get(indx++);
max=Math.max(max, num);
for (int j = i; j <i+num ; j++) {
length[j]=num;
}
i+=num-1;
}
//System.out.println(Arrays.toString(length));
for (int i = 0; i < length.length; i++) {
//System.out.println("i: " + i);
if(breakpnts.contains(i))
{
if(i-1>-1 && a[i-1]<a[i+1])
{
if(length[i]==1)
{
max=Math.max(length[i-1]+length[i+1], max);
}
else
{
max=Math.max(length[i]+length[i+1]-1, max);
}
}
if(i+2<a.length && a[i]<a[i+2])
{
if(length[i+1]==1)
{
max=Math.max(length[i]+length[i+2], max);
}
else
{
max=Math.max(length[i]+length[i+2]-1, max);
}
}
}
//System.out.println(max);
}
pw.println(max);
pw.close();
}
} | Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | 5f9dea8f5c378dbaf5ed990fe6242cd7 | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | // Don't place your source in a package
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
// Please name your class Main
public class Main {
static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static int read() throws IOException {
in.nextToken();
return (int) in.nval;
}
static String readString() throws IOException {
in.nextToken();
return in.sval;
}
public static void main (String[] args) throws java.lang.Exception {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
//InputReader in = new InputReader(System.in);
int T=1;
for(int t=0;t<T;t++){
int n=in.nextInt();
int A[]=new int[n];
for(int i=0;i<n;i++){
A[i]=in.nextInt();
}
Solution sol=new Solution();
sol.solution(A);
}
out.flush();
}
}
class Solution{
//constant variable
final int MAX=Integer.MAX_VALUE;
final int MIN=Integer.MIN_VALUE;
//Set<Integer>adjecent[];
//////////////////////////////
public void solution(int A[]){
int cnt=1;
int dp[]=new int[A.length];
int res=1;
Arrays.fill(dp,1);
for(int i=1;i<A.length;i++){//not delete
if(A[i]>A[i-1]){
cnt++;
dp[i]=cnt;
res=Math.max(res,cnt);
}else{
cnt=1;
}
}
int back[]=new int[A.length];
Arrays.fill(back,1);
cnt=1;
for(int i=A.length-2;i>=0;i--){//not delete
if(A[i]<A[i+1]){
cnt++;
back[i]=cnt;
res=Math.max(res,cnt);
}else{
cnt=1;
}
}
for(int i=1;i<A.length-1;i++){
if(A[i+1]>A[i-1]){
res=Math.max(res,dp[i-1]+back[i+1]);
}
}
msg(res+"");
}
public void swap(int A[],int l,int r){
int t=A[l];
A[l]=A[r];
A[r]=t;
}
public long C(long fact[],int i,int j){ // C(20,3)=20!/(17!*3!)
// take a/b where a=20! b=17!*3!
if(j>i)return 0;
if(j==0)return 1;
long mod=998244353;
long a=fact[i];
long b=((fact[i-j]%mod)*(fact[j]%mod))%mod;
BigInteger B= BigInteger.valueOf(b);
long binverse=B.modInverse(BigInteger.valueOf(mod)).longValue();
return ((a)*(binverse%mod))%mod;
}
//map operation
public void put(Map<Integer,Integer>map,int i){
if(!map.containsKey(i))map.put(i,0);
map.put(i,map.get(i)+1);
}
public void delete(Map<Integer,Integer>map,int i){
map.put(i,map.get(i)-1);
if(map.get(i)==0)map.remove(i);
}
/*public void tarjan(int p,int r){
if(cut)return;
List<Integer>childs=adjecent[r];
dis[r]=low[r]=time;
time++;
//core for tarjan
int son=0;
for(int c:childs){
if(ban==c||c==p)continue;
if(dis[c]==-1){
son++;
tarjan(r,c);
low[r]=Math.min(low[r],low[c]);
if((r==root&&son>1)||(low[c]>=dis[r]&&r!=root)){
cut=true;
return;
}
}else{
if(c!=p){
low[r]=Math.min(low[r],dis[c]);
}
}
}
}*/
//helper function I would use
public void remove(Map<Integer,Integer>map,int i){
map.put(i,map.get(i)-1);
if(map.get(i)==0)map.remove(i);
}
public void ascii(String s){
for(char c:s.toCharArray()){
System.out.print((c-'a')+" ");
}
msg("");
}
public int flip(int i){
if(i==0)return 1;
else return 0;
}
public boolean[] primes(int n){
boolean A[]=new boolean[n+1];
for(int i=2;i<=n;i++){
if(A[i]==false){
for(int j=i+i;j<=n;j+=i){
A[j]=true;
}
}
}
return A;
}
public void msg(String s){
System.out.println(s);
}
public void msg1(String s){
System.out.print(s);
}
public int[] kmpPre(String p){
int pre[]=new int[p.length()];
int l=0,r=1;
while(r<p.length()){
if(p.charAt(l)==p.charAt(r)){
pre[r]=l+1;
l++;r++;
}else{
if(l==0)r++;
else l=pre[l-1];
}
}
return pre;
}
public boolean isP(String s){
int l=0,r=s.length()-1;
while(l<r){
if(s.charAt(l)!=s.charAt(r))return false;
l++;r--;
}
return true;
}
public int find(int nums[],int x){//union find => find method
if(nums[x]==x)return x;
int root=find(nums,nums[x]);
nums[x]=root;
return root;
}
public int get(int A[],int i){
if(i<0||i>=A.length)return 0;
return A[i];
}
public int[] copy1(int A[]){
int a[]=new int[A.length];
for(int i=0;i<a.length;i++)a[i]=A[i];
return a;
}
public int[] copy2(int A[]){
int a[]=new int[A.length];
for(int i=0;i<a.length;i++)a[i]=A[i];
return a;
}
public void print1(int A[]){
for(long i:A)System.out.print(i+" ");
System.out.println();
}
public void print2(long A[][]){
for(int i=0;i<A.length;i++){
for(int j=0;j<A[0].length;j++){
System.out.print(A[i][j]+" ");
}System.out.println();
}
}
public int min(int a,int b){
return Math.min(a,b);
}
public int[][] matrixdp(int[][] grid) {
if(grid.length==0)return new int[][]{};
int res[][]=new int[grid.length][grid[0].length];
for(int i=0;i<grid.length;i++){
for(int j=0;j<grid[0].length;j++){
res[i][j]=grid[i][j]+get(res,i-1,j)+get(res,i,j-1)-get(res,i-1,j-1);
}
}
return res;
}
public int get(int grid[][],int i,int j){
if(i<0||j<0||i>=grid.length||j>=grid[0].length)return 0;
return grid[i][j];
}
public int[] suffixArray(String s){
int n=s.length();
Suffix A[]=new Suffix[n];
for(int i=0;i<n;i++){
A[i]=new Suffix(i,s.charAt(i)-'a',0);
}
for(int i=0;i<n;i++){
if(i==n-1){
A[i].next=-1;
}else{
A[i].next=A[i+1].rank;
}
}
Arrays.sort(A);
for(int len=4;len<A.length*2;len<<=1){
int in[]=new int[A.length];
int rank=0;
int pre=A[0].rank;
A[0].rank=rank;
in[A[0].index]=0;
for(int i=1;i<A.length;i++){//rank for the first two letter
if(A[i].rank==pre&&A[i].next==A[i-1].next){
pre=A[i].rank;
A[i].rank=rank;
}else{
pre=A[i].rank;
A[i].rank=++rank;
}
in[A[i].index]=i;
}
for(int i=0;i<A.length;i++){
int next=A[i].index+len/2;
if(next>=A.length){
A[i].next=-1;
}else{
A[i].next=A[in[next]].rank;
}
}
Arrays.sort(A);
}
int su[]=new int[A.length];
for(int i=0;i<su.length;i++){
su[i]=A[i].index;
}
return su;
}
}
//suffix array Struct
class Suffix implements Comparable<Suffix>{
int index;
int rank;
int next;
public Suffix(int i,int rank,int next){
this.index=i;
this.rank=rank;
this.next=next;
}
@Override
public int compareTo(Suffix other) {
if(this.rank==other.rank){
return this.next-other.next;
}
return this.rank-other.rank;
}
public String toString(){
return this.index+" "+this.rank+" "+this.next+" ";
}
}
class Wrapper implements Comparable<Wrapper>{
int spf;int cnt;
public Wrapper(int spf,int cnt){
this.spf=spf;
this.cnt=cnt;
}
@Override
public int compareTo(Wrapper other) {
return this.spf-other.spf;
}
}
class Node{//what the range would be for that particular node
boolean state=false;
int l=0,r=0;
int ll=0,rr=0;
public Node(boolean state){
this.state=state;
}
}
class Seg1{
int A[];
public Seg1(int A[]){
this.A=A;
}
public void update(int left,int right,int val,int s,int e,int id){
if(left<0||right<0||left>right)return;
if(left==s&&right==e){
A[id]+=val;
return;
}
int mid=s+(e-s)/2; //[s,mid] [mid+1,e]
if(left>=mid+1){
update(left,right,val,mid+1,e,id*2+2);
}else if(right<=mid){
update(left,right,val,s,mid,id*2+1);
}else{
update(left,mid,val,s,mid,id*2+1);
update(mid+1,right,val,mid+1,e,id*2+2);
}
}
public int query(int i,int add,int s,int e,int id){
if(s==e&&i==s){
return A[id]+add;
}
int mid=s+(e-s)/2; //[s,mid] [mid+1,e]
if(i>=mid+1){
return query(i,A[id]+add,mid+1,e,id*2+2);
}else{
return query(i,A[id]+add,s,mid,id*2+1);
}
}
}
class MaxFlow{
public static List<Edge>[] createGraph(int nodes) {
List<Edge>[] graph = new List[nodes];
for (int i = 0; i < nodes; i++)
graph[i] = new ArrayList<>();
return graph;
}
public static void addEdge(List<Edge>[] graph, int s, int t, int cap) {
graph[s].add(new Edge(t, graph[t].size(), cap));
graph[t].add(new Edge(s, graph[s].size() - 1, 0));
}
static boolean dinicBfs(List<Edge>[] graph, int src, int dest, int[] dist) {
Arrays.fill(dist, -1);
dist[src] = 0;
int[] Q = new int[graph.length];
int sizeQ = 0;
Q[sizeQ++] = src;
for (int i = 0; i < sizeQ; i++) {
int u = Q[i];
for (Edge e : graph[u]) {
if (dist[e.t] < 0 && e.f < e.cap) {
dist[e.t] = dist[u] + 1;
Q[sizeQ++] = e.t;
}
}
}
return dist[dest] >= 0;
}
static int dinicDfs(List<Edge>[] graph, int[] ptr, int[] dist, int dest, int u, int f) {
if (u == dest)
return f;
for (; ptr[u] < graph[u].size(); ++ptr[u]) {
Edge e = graph[u].get(ptr[u]);
if (dist[e.t] == dist[u] + 1 && e.f < e.cap) {
int df = dinicDfs(graph, ptr, dist, dest, e.t, Math.min(f, e.cap - e.f));
if (df > 0) {
e.f += df;
graph[e.t].get(e.rev).f -= df;
return df;
}
}
}
return 0;
}
public static int maxFlow(List<Edge>[] graph, int src, int dest) {
int flow = 0;
int[] dist = new int[graph.length];
while (dinicBfs(graph, src, dest, dist)) {
int[] ptr = new int[graph.length];
while (true) {
int df = dinicDfs(graph, ptr, dist, dest, src, Integer.MAX_VALUE);
if (df == 0)
break;
flow += df;
}
}
return flow;
}
}
class Edge {
int t, rev, cap, f;
public Edge(int t, int rev, int cap) {
this.t = t;
this.rev = rev;
this.cap = cap;
}
}
| Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | 75e43cd286918e22bd1b33859191066c | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.util.Scanner;
// https://codeforces.com/problemset/problem/1272/D
public class RemoveOneElement {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int dp[] = new int[n];
dp[0] = 1;
int ans = 1, prev = 0;
for (int i = 1; i < n; i++) {
if (arr[i] > arr[i - 1]) {
dp[i] = dp[i-1] + 1;
}
else {
ans = Math.max(ans, i - prev);
dp[i] = 1;
prev = i;
}
}
if (dp[n-1] != 1) {
ans = Math.max(ans, dp[n-1]);
}
// for (int i = 0; i < n; i++) {
// System.out.print(dp[i]+ " ");
// }
int dp1[] = new int[n];
dp1[n-1] = 1;
for (int i = n - 2; i >= 0; i--) {
if (arr[i] < arr[i + 1]) {
dp1[i] = dp1[i+1] + 1;
}
else {
dp1[i] = 1;
}
}
for (int i = 1; i < n - 1; i++) {
if (arr[i-1] < arr[i+1])
ans = Math.max(ans, dp[i-1] + dp1[i + 1]);
}
System.out.println(ans);
}
}
| Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | 98f0e053566d999b557329c8174709b6 | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | // template halnix16
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
static BufferedReader br;
public static void main(String[] args) throws Exception {
// write your code here
br = new BufferedReader(new InputStreamReader(System.in));
long n = in();
long arr[] = arr(n);
long dp[][] = new long[(int)n][2];
dp[0][0]=1;
for(int k=1;k<n;k++){
if(arr[k]>arr[k-1]){
dp[k][0]= dp[k-1][0]+1;
}else{
dp[k][0] = 1;
}
}
dp[(int)n-1][1] = 1;
for(int k =(int)n-2;k>1;k--){
if(arr[k]>arr[k+1]){
dp[k][1] =1 ;
}else
dp[k][1]= dp[k+1][1]+1;
}
long ans=0;
for(int i =0;i<n;i++){
ans = Math.max(ans,dp[i][0]);
if(i>=n-2)
continue;
if(arr[i+2]>arr[i]) {
ans = Math.max(ans, dp[i][0] + dp[i + 2][1]);
}
}
System.out.println(ans);
}
static long[] arr(long n) throws Exception {
String read[] = sarrin();
long arr[] = new long[(int) n];
for (int k = 0; k < n; k++)
arr[k] = in(read[k]);
return arr;
}
static long[][] arr(long n, long m) throws Exception {
long arr[][] = new long[(int) n][(int) m];
for (int k = 0; k < n; k++) {
String read[] = sarrin();
for (int j = 0; j < m; j++)
arr[k][j] = in(read[k]);
}
return arr;
}
static long in() throws Exception {
return Long.parseLong(br.readLine());
}
static long in(String num) throws Exception {
return Long.parseLong(num);
}
static String sin() throws Exception {
return br.readLine();
}
static String[] sarrin() throws Exception {
return br.readLine().split(" ");
}
static String[] regexSplit() throws Exception {
return br.readLine().split(" ?(?<!\\G)((?<=[^\\p{Punct}])(?=\\p{Punct})|\\b) ?");
}
}
| Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | 589100ef46e5dc323a8953ece214e259 | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | //package cf;
import java.io.*;
import java.util.*;
import java.lang.*;
import java.math.*;
public class USACO {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter (System.out);
//BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
//StringTokenizer st = new StringTokenizer(reader.readLine()," ");
int n = Integer.parseInt(reader.readLine());
StringTokenizer st = new StringTokenizer(reader.readLine()," ");
// HEIGHT: must be taller than this, DIST: how far
int answer=0;
int zeroHeight=0; // ZERO: cut at zero
int zeroDist=0;
int onePlusHeight=0;
int onePlusDist=0;
int cutlessHeight=0;
int cutlessDist=0;
for (int i=0;i<n;i++) {
int x = Integer.parseInt(st.nextToken());
if (n>0&&x>zeroHeight&&(zeroDist>=onePlusDist||(x<=onePlusHeight||n<2))) {
onePlusHeight=x;
onePlusDist=zeroDist+1;
} else if (n>1&&x>onePlusHeight) { //onePlusHeight is valid at n=2
onePlusHeight=x;
onePlusDist=onePlusDist+1;
} else if (n>0) {
onePlusHeight=x;
onePlusDist=1;
}
zeroHeight=cutlessHeight;
zeroDist=cutlessDist;
if (x>cutlessHeight) {
cutlessHeight=x;
cutlessDist++;
} else {
cutlessHeight=x;
cutlessDist=1;
}
answer=Math.max(answer, Math.max(cutlessDist, Math.max(zeroDist,onePlusDist)));
}
out.println(answer);
reader.close();
out.close();
}
} | Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | af5d293595f5c408437054310f69d240 | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution
{
public static void main(String ag[])
{
Scanner sc=new Scanner(System.in);
int i,j,k;
int N=sc.nextInt();
int A[]=new int[N];
for(i=0;i<N;i++)
A[i]=sc.nextInt();
int ans=0;
int preInc[]=new int[N];
int suffDec[]=new int[N];
Arrays.fill(preInc,1);
for(i=1;i<N;i++)
{
if(A[i]>A[i-1])
preInc[i]=preInc[i-1]+1;
ans=Math.max(ans,preInc[i]);
}
Arrays.fill(suffDec,1);
for(i=N-2;i>=0;i--)
{
if(A[i]<A[i+1])
suffDec[i]=suffDec[i+1]+1;
ans=Math.max(ans,suffDec[i]);
}
for(i=1;i<N-1;i++)
{
if(A[i-1]<A[i+1])
ans=Math.max(ans,preInc[i-1]+suffDec[i+1]);
}
System.out.println(ans);
}
} | Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | aecca88754a56fdfd182858436d92798 | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.io.*;
import java.util.*;
/**
* Only By Abhi_Valani
*/
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);
Unstoppable solver = new Unstoppable();
// int t=in.nextInt();
// while(t-->0)
solver.solve(in, out);
out.close();
}
static class Unstoppable {
public void solve(InputReader in, PrintWriter out) {
int n=in.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=in.nextInt();
}
int count=1;
ArrayList<Integer> array=new ArrayList<>();
for (int i=1;i<n;i++) {
if(a[i]>a[i-1]) { count++; continue; }
array.add(count);
count=1;
}
array.add(count);
int c=0;
for(int i=1;i<n;i++)
{
if(a[i]>a[i-1]) continue;
if((i-2>=0&&a[i]>a[i-2])||(i+1<n&&a[i+1]>a[i-1])) array.add(array.get(c)+array.get(++c)-1);
else ++c;
}
int size=array.size();
int max=array.get(0);
for(int i=1;i<size;i++)
{
if(array.get(i)>max) max=array.get(i);
}
out.println(max);
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong(){
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | 7b2a7ef3d19617d5221ce2999ac9e757 | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | /**
* Alipay.com Inc. Copyright (c) 2004-2020 All Rights Reserved.
*/
import java.util.Arrays;
import java.util.Scanner;
/**
* Codeforces Round #605 (Div. 3)
* 1272/D
*
* D. Remove One Element
*
* Examples
* inputCopy
* 5
* 1 2 5 3 4
* outputCopy
* 4
* inputCopy
* 2
* 1 2
* outputCopy
* 2
* inputCopy
* 7
* 6 5 4 3 2 4 3
* outputCopy
* 2
*
* @author linwanying
*/
public class RemoveOneElement {
public static void main(String[] args) {
new RemoveOneElement().run();
}
private void run() {
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
int[] arr = new int[number];
for (int i = 0; i < number; ++i) {
int cur = scanner.nextInt();
arr[i] = cur;
}
int result = 1;
int[] l = new int[number];
int[] r = new int[number];
Arrays.fill(l, 1);
Arrays.fill(r, 1);
for (int i = 1; i < number; ++i) {
if (arr[i] > arr[i-1]) r[i] = r[i-1] + 1;
result = Math.max(result, r[i]);
}
for (int i = number-2; i >= 0; --i) {
if (arr[i] < arr[i+1]) l[i] = l[i+1] + 1;
result = Math.max(result, l[i]);
}
for (int i = 1; i < number-1; ++i) {
if (arr[i-1] < arr[i+1]) result = Math.max(result, l[i+1] + r[i-1]);
}
System.out.println(result);
}
} | Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | f741f6b6f1c84651e55b5c2418037415 | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Stack;
import java.util.StringTokenizer;
public class TaskD {
public static void main(String[] arg) {
final FastScanner in = new FastScanner(System.in);
final PrintWriter out = new PrintWriter(System.out);
final int n = in.nextInt();
final int[] a = in.readIntArr(n);
Solution sol = new Solution(n, a);
out.printf("%d%n", sol.sol_1());
out.close();
in.close();
}
private static class Solution {
final int n;
final int[] a;
public Solution(int n, int[] a) {
this.n = n;
this.a = a;
}
public long sol() {
long result = 1;
int[] dp = new int[2];
dp[0] = 1;
dp[1] = 1;
for (int i = 1; i < n; i++) {
if (a[i - 1] < a[i]) {
dp[0]++;
dp[1]++;
} else {
if (i >= 2 && a[i - 2] < a[i]) {
dp[1] = dp[0];
dp[0] = 1;
} else {
dp[1] = 1;
dp[0] = 1;
}
}
result = Math.max(result, Math.max(dp[1], dp[0]));
}
return result;
}
public long sol_1() {
int[] al = new int[n];
Arrays.fill(al, 1);
int result = 1;
for (int i = n - 2; i >= 0; i--) {
if (a[i] < a[i + 1]) {
al[i] = al[i + 1] + 1;
result = Math.max(al[i], result);
}
}
// System.out.println(Arrays.toString(al));
int[] ar = new int[n];
Arrays.fill(ar, 1);
for (int i = 1; i < n; i++) {
if (a[i] > a[i - 1]) {
ar[i] = ar[i - 1] + 1;
}
}
// System.out.println(Arrays.toString(ar));
for (int i = 1; i < n - 1; i++) {
if (a[i + 1] > a[i - 1]) {
result = Math.max(result, al[i+1] + ar[i-1]);
}
}
return result;
}
}
private static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream stream) {
try {
br = new BufferedReader(new InputStreamReader(stream));
} catch (Exception e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readIntArr(int n) {
int[] result = new int[n];
for (int i = 0; i < n; i++) {
result[i] = Integer.parseInt(next());
}
return result;
}
void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | 21bafd990217e9064b02923768f8ec17 | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.util.*;
public class wha {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int arr[] = new int[n];
for(int i=0;i<n;i++) {
arr[i] = input.nextInt();
}
System.out.println(sol(arr,arr.length));
}
static int sol(int arr[],int n) {
int l[] = new int[n];
int r[] = new int[n];
for(int i=0;i<n;i++) {
l[i] = r[i] = 1;
}
for(int i=1;i<n;i++) {
if(arr[i]>arr[i-1]) {
l[i] = l[i-1]+1;
}
}
int max = 1;
for(int i=n-2;i>=0;i--) {
if(arr[i+1]>arr[i]) {
r[i] = r[i+1]+1;
max = Math.max(max, r[i]);
}
}
for(int i=1;i<n-1;i++) {
if(arr[i+1]>arr[i-1]) {
max = Math.max(max,l[i-1]+r[i+1]);
}
}
return max;
}
}
| Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | 9d392252deafb81332088edca6216bd1 | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main{
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
// String[] cmd=br.readLine().split(" ");
int cases=1;
while(cases!=0)
{
cases--;
int n=Integer.valueOf(br.readLine());
int[] arr=new int[n];
String[] cmd=br.readLine().split(" ");
for(int i=0;i<n;i++)
{
arr[i]=Integer.valueOf(cmd[i]);
}
int[] nor=new int[n];
int[] fin=new int[n];
Arrays.fill(nor,1);
Arrays.fill(fin,1);
for(int i=1;i<n;i++)
{
if(arr[i]>arr[i-1])
{
nor[i]=nor[i-1]+1;
fin[i]=Math.max(fin[i],fin[i-1]+1);
}
if(i-2>=0 && arr[i]>arr[i-2])
fin[i]=Math.max(fin[i],nor[i-2]+1);
// fin[i]=Math.max(fin[i],nor[i]);
}
int ans=0;
// System.out.println(Arrays.toString(fin));
for(int i=0;i<n;i++)
{
ans=Math.max(ans,fin[i]);
}
System.out.println(ans);
}
}
}
| Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | 3f50827a5183f2735c2abc59b5de379c | train_003.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes |
// Working program with FastReader
import java.io.*;
import java.util.*;
public class C {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static List<Integer> list = new ArrayList<Integer>();
public static void main(String[] args) {
FastReader s = new FastReader();
int n = s.nextInt();
for (int i = 0; i < n; i++) {
int val = s.nextInt();
list.add(val);
}
int result = solve(list, n, n);
System.out.println(result);
}
public static int solve(List<Integer> list, int n, int f) {
int ar[] = new int[200005];
int rev[] = new int[200005];
for (int i = 0; i < list.size() + 2; i++) {
ar[i] = 1;
rev[i] = 1;
}
for (int i = 0; i < list.size() - 1; i++) {
if (list.get(i) < list.get(i + 1)) {
ar[i + 1] = ar[i] + 1;
} else {
ar[i+1] = 1;
}
}
for (int i = list.size() - 1; i >= 1; i--) {
if (list.get(i) > list.get(i - 1)) {
rev[i - 1] = rev[i] + 1;
} else {
rev[i-1] = 1;
}
}
int res = 0;
res = Math.max(ar[n - 1], rev[0]);
for (int i = 0; i < list.size() - 2; i++) {
if (list.get(i) < list.get(i + 1)) {
res = Math.max(res, ar[i + 1]);
}
if (list.get(i) < list.get(i + 2)) {
res = Math.max(res, ar[i] + rev[i + 2]);
}
res = Math.max(res, rev[i]);
res = Math.max(res, ar[i]);
}
return res;
}
} | Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | 10d30538c04ea0f47ed03073af8125d3 | train_003.jsonl | 1343662200 | Furik and Rubik take part in a relay race. The race will be set up on a large square with the side of n meters. The given square is split into n × n cells (represented as unit squares), each cell has some number.At the beginning of the race Furik stands in a cell with coordinates (1, 1), and Rubik stands in a cell with coordinates (n, n). Right after the start Furik runs towards Rubik, besides, if Furik stands at a cell with coordinates (i, j), then he can move to cell (i + 1, j) or (i, j + 1). After Furik reaches Rubik, Rubik starts running from cell with coordinates (n, n) to cell with coordinates (1, 1). If Rubik stands in cell (i, j), then he can move to cell (i - 1, j) or (i, j - 1). Neither Furik, nor Rubik are allowed to go beyond the boundaries of the field; if a player goes beyond the boundaries, he will be disqualified. To win the race, Furik and Rubik must earn as many points as possible. The number of points is the sum of numbers from the cells Furik and Rubik visited. Each cell counts only once in the sum.Print the maximum number of points Furik and Rubik can earn on the relay race. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.awt.geom.*;
import static java.lang.Math.*;
public class Solution implements Runnable {
static final long MOD = 1000000007;
int di [] = {0, 1};
int dj [] = {1, 0};
public void solve () throws Exception {
int n = nextInt();
int a [][] = new int [n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a [i][j] = nextInt();
}
}
int d [][][] = new int [n][n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
d[i][j][k] = Integer.MIN_VALUE / 2;
}
}
}
d[0][0][0] = a[0][0];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int ii = 0; ii < n; ii++) {
int jj = (i + j) - ii;
if (jj < 0 || jj >= n) continue;
for (int nextI = 0; nextI < 2; nextI++) {
for (int nextII = 0; nextII < 2; nextII++) {
int ti = i + di[nextI];
int tj = j + dj[nextI];
int tii = ii + di[nextII];
int tjj = jj + dj[nextII];
if (ti < n && tj < n && tii < n && tjj < n) {
if (ti == tii && tj == tjj) {
d[ti][tj][tii] = max (d[ti][tj][tii], d[i][j][ii] + a[ti][tj]);
} else {
d[ti][tj][tii] = max (d[ti][tj][tii], d[i][j][ii] + a[ti][tj] + a[tii][tjj]);
}
}
}
}
}
}
}
out.println(d[n - 1][n - 1][n - 1]);
}
static final String fname = "";
static long stime = 0;
BufferedReader in;
PrintWriter out;
StringTokenizer st;
private String nextToken () throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
private int nextInt () throws Exception {
return Integer.parseInt(nextToken());
}
private long nextLong () throws Exception {
return Long.parseLong(nextToken());
}
private double nextDouble () throws Exception {
return Double.parseDouble(nextToken());
}
@Override
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve ();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
out.close();
}
}
public static void main(String[] args) {
new Thread(null, new Solution(), "", 1<<26).start();
}
} | Java | ["1\n5", "2\n11 14\n16 12", "3\n25 16 25\n12 18 19\n11 13 8"] | 4 seconds | ["5", "53", "136"] | NoteComments to the second sample: The profitable path for Furik is: (1, 1), (1, 2), (2, 2), and for Rubik: (2, 2), (2, 1), (1, 1). Comments to the third sample: The optimal path for Furik is: (1, 1), (1, 2), (1, 3), (2, 3), (3, 3), and for Rubik: (3, 3), (3, 2), (2, 2), (2, 1), (1, 1). The figure to the sample: Furik's path is marked with yellow, and Rubik's path is marked with pink. | Java 7 | standard input | [
"dp"
] | 45ccda0657d2b02540b1fc33745820b8 | The first line contains a single integer (1 ≤ n ≤ 300). The next n lines contain n integers each: the j-th number on the i-th line ai, j ( - 1000 ≤ ai, j ≤ 1000) is the number written in the cell with coordinates (i, j). | 2,000 | On a single line print a single number — the answer to the problem. | standard output | |
PASSED | 54b53341108770475b50b69e2b8479af | train_003.jsonl | 1343662200 | Furik and Rubik take part in a relay race. The race will be set up on a large square with the side of n meters. The given square is split into n × n cells (represented as unit squares), each cell has some number.At the beginning of the race Furik stands in a cell with coordinates (1, 1), and Rubik stands in a cell with coordinates (n, n). Right after the start Furik runs towards Rubik, besides, if Furik stands at a cell with coordinates (i, j), then he can move to cell (i + 1, j) or (i, j + 1). After Furik reaches Rubik, Rubik starts running from cell with coordinates (n, n) to cell with coordinates (1, 1). If Rubik stands in cell (i, j), then he can move to cell (i - 1, j) or (i, j - 1). Neither Furik, nor Rubik are allowed to go beyond the boundaries of the field; if a player goes beyond the boundaries, he will be disqualified. To win the race, Furik and Rubik must earn as many points as possible. The number of points is the sum of numbers from the cells Furik and Rubik visited. Each cell counts only once in the sum.Print the maximum number of points Furik and Rubik can earn on the relay race. | 256 megabytes | import java.io.*;
import java.util.*;
public class cf214e {
public static void main(String[] args) {
FastIO in = new FastIO(), out = in;
int n = in.nextInt();
int[][] v = new int[n][n];
for(int i=0; i<n; i++) for(int j=0; j<n; j++) v[i][j] = in.nextInt();
int numDiag = 2*n-1;
int[][][] dp = new int[2][n][n];
int oo = 987654321;
for(int[][] x : dp) for(int[] y : x) Arrays.fill(y, -oo);
dp[0][0][0] = v[0][0];
for(int row = 0; row < numDiag-1; row++) {
int diagWidth = Math.min(row+1, numDiag - row);
int nRow = row+1;
int nWidth = Math.min(nRow+1, numDiag - nRow);
for(int[] x : dp[nRow%2]) Arrays.fill(x,-oo);
int lod = 0, hid = 1;
if(row >= n-1) {
lod = -1;
hid = 0;
}
for(int i=0; i<diagWidth; i++)
for(int j=0; j<diagWidth; j++)
for(int d1 = lod; d1 <= hid; d1++)
for(int d2 = lod; d2 <= hid; d2++) {
int ni = i+d1;
int nj = j+d2;
if(ni < 0 || nj < 0 || ni >= nWidth || nj >= nWidth) continue;
int nScore = dp[row%2][i][j];
int x = Math.min(nRow,n-1) - ni;
int y = Math.max(0, nRow-n+1) + ni;
nScore += v[x][y];
if(ni != nj) {
x = Math.min(nRow,n-1) - nj;
y = Math.max(0, nRow-n+1) + nj;
nScore += v[x][y];
}
dp[nRow%2][ni][nj] = Math.max(dp[nRow%2][ni][nj],nScore);
}
}
out.println(dp[(numDiag-1)%2][0][0]);
out.close();
}
/*
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 9
1 2 3 4 5 6 7 8 8 8
1 2 3 4 5 6 7 7 7 7
1 2 3 4 5 6 6 6 6 6
1 2 3 4 5 5 5 5 5 5
1 2 3 4 4 4 4 4 4 4
1 2 3 3 3 3 3 3 3 3
1 2 2 2 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1 1
*/
static class FastIO extends PrintWriter {
BufferedReader br;
StringTokenizer st;
public FastIO() {
this(System.in, System.out);
}
public FastIO(InputStream in, OutputStream out) {
super(new BufferedWriter(new OutputStreamWriter(out)));
br = new BufferedReader(new InputStreamReader(in));
scanLine();
}
public void scanLine() {
try {
st = new StringTokenizer(br.readLine().trim());
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
public int numTokens() {
if (!st.hasMoreTokens()) {
scanLine();
return numTokens();
}
return st.countTokens();
}
public String next() {
if (!st.hasMoreTokens()) {
scanLine();
return next();
}
return st.nextToken();
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["1\n5", "2\n11 14\n16 12", "3\n25 16 25\n12 18 19\n11 13 8"] | 4 seconds | ["5", "53", "136"] | NoteComments to the second sample: The profitable path for Furik is: (1, 1), (1, 2), (2, 2), and for Rubik: (2, 2), (2, 1), (1, 1). Comments to the third sample: The optimal path for Furik is: (1, 1), (1, 2), (1, 3), (2, 3), (3, 3), and for Rubik: (3, 3), (3, 2), (2, 2), (2, 1), (1, 1). The figure to the sample: Furik's path is marked with yellow, and Rubik's path is marked with pink. | Java 7 | standard input | [
"dp"
] | 45ccda0657d2b02540b1fc33745820b8 | The first line contains a single integer (1 ≤ n ≤ 300). The next n lines contain n integers each: the j-th number on the i-th line ai, j ( - 1000 ≤ ai, j ≤ 1000) is the number written in the cell with coordinates (i, j). | 2,000 | On a single line print a single number — the answer to the problem. | standard output | |
PASSED | 9417b435f145a5341acf1190c403b36a | train_003.jsonl | 1343662200 | Furik and Rubik take part in a relay race. The race will be set up on a large square with the side of n meters. The given square is split into n × n cells (represented as unit squares), each cell has some number.At the beginning of the race Furik stands in a cell with coordinates (1, 1), and Rubik stands in a cell with coordinates (n, n). Right after the start Furik runs towards Rubik, besides, if Furik stands at a cell with coordinates (i, j), then he can move to cell (i + 1, j) or (i, j + 1). After Furik reaches Rubik, Rubik starts running from cell with coordinates (n, n) to cell with coordinates (1, 1). If Rubik stands in cell (i, j), then he can move to cell (i - 1, j) or (i, j - 1). Neither Furik, nor Rubik are allowed to go beyond the boundaries of the field; if a player goes beyond the boundaries, he will be disqualified. To win the race, Furik and Rubik must earn as many points as possible. The number of points is the sum of numbers from the cells Furik and Rubik visited. Each cell counts only once in the sum.Print the maximum number of points Furik and Rubik can earn on the relay race. | 256 megabytes | import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.math.BigDecimal;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author aircube
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastInputReader in = new FastInputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
}
class TaskC {
public void solve(int testNumber, FastInputReader in, PrintWriter out) {
int n = in.nextInt();
int[][]a = new int[n][n];
for (int i = 0; i < n; ++i)
InputUtils.inputArray(in, a[i]);
int[][]d = new int[n][n];
MatrixUtils.fill(d, Integer.MIN_VALUE);
d[0][0] = a[0][0];
int []dx = new int[] {+1, 0};
int []dy = new int[] {0, +1};
for (int diag = 0; diag < 2 * n - 2; ++diag) {
int[][]next = new int[n][n];
MatrixUtils.fill(next, Integer.MIN_VALUE);
for (int x1 = 0; x1 < n; ++x1)
for (int x2 = 0; x2 < n; ++x2) {
// x + y = diag
int y1 = diag - x1;
int y2 = diag - x2;
for (int dir1 = 0; dir1 < 2; ++dir1)
for (int dir2 = 0; dir2 < 2; ++dir2) {
int nx1 = x1 + dx[dir1];
int ny1 = y1 + dy[dir1];
int nx2 = x2 + dx[dir2];
int ny2 = y2 + dy[dir2];
if (field(nx1, ny1,n) && field(nx2, ny2, n)) {
if (d[x1][x2]==Integer.MIN_VALUE)
continue;
int add = a[ny1][nx1] + a[ny2][nx2];
if(ny1 == ny2 && nx1 == nx2)
add -= a[ny1][nx1];
next[nx1][nx2] = Math.max(next[nx1][nx2], d[x1][x2] + add);
}
}
}
d = next;
}
out.print(d[n - 1][n - 1]);
}
private boolean field(int x, int y, int n) {
return 0 <= x && x < n && 0 <= y && y < n;
}
}
class FastInputReader {
private StringTokenizer tokenizer;
public BufferedReader reader;
public FastInputReader(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
tokenizer=null;
}
public String next() {
try {
while (tokenizer==null || !tokenizer.hasMoreTokens()){
tokenizer=new StringTokenizer(reader.readLine());
}
} catch (IOException e) {
return "-1";
}
return tokenizer.nextToken();
}
public int nextInt(){
return Integer.parseInt(next());
}
}
class InputUtils {
public static void inputArray(FastInputReader in, int[]...arrays){
for (int i = 0; i < arrays[0].length; ++i) {
for (int j = 0; j < arrays.length; ++j) {
arrays[j][i] = in.nextInt();
}
}
}
}
class MatrixUtils {
public static void fill(int[][]a, int value) {
for (int[]b:a)
Arrays.fill(b, value);
}
}
| Java | ["1\n5", "2\n11 14\n16 12", "3\n25 16 25\n12 18 19\n11 13 8"] | 4 seconds | ["5", "53", "136"] | NoteComments to the second sample: The profitable path for Furik is: (1, 1), (1, 2), (2, 2), and for Rubik: (2, 2), (2, 1), (1, 1). Comments to the third sample: The optimal path for Furik is: (1, 1), (1, 2), (1, 3), (2, 3), (3, 3), and for Rubik: (3, 3), (3, 2), (2, 2), (2, 1), (1, 1). The figure to the sample: Furik's path is marked with yellow, and Rubik's path is marked with pink. | Java 7 | standard input | [
"dp"
] | 45ccda0657d2b02540b1fc33745820b8 | The first line contains a single integer (1 ≤ n ≤ 300). The next n lines contain n integers each: the j-th number on the i-th line ai, j ( - 1000 ≤ ai, j ≤ 1000) is the number written in the cell with coordinates (i, j). | 2,000 | On a single line print a single number — the answer to the problem. | standard output | |
PASSED | d7eeaccaf45ba3b0afd688c47ab5a434 | train_003.jsonl | 1343662200 | Furik and Rubik take part in a relay race. The race will be set up on a large square with the side of n meters. The given square is split into n × n cells (represented as unit squares), each cell has some number.At the beginning of the race Furik stands in a cell with coordinates (1, 1), and Rubik stands in a cell with coordinates (n, n). Right after the start Furik runs towards Rubik, besides, if Furik stands at a cell with coordinates (i, j), then he can move to cell (i + 1, j) or (i, j + 1). After Furik reaches Rubik, Rubik starts running from cell with coordinates (n, n) to cell with coordinates (1, 1). If Rubik stands in cell (i, j), then he can move to cell (i - 1, j) or (i, j - 1). Neither Furik, nor Rubik are allowed to go beyond the boundaries of the field; if a player goes beyond the boundaries, he will be disqualified. To win the race, Furik and Rubik must earn as many points as possible. The number of points is the sum of numbers from the cells Furik and Rubik visited. Each cell counts only once in the sum.Print the maximum number of points Furik and Rubik can earn on the relay race. | 256 megabytes | import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.math.BigDecimal;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author aircube
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastInputReader in = new FastInputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
}
class TaskC {
public void solve(int testNumber, FastInputReader in, PrintWriter out) {
int n = in.nextInt();
int[][]a = new int[n][n];
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
a[i][j] = in.nextInt();
int[][]d = new int[n][n];
MatrixUtils.fill(d, Integer.MIN_VALUE);
d[0][0] = a[0][0];
int []dx = new int[] {+1, 0};
int []dy = new int[] {0, +1};
for (int diag = 0; diag < 2 * n - 2; ++diag) {
int[][]next = new int[n][n];
MatrixUtils.fill(next, Integer.MIN_VALUE);
for (int x1 = 0; x1 < n; ++x1)
for (int x2 = x1; x2 < n; ++x2) {
// x + y = diag
int y1 = diag - x1;
int y2 = diag - x2;
for (int dir1 = 0; dir1 < 2; ++dir1)
for (int dir2 = 0; dir2 < 2; ++dir2) {
int nx1 = x1 + dx[dir1];
int ny1 = y1 + dy[dir1];
int nx2 = x2 + dx[dir2];
int ny2 = y2 + dy[dir2];
if (field(nx1, ny1,n) && field(nx2, ny2, n)) {
if (d[x1][x2]==Integer.MIN_VALUE)
continue;
int add = a[ny1][nx1] + a[ny2][nx2];
if(ny1 == ny2 && nx1 == nx2)
add -= a[ny1][nx1];
next[Math.min(nx1, nx2)][Math.max(nx1, nx2)] = Math.max(next[Math.min(nx1, nx2)][Math.max(nx1, nx2)], d[x1][x2] + add);
}
}
}
d = next;
}
out.print(d[n - 1][n - 1]);
}
private boolean field(int x, int y, int n) {
return 0 <= x && x < n && 0 <= y && y < n;
}
}
class FastInputReader {
private StringTokenizer tokenizer;
public BufferedReader reader;
public FastInputReader(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
tokenizer=null;
}
public String next() {
try {
while (tokenizer==null || !tokenizer.hasMoreTokens()){
tokenizer=new StringTokenizer(reader.readLine());
}
} catch (IOException e) {
return "-1";
}
return tokenizer.nextToken();
}
public int nextInt(){
return Integer.parseInt(next());
}
}
class MatrixUtils {
public static void fill(int[][]a, int value) {
for (int[]b:a)
Arrays.fill(b, value);
}
}
| Java | ["1\n5", "2\n11 14\n16 12", "3\n25 16 25\n12 18 19\n11 13 8"] | 4 seconds | ["5", "53", "136"] | NoteComments to the second sample: The profitable path for Furik is: (1, 1), (1, 2), (2, 2), and for Rubik: (2, 2), (2, 1), (1, 1). Comments to the third sample: The optimal path for Furik is: (1, 1), (1, 2), (1, 3), (2, 3), (3, 3), and for Rubik: (3, 3), (3, 2), (2, 2), (2, 1), (1, 1). The figure to the sample: Furik's path is marked with yellow, and Rubik's path is marked with pink. | Java 7 | standard input | [
"dp"
] | 45ccda0657d2b02540b1fc33745820b8 | The first line contains a single integer (1 ≤ n ≤ 300). The next n lines contain n integers each: the j-th number on the i-th line ai, j ( - 1000 ≤ ai, j ≤ 1000) is the number written in the cell with coordinates (i, j). | 2,000 | On a single line print a single number — the answer to the problem. | standard output | |
PASSED | 4b67e51ae1cba0c42cf69ae71b41bde2 | train_003.jsonl | 1343662200 | Furik and Rubik take part in a relay race. The race will be set up on a large square with the side of n meters. The given square is split into n × n cells (represented as unit squares), each cell has some number.At the beginning of the race Furik stands in a cell with coordinates (1, 1), and Rubik stands in a cell with coordinates (n, n). Right after the start Furik runs towards Rubik, besides, if Furik stands at a cell with coordinates (i, j), then he can move to cell (i + 1, j) or (i, j + 1). After Furik reaches Rubik, Rubik starts running from cell with coordinates (n, n) to cell with coordinates (1, 1). If Rubik stands in cell (i, j), then he can move to cell (i - 1, j) or (i, j - 1). Neither Furik, nor Rubik are allowed to go beyond the boundaries of the field; if a player goes beyond the boundaries, he will be disqualified. To win the race, Furik and Rubik must earn as many points as possible. The number of points is the sum of numbers from the cells Furik and Rubik visited. Each cell counts only once in the sum.Print the maximum number of points Furik and Rubik can earn on the relay race. | 256 megabytes | import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.math.BigDecimal;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author aircube
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastInputReader in = new FastInputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
}
class TaskC {
public void solve(int testNumber, FastInputReader in, PrintWriter out) {
int n = in.nextInt();
int[][]a = new int[n][n];
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
a[i][j] = in.nextInt();
int[][]d = new int[n][n];
MatrixUtils.fill(d, Integer.MIN_VALUE);
d[0][0] = a[0][0];
int []dx = new int[] {+1, 0};
int []dy = new int[] {0, +1};
for (int diag = 0; diag < 2 * n - 2; ++diag) {
int[][]next = new int[n][n];
MatrixUtils.fill(next, Integer.MIN_VALUE);
for (int x1 = 0; x1 < Math.min(n, diag + 1); ++x1)
for (int x2 = x1; x2 < Math.min(n, diag + 1); ++x2) {
// x + y = diag
int y1 = diag - x1;
int y2 = diag - x2;
for (int dir1 = 0; dir1 < 2; ++dir1)
for (int dir2 = 0; dir2 < 2; ++dir2) {
int nx1 = x1 + dx[dir1];
int ny1 = y1 + dy[dir1];
int nx2 = x2 + dx[dir2];
int ny2 = y2 + dy[dir2];
if (field(nx1, ny1,n) && field(nx2, ny2, n)) {
int add = a[ny1][nx1] + a[ny2][nx2];
if(ny1 == ny2 && nx1 == nx2)
add -= a[ny1][nx1];
next[Math.min(nx1, nx2)][Math.max(nx1, nx2)] = Math.max(next[Math.min(nx1, nx2)][Math.max(nx1, nx2)], d[x1][x2] + add);
}
}
}
d = next;
}
out.print(d[n - 1][n - 1]);
}
private boolean field(int x, int y, int n) {
return 0 <= x && x < n && 0 <= y && y < n;
}
}
class FastInputReader {
private StringTokenizer tokenizer;
public BufferedReader reader;
public FastInputReader(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
tokenizer=null;
}
public String next() {
try {
while (tokenizer==null || !tokenizer.hasMoreTokens()){
tokenizer=new StringTokenizer(reader.readLine());
}
} catch (IOException e) {
return "-1";
}
return tokenizer.nextToken();
}
public int nextInt(){
return Integer.parseInt(next());
}
}
class MatrixUtils {
public static void fill(int[][]a, int value) {
for (int[]b:a)
Arrays.fill(b, value);
}
}
| Java | ["1\n5", "2\n11 14\n16 12", "3\n25 16 25\n12 18 19\n11 13 8"] | 4 seconds | ["5", "53", "136"] | NoteComments to the second sample: The profitable path for Furik is: (1, 1), (1, 2), (2, 2), and for Rubik: (2, 2), (2, 1), (1, 1). Comments to the third sample: The optimal path for Furik is: (1, 1), (1, 2), (1, 3), (2, 3), (3, 3), and for Rubik: (3, 3), (3, 2), (2, 2), (2, 1), (1, 1). The figure to the sample: Furik's path is marked with yellow, and Rubik's path is marked with pink. | Java 7 | standard input | [
"dp"
] | 45ccda0657d2b02540b1fc33745820b8 | The first line contains a single integer (1 ≤ n ≤ 300). The next n lines contain n integers each: the j-th number on the i-th line ai, j ( - 1000 ≤ ai, j ≤ 1000) is the number written in the cell with coordinates (i, j). | 2,000 | On a single line print a single number — the answer to the problem. | standard output | |
PASSED | 353b12fc6693cb49e5d2558333ee1371 | train_003.jsonl | 1343662200 | Furik and Rubik take part in a relay race. The race will be set up on a large square with the side of n meters. The given square is split into n × n cells (represented as unit squares), each cell has some number.At the beginning of the race Furik stands in a cell with coordinates (1, 1), and Rubik stands in a cell with coordinates (n, n). Right after the start Furik runs towards Rubik, besides, if Furik stands at a cell with coordinates (i, j), then he can move to cell (i + 1, j) or (i, j + 1). After Furik reaches Rubik, Rubik starts running from cell with coordinates (n, n) to cell with coordinates (1, 1). If Rubik stands in cell (i, j), then he can move to cell (i - 1, j) or (i, j - 1). Neither Furik, nor Rubik are allowed to go beyond the boundaries of the field; if a player goes beyond the boundaries, he will be disqualified. To win the race, Furik and Rubik must earn as many points as possible. The number of points is the sum of numbers from the cells Furik and Rubik visited. Each cell counts only once in the sum.Print the maximum number of points Furik and Rubik can earn on the relay race. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.awt.geom.*;
import static java.lang.Math.*;
public class Solution implements Runnable {
static final long MOD = 1000000007;
int di [] = {0, 1};
int dj [] = {1, 0};
public void solve () throws Exception {
int n = nextInt();
int a [][] = new int [n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a [i][j] = nextInt();
}
}
int d [][][] = new int [n][n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
d[i][j][k] = Integer.MIN_VALUE / 2;
}
}
}
d[0][0][0] = a[0][0];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int ii = 0; ii < n; ii++) {
int jj = (i + j) - ii;
if (jj < 0 || jj >= n) continue;
for (int nextI = 0; nextI < 2; nextI++) {
for (int nextII = 0; nextII < 2; nextII++) {
int ti = i + di[nextI];
int tj = j + dj[nextI];
int tii = ii + di[nextII];
int tjj = jj + dj[nextII];
if (ti < n && tj < n && tii < n && tjj < n) {
if (ti == tii && tj == tjj) {
d[ti][tj][tii] = max (d[ti][tj][tii], d[i][j][ii] + a[ti][tj]);
} else {
d[ti][tj][tii] = max (d[ti][tj][tii], d[i][j][ii] + a[ti][tj] + a[tii][tjj]);
}
}
}
}
}
}
}
out.println(d[n - 1][n - 1][n - 1]);
}
static final String fname = "";
static long stime = 0;
BufferedReader in;
PrintWriter out;
StringTokenizer st;
private String nextToken () throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
private int nextInt () throws Exception {
return Integer.parseInt(nextToken());
}
private long nextLong () throws Exception {
return Long.parseLong(nextToken());
}
private double nextDouble () throws Exception {
return Double.parseDouble(nextToken());
}
@Override
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve ();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
out.close();
}
}
public static void main(String[] args) {
new Thread(null, new Solution(), "", 1<<26).start();
}
} | Java | ["1\n5", "2\n11 14\n16 12", "3\n25 16 25\n12 18 19\n11 13 8"] | 4 seconds | ["5", "53", "136"] | NoteComments to the second sample: The profitable path for Furik is: (1, 1), (1, 2), (2, 2), and for Rubik: (2, 2), (2, 1), (1, 1). Comments to the third sample: The optimal path for Furik is: (1, 1), (1, 2), (1, 3), (2, 3), (3, 3), and for Rubik: (3, 3), (3, 2), (2, 2), (2, 1), (1, 1). The figure to the sample: Furik's path is marked with yellow, and Rubik's path is marked with pink. | Java 7 | standard input | [
"dp"
] | 45ccda0657d2b02540b1fc33745820b8 | The first line contains a single integer (1 ≤ n ≤ 300). The next n lines contain n integers each: the j-th number on the i-th line ai, j ( - 1000 ≤ ai, j ≤ 1000) is the number written in the cell with coordinates (i, j). | 2,000 | On a single line print a single number — the answer to the problem. | standard output | |
PASSED | 040c7cb5537f934f68504e83635cc6d1 | train_003.jsonl | 1343662200 | Furik and Rubik take part in a relay race. The race will be set up on a large square with the side of n meters. The given square is split into n × n cells (represented as unit squares), each cell has some number.At the beginning of the race Furik stands in a cell with coordinates (1, 1), and Rubik stands in a cell with coordinates (n, n). Right after the start Furik runs towards Rubik, besides, if Furik stands at a cell with coordinates (i, j), then he can move to cell (i + 1, j) or (i, j + 1). After Furik reaches Rubik, Rubik starts running from cell with coordinates (n, n) to cell with coordinates (1, 1). If Rubik stands in cell (i, j), then he can move to cell (i - 1, j) or (i, j - 1). Neither Furik, nor Rubik are allowed to go beyond the boundaries of the field; if a player goes beyond the boundaries, he will be disqualified. To win the race, Furik and Rubik must earn as many points as possible. The number of points is the sum of numbers from the cells Furik and Rubik visited. Each cell counts only once in the sum.Print the maximum number of points Furik and Rubik can earn on the relay race. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class R131qCRelayRace {
static int n;
static int a[][];
static int dp[][][];
static int oo = (int)(1e9);
public static void main(String args[] ) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter w = new PrintWriter(System.out);
n = ip(br.readLine());
a = new int[n][n];
for(int i=0;i<n;i++){
StringTokenizer st2 = new StringTokenizer(br.readLine());
for(int j=0;j<n;j++)
a[i][j] = ip(st2.nextToken());
}
dp = new int[n][n][2];
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
dp[i][j][1] = a[n-1][n-1];
for(int total = 2*n-2;total>=0;total--){
for(int aR=Math.max(0,total-(n-1));aR<=Math.min(n-1,total);aR++){
for(int bR=Math.max(0,total-(n-1));bR<=Math.min(n-1,total);bR++){
int ax = total - aR;
int ay = aR;
int bx = total - bR;
int by = bR;
int ans = -oo;
if(ax+1 < n && bx+1 < n)
ans = Math.max(ans,dp[aR][bR][1]);
if(ax+1 < n && by+1 < n)
ans = Math.max(ans,dp[aR][bR+1][1]);
if(ay+1 < n && bx+1 < n)
ans = Math.max(ans,dp[aR+1][bR][1]);
if(ay+1 < n && by+1 < n)
ans = Math.max(ans,dp[aR+1][bR+1][1]);
ans = (ans == -oo) ? 0 : ans;
ans += a[ax][ay] + a[bx][by];
if(ax == bx && ay == by) ans -= a[ax][by];
dp[aR][bR][0] = ans;
}
}
for(int aR=0;aR<=Math.min(n-1,total);aR++)
for(int bR=0;bR<=Math.min(n-1,total);bR++)
dp[aR][bR][1] = dp[aR][bR][0];
}
w.println(dp[0][0][1]);
w.close();
}
public static int solve(int aR,int bR,int total){
if(total == 2*n - 1) return 0;
if(dp[aR][bR][total] == -oo){
int ax = total - aR;
int ay = aR;
int bx = total - bR;
int by = bR;
int ans = -oo;
if(ax+1 < n && bx+1 < n)
ans = Math.max(ans,solve(aR,bR,total+1));
if(ax+1 < n && by+1 < n)
ans = Math.max(ans,solve(aR,bR+1,total+1));
if(ay+1 < n && bx+1 < n)
ans = Math.max(ans,solve(aR+1,bR,total+1));
if(ay+1 < n && by+1 < n)
ans = Math.max(ans,solve(aR+1,bR+1,total+1));
ans = (ans == -oo) ? 0 : ans;
ans += a[ax][ay] + a[bx][by];
if(ax == bx && ay == by) ans -= a[ax][by];
dp[aR][bR][total] = ans;
}
return dp[aR][bR][total];
}
public static int ip(String s){
return Integer.parseInt(s);
}
}
| Java | ["1\n5", "2\n11 14\n16 12", "3\n25 16 25\n12 18 19\n11 13 8"] | 4 seconds | ["5", "53", "136"] | NoteComments to the second sample: The profitable path for Furik is: (1, 1), (1, 2), (2, 2), and for Rubik: (2, 2), (2, 1), (1, 1). Comments to the third sample: The optimal path for Furik is: (1, 1), (1, 2), (1, 3), (2, 3), (3, 3), and for Rubik: (3, 3), (3, 2), (2, 2), (2, 1), (1, 1). The figure to the sample: Furik's path is marked with yellow, and Rubik's path is marked with pink. | Java 7 | standard input | [
"dp"
] | 45ccda0657d2b02540b1fc33745820b8 | The first line contains a single integer (1 ≤ n ≤ 300). The next n lines contain n integers each: the j-th number on the i-th line ai, j ( - 1000 ≤ ai, j ≤ 1000) is the number written in the cell with coordinates (i, j). | 2,000 | On a single line print a single number — the answer to the problem. | standard output | |
PASSED | f2603f2ef839d071a30306e0bc5e9147 | train_003.jsonl | 1343662200 | Furik and Rubik take part in a relay race. The race will be set up on a large square with the side of n meters. The given square is split into n × n cells (represented as unit squares), each cell has some number.At the beginning of the race Furik stands in a cell with coordinates (1, 1), and Rubik stands in a cell with coordinates (n, n). Right after the start Furik runs towards Rubik, besides, if Furik stands at a cell with coordinates (i, j), then he can move to cell (i + 1, j) or (i, j + 1). After Furik reaches Rubik, Rubik starts running from cell with coordinates (n, n) to cell with coordinates (1, 1). If Rubik stands in cell (i, j), then he can move to cell (i - 1, j) or (i, j - 1). Neither Furik, nor Rubik are allowed to go beyond the boundaries of the field; if a player goes beyond the boundaries, he will be disqualified. To win the race, Furik and Rubik must earn as many points as possible. The number of points is the sum of numbers from the cells Furik and Rubik visited. Each cell counts only once in the sum.Print the maximum number of points Furik and Rubik can earn on the relay race. | 256 megabytes | import java.io.*;
import java.util.*;
public class c {
static int n;
static int[][] as;
static int oo = -999999999;
public static void main(String[] args) throws IOException {
input.init(System.in);
PrintWriter out = new PrintWriter(System.out);
n = input.nextInt();
as = new int[n][n];
for(int i = 0; i<n; i++)
for(int j = 0; j<n; j++)
as[i][j] = input.nextInt();
memo = new int[2][n][n];
for(int t = 2*n-2; t>=0; t--)
for(int r1 = 0; r1<n && r1 <= t; r1++)
for(int r2 = 0; r2<n && r2 <= t; r2++)
{
if(t == n - 1 + n - 1)
{
memo[t&1][r1][r2] = 0;
continue;
}
int c1 = t - r1, c2 = t - r2;
if(c1 >= n || c2 >= n) continue;
int max = -1000000000;
for(int dr1 = 0; dr1 <2; dr1++)
for(int dr2 = 0; dr2 < 2; dr2++)
{
int nr1 = r1 + dr1, nr2 = r2 + dr2, nc1 = c1 + 1 - dr1, nc2 = c2 + 1 - dr2;
if(nr1 == n || nr2 == n || nc1 == n || nc2 == n) continue;
int add = (nr1 == nr2 ? as[nr1][nc1] : (as[nr1][nc1] + as[nr2][nc2])) + memo[(t&1)^1][nr1][nr2];
max = Math.max(max, add);
}
memo[t&1][r1][r2] = max;
}
out.println(as[0][0] + memo[0][0][0]);
out.close();
}
static int[][][] memo;
public static class input {
static BufferedReader reader;
static StringTokenizer tokenizer;
static void init(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
static String next() throws IOException {
while (!tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(reader.readLine());
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
}
}
| Java | ["1\n5", "2\n11 14\n16 12", "3\n25 16 25\n12 18 19\n11 13 8"] | 4 seconds | ["5", "53", "136"] | NoteComments to the second sample: The profitable path for Furik is: (1, 1), (1, 2), (2, 2), and for Rubik: (2, 2), (2, 1), (1, 1). Comments to the third sample: The optimal path for Furik is: (1, 1), (1, 2), (1, 3), (2, 3), (3, 3), and for Rubik: (3, 3), (3, 2), (2, 2), (2, 1), (1, 1). The figure to the sample: Furik's path is marked with yellow, and Rubik's path is marked with pink. | Java 7 | standard input | [
"dp"
] | 45ccda0657d2b02540b1fc33745820b8 | The first line contains a single integer (1 ≤ n ≤ 300). The next n lines contain n integers each: the j-th number on the i-th line ai, j ( - 1000 ≤ ai, j ≤ 1000) is the number written in the cell with coordinates (i, j). | 2,000 | On a single line print a single number — the answer to the problem. | standard output | |
PASSED | b7cda26348708b7ede30d939a3a8085e | train_003.jsonl | 1343662200 | Furik and Rubik take part in a relay race. The race will be set up on a large square with the side of n meters. The given square is split into n × n cells (represented as unit squares), each cell has some number.At the beginning of the race Furik stands in a cell with coordinates (1, 1), and Rubik stands in a cell with coordinates (n, n). Right after the start Furik runs towards Rubik, besides, if Furik stands at a cell with coordinates (i, j), then he can move to cell (i + 1, j) or (i, j + 1). After Furik reaches Rubik, Rubik starts running from cell with coordinates (n, n) to cell with coordinates (1, 1). If Rubik stands in cell (i, j), then he can move to cell (i - 1, j) or (i, j - 1). Neither Furik, nor Rubik are allowed to go beyond the boundaries of the field; if a player goes beyond the boundaries, he will be disqualified. To win the race, Furik and Rubik must earn as many points as possible. The number of points is the sum of numbers from the cells Furik and Rubik visited. Each cell counts only once in the sum.Print the maximum number of points Furik and Rubik can earn on the relay race. | 256 megabytes | import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.Locale;
import java.io.OutputStream;
import java.util.RandomAccess;
import java.io.PrintWriter;
import java.util.AbstractList;
import java.io.Writer;
import java.util.Collection;
import java.util.List;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Jacob Jiang
*/
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();
}
}
class TaskC {
public static final int INF = (int) 4e8;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int[][] score = in.next2DIntArray(n, n);
int[][][] dp = new int[n + n - 1][][];
dp[0] = new int[n][n];
ArrayUtils.fill(dp[0], -INF);
dp[0][0][0] = score[0][0];
for (int len = 1; len <= n + n - 2; len++) {
dp[len] = new int[n][n];
ArrayUtils.fill(dp[len], -INF);
for (int ai = 0; ai < n; ai++) {
int aj = len - ai;
if (aj < 0 || aj >= n) continue;
for (int bi = 0; bi < n; bi++) {
int bj = len - bi;
if (bj < 0 || bj >= n) continue;
int preMax = -INF;
for (int da = -1; da <= 0; da++) {
if (ai + da >= 0) {
for (int db = -1; db <= 0; db++) {
if (bi + db >= 0) {
preMax = Math.max(preMax, dp[len - 1][ai + da][bi + db]);
}
}
}
}
dp[len][ai][bi] = preMax + (ai == bi ? score[ai][aj] : score[ai][aj] + score[bi][bj]);
}
}
dp[len - 1] = null;
}
out.println(dp[n + n - 2][n - 1][n - 1]);
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1 << 20];
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 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 & 15;
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int[] nextIntArray(int count) {
int[] result = new int[count];
for (int i = 0; i < count; i++) {
result[i] = nextInt();
}
return result;
}
public int[][] next2DIntArray(int n, int m) {
int[][] result = new int[n][];
for (int i = 0; i < n; i++) {
result[i] = nextIntArray(m);
}
return result;
}
}
class OutputWriter {
private PrintWriter writer;
public OutputWriter(OutputStream stream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void println(int x) {
writer.println(x);
}
public void close() {
writer.close();
}
}
class ArrayUtils {
public static void fill(int[][] array, int val) {
for (int[] subArray : array) {
Arrays.fill(subArray, val);
}
}
}
| Java | ["1\n5", "2\n11 14\n16 12", "3\n25 16 25\n12 18 19\n11 13 8"] | 4 seconds | ["5", "53", "136"] | NoteComments to the second sample: The profitable path for Furik is: (1, 1), (1, 2), (2, 2), and for Rubik: (2, 2), (2, 1), (1, 1). Comments to the third sample: The optimal path for Furik is: (1, 1), (1, 2), (1, 3), (2, 3), (3, 3), and for Rubik: (3, 3), (3, 2), (2, 2), (2, 1), (1, 1). The figure to the sample: Furik's path is marked with yellow, and Rubik's path is marked with pink. | Java 7 | standard input | [
"dp"
] | 45ccda0657d2b02540b1fc33745820b8 | The first line contains a single integer (1 ≤ n ≤ 300). The next n lines contain n integers each: the j-th number on the i-th line ai, j ( - 1000 ≤ ai, j ≤ 1000) is the number written in the cell with coordinates (i, j). | 2,000 | On a single line print a single number — the answer to the problem. | standard output | |
PASSED | c0896bfa7bea3b749d7b5ea27442a59e | train_003.jsonl | 1343662200 | Furik and Rubik take part in a relay race. The race will be set up on a large square with the side of n meters. The given square is split into n × n cells (represented as unit squares), each cell has some number.At the beginning of the race Furik stands in a cell with coordinates (1, 1), and Rubik stands in a cell with coordinates (n, n). Right after the start Furik runs towards Rubik, besides, if Furik stands at a cell with coordinates (i, j), then he can move to cell (i + 1, j) or (i, j + 1). After Furik reaches Rubik, Rubik starts running from cell with coordinates (n, n) to cell with coordinates (1, 1). If Rubik stands in cell (i, j), then he can move to cell (i - 1, j) or (i, j - 1). Neither Furik, nor Rubik are allowed to go beyond the boundaries of the field; if a player goes beyond the boundaries, he will be disqualified. To win the race, Furik and Rubik must earn as many points as possible. The number of points is the sum of numbers from the cells Furik and Rubik visited. Each cell counts only once in the sum.Print the maximum number of points Furik and Rubik can earn on the relay race. | 256 megabytes | import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.Locale;
import java.io.OutputStream;
import java.util.RandomAccess;
import java.io.PrintWriter;
import java.util.AbstractList;
import java.io.Writer;
import java.util.Collection;
import java.util.List;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Jacob Jiang
*/
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();
}
}
class TaskC {
public static final int INF = (int) 4e8;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int[][] score = in.next2DIntArray(n, n);
int[][] dp = new int[n][n];
ArrayUtils.fill(dp, -INF);
dp[0][0] = score[0][0];
for (int len = 1; len <= n + n - 2; len++) {
int[][] preDp = dp;
dp = new int[n][n];
ArrayUtils.fill(dp, -INF);
for (int ai = 0; ai < n; ai++) {
int aj = len - ai;
if (aj < 0 || aj >= n) continue;
for (int bi = 0; bi < n; bi++) {
int bj = len - bi;
if (bj < 0 || bj >= n) continue;
int preMax = -INF;
for (int da = -1; da <= 0; da++) {
if (ai + da >= 0) {
for (int db = -1; db <= 0; db++) {
if (bi + db >= 0) {
preMax = Math.max(preMax, preDp[ai + da][bi + db]);
}
}
}
}
dp[ai][bi] = preMax + (ai == bi ? score[ai][aj] : score[ai][aj] + score[bi][bj]);
}
}
}
out.println(dp[n - 1][n - 1]);
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1 << 20];
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 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 & 15;
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int[] nextIntArray(int count) {
int[] result = new int[count];
for (int i = 0; i < count; i++) {
result[i] = nextInt();
}
return result;
}
public int[][] next2DIntArray(int n, int m) {
int[][] result = new int[n][];
for (int i = 0; i < n; i++) {
result[i] = nextIntArray(m);
}
return result;
}
}
class OutputWriter {
private PrintWriter writer;
public OutputWriter(OutputStream stream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void println(int x) {
writer.println(x);
}
public void close() {
writer.close();
}
}
class ArrayUtils {
public static void fill(int[][] array, int val) {
for (int[] subArray : array) {
Arrays.fill(subArray, val);
}
}
}
| Java | ["1\n5", "2\n11 14\n16 12", "3\n25 16 25\n12 18 19\n11 13 8"] | 4 seconds | ["5", "53", "136"] | NoteComments to the second sample: The profitable path for Furik is: (1, 1), (1, 2), (2, 2), and for Rubik: (2, 2), (2, 1), (1, 1). Comments to the third sample: The optimal path for Furik is: (1, 1), (1, 2), (1, 3), (2, 3), (3, 3), and for Rubik: (3, 3), (3, 2), (2, 2), (2, 1), (1, 1). The figure to the sample: Furik's path is marked with yellow, and Rubik's path is marked with pink. | Java 7 | standard input | [
"dp"
] | 45ccda0657d2b02540b1fc33745820b8 | The first line contains a single integer (1 ≤ n ≤ 300). The next n lines contain n integers each: the j-th number on the i-th line ai, j ( - 1000 ≤ ai, j ≤ 1000) is the number written in the cell with coordinates (i, j). | 2,000 | On a single line print a single number — the answer to the problem. | standard output | |
PASSED | b22bb804e153a2ff1551dc7524e63cda | train_003.jsonl | 1343662200 | Furik and Rubik take part in a relay race. The race will be set up on a large square with the side of n meters. The given square is split into n × n cells (represented as unit squares), each cell has some number.At the beginning of the race Furik stands in a cell with coordinates (1, 1), and Rubik stands in a cell with coordinates (n, n). Right after the start Furik runs towards Rubik, besides, if Furik stands at a cell with coordinates (i, j), then he can move to cell (i + 1, j) or (i, j + 1). After Furik reaches Rubik, Rubik starts running from cell with coordinates (n, n) to cell with coordinates (1, 1). If Rubik stands in cell (i, j), then he can move to cell (i - 1, j) or (i, j - 1). Neither Furik, nor Rubik are allowed to go beyond the boundaries of the field; if a player goes beyond the boundaries, he will be disqualified. To win the race, Furik and Rubik must earn as many points as possible. The number of points is the sum of numbers from the cells Furik and Rubik visited. Each cell counts only once in the sum.Print the maximum number of points Furik and Rubik can earn on the relay race. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class CodeG
{
static class Scanner
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String nextLine()
{
try
{
return br.readLine();
}
catch(Exception e)
{
throw(new RuntimeException());
}
}
public String next()
{
while(!st.hasMoreTokens())
{
String l = nextLine();
if(l == null)
return null;
st = new StringTokenizer(l);
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
public double nextDouble()
{
return Double.parseDouble(next());
}
public int[] nextIntArray(int n)
{
int[] res = new int[n];
for(int i = 0; i < res.length; i++)
res[i] = nextInt();
return res;
}
public long[] nextLongArray(int n)
{
long[] res = new long[n];
for(int i = 0; i < res.length; i++)
res[i] = nextLong();
return res;
}
public double[] nextDoubleArray(int n)
{
double[] res = new double[n];
for(int i = 0; i < res.length; i++)
res[i] = nextLong();
return res;
}
public void sortIntArray(int[] array)
{
Integer[] vals = new Integer[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public void sortLongArray(long[] array)
{
Long[] vals = new Long[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public void sortDoubleArray(double[] array)
{
Double[] vals = new Double[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public String[] nextStringArray(int n)
{
String[] vals = new String[n];
for(int i = 0; i < n; i++)
vals[i] = next();
return vals;
}
Integer nextInteger()
{
String s = next();
if(s == null)
return null;
return Integer.parseInt(s);
}
int[][] nextIntMatrix(int n, int m)
{
int[][] ans = new int[n][];
for(int i = 0; i < n; i++)
ans[i] = nextIntArray(m);
return ans;
}
}
static int n;
static int n2;
static int[][] vals;
static int[] dp;
static int darIndice(int turno, int columnaA, int columnaB)
{
return turno * n2 + columnaA * n + columnaB;
}
static int dp(int columnaA, int columnaB, int turno)
{
if(dp[darIndice(turno, columnaA, columnaB)] != Integer.MIN_VALUE)
return dp[darIndice(turno, columnaA, columnaB)];
int filaA = turno - columnaA;
int filaB = turno - columnaB;
int costoEste = columnaA == columnaB ? vals[filaA][columnaA] : vals[filaA][columnaA] + vals[filaB][columnaB];
Integer best = null;
if(filaA + 1 < n && filaB + 1 < n)
{
int pos = costoEste + dp(columnaA, columnaB, turno + 1);
if(best == null || pos > best)
best = pos;
}
if(filaA + 1 < n && columnaB + 1 < n)
{
int pos = costoEste + dp(columnaA, columnaB + 1, turno + 1);
if(best == null || pos > best)
best = pos;
}
if(columnaA + 1 < n && filaB + 1 < n)
{
int pos = costoEste + dp(columnaA + 1, columnaB, turno + 1);
if(best == null || pos > best)
best = pos;
}
if(columnaA + 1 < n && columnaB + 1 < n)
{
int pos = costoEste + dp(columnaA + 1, columnaB + 1, turno + 1);
if(best == null || pos > best)
best = pos;
}
return dp[darIndice(turno, columnaA, columnaB)] = best == null ? costoEste : best;
}
public static void main(String[] args)
{
Scanner sc = new Scanner();
n = sc.nextInt();
n2 = n * n;
vals = sc.nextIntMatrix(n, n);
dp = new int[2 * n * n * n];
Arrays.fill(dp, Integer.MIN_VALUE);
System.out.println(dp(0, 0, 0));
}
}
| Java | ["1\n5", "2\n11 14\n16 12", "3\n25 16 25\n12 18 19\n11 13 8"] | 4 seconds | ["5", "53", "136"] | NoteComments to the second sample: The profitable path for Furik is: (1, 1), (1, 2), (2, 2), and for Rubik: (2, 2), (2, 1), (1, 1). Comments to the third sample: The optimal path for Furik is: (1, 1), (1, 2), (1, 3), (2, 3), (3, 3), and for Rubik: (3, 3), (3, 2), (2, 2), (2, 1), (1, 1). The figure to the sample: Furik's path is marked with yellow, and Rubik's path is marked with pink. | Java 7 | standard input | [
"dp"
] | 45ccda0657d2b02540b1fc33745820b8 | The first line contains a single integer (1 ≤ n ≤ 300). The next n lines contain n integers each: the j-th number on the i-th line ai, j ( - 1000 ≤ ai, j ≤ 1000) is the number written in the cell with coordinates (i, j). | 2,000 | On a single line print a single number — the answer to the problem. | standard output | |
PASSED | 248612b68e3e2046954aaafc2609a3f7 | train_003.jsonl | 1423931400 | There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location. | 256 megabytes |
import java.util.Arrays;
import java.util.Scanner;
public class B {
public static void main(String[] args) {
Scanner inputt = new Scanner(System.in);
int num = inputt.nextInt();
int a = inputt.nextInt();
int b = inputt.nextInt();
double[] angles = new double[num];
for (int i = 0; i < num; i++) {
int x = inputt.nextInt();
int y = inputt.nextInt();
angles[i] = getMeTheA(a, b, x, y);
}
Arrays.sort(angles);
int count = 1;
double curr = angles[0];
for (int i = 1; i < num; i++) {
//System.out.println(angles[i] + " " + curr);
if (Math.abs(angles[i] - curr) < 1e-15) continue;
//if (angles[i] == curr) continue;
count++;
curr = angles[i];
}
System.out.println(count);
}
private static double getMeTheA(int a, int b, int x, int y) {
if (x == a) return 1e9;
return 1.*(y-b)/(x-a);
}
}
| Java | ["4 0 0\n1 1\n2 2\n2 0\n-1 -1", "2 1 2\n1 1\n1 0"] | 1 second | ["2", "1"] | NoteExplanation to the first and second samples from the statement, respectively: | Java 7 | standard input | [
"geometry",
"math",
"implementation",
"data structures",
"brute force"
] | 8d2845c33645ac45d4d37f9493b0c380 | The first line contains three integers n, x0 и y0 (1 ≤ n ≤ 1000, - 104 ≤ x0, y0 ≤ 104) — the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point. | 1,400 | Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers. | standard output | |
PASSED | 4246a25b5bb6b310f882474975558ad6 | train_003.jsonl | 1423931400 | There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location. | 256 megabytes |
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author hitarthk
*/
public class c_291_b {
public static void main(String[] args) {
FasterScanner in=new FasterScanner();
int n=in.nextInt();
int x=in.nextInt();
int y=in.nextInt();
HashSet<Node> h=new HashSet<>();
int[][] a=new int[n][2];
for(int i=0;i<n;i++){
a[i][0]=in.nextInt()-x;
a[i][1]=in.nextInt()-y;
}
for(int i=0;i<n;i++){
if(a[i][0]!=0 && a[i][1]!=0){
Node cr=new Node(a[i][0],a[i][1]);
if(!h.contains(cr)){
h.add(cr);
}
}
}
int ans=0;
for(int i=0;i<n;i++){
if(a[i][0]==0){
ans++;
break;
}
}
for(int i=0;i<n;i++){
if(a[i][1]==0){
ans++;
break;
}
}
//System.out.println(h);
ans+=h.size();
System.out.println(ans);
}
static int gcd(int a, int b) {
if(a<0){
a=-a;
}
if(b<0){
b=-b;
}
if (a < b) {
int temp = a;
a = b;
b = temp;
}
while (b > 0) {
int temp = a % b;
a = b;
b = temp;
}
return a;
}
static class Node {
int x;
int y;
public Node(int x,int y){
this.x=x;
this.y=y;
}
public String toString(){
return String.format("%d %d", x,y);
}
public boolean equals(Object o){
Node n=(Node)o;
return n.x*this.y==n.y*this.x;
}
public int hashCode(){
int x=this.x/gcd(this.x,y)+this.y/(gcd(this.x,y));
return x<0?-x:x;
}
}
static class FasterScanner {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = System.in.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String 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;
}
}
}
| Java | ["4 0 0\n1 1\n2 2\n2 0\n-1 -1", "2 1 2\n1 1\n1 0"] | 1 second | ["2", "1"] | NoteExplanation to the first and second samples from the statement, respectively: | Java 7 | standard input | [
"geometry",
"math",
"implementation",
"data structures",
"brute force"
] | 8d2845c33645ac45d4d37f9493b0c380 | The first line contains three integers n, x0 и y0 (1 ≤ n ≤ 1000, - 104 ≤ x0, y0 ≤ 104) — the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point. | 1,400 | Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers. | standard output | |
PASSED | 4144b3dec828b8651b273b895d853d61 | train_003.jsonl | 1423931400 | There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException{
ContestScanner in = new ContestScanner();
int n = in.nextInt();
int x0 = in.nextInt();
int y0 = in.nextInt();
// int[] p = new int[1000];
// p[0] = 2;
// int len = 0;
// for(int i=3; i<1000; i++){
// boolean isp = true;
// for(int j=0; j<=len; j++){
// if(i % p[j] == 0){
// isp = false;
// }
// }
// if(isp){
// len++;
// p[len] = i;
// }
// }
HashSet<Integer> set = new HashSet<Integer>();
for(int i=0; i<n; i++){
int x = in.nextInt()-x0;
int y = in.nextInt()-y0;
boolean fg = (x*y)>0;
// attention!!!! x==0||y==0
x = Math.abs(x);
y = Math.abs(y);
int gcd = gcd(x, y);
x /= gcd;
y /= gcd;
set.add((fg?1:0)|(x<<14)|(y<<1));
// if(x==0){
//
// }else if(y==0){
//
// }else for(int j=0; j<=len; j++){
// if(x )
// }
}
System.out.println(set.size());
}
static int gcd(int a, int b){
return b == 0 ? a : gcd(b, a % b);
}
}
class MyComp implements Comparator<int[]>{
public int compare(int[] a, int[] b) {
return a[0] - b[0];
}
}
class Reverse implements Comparator<Integer>{
public int compare(Integer arg0, Integer arg1) {
return arg1 - arg0;
}
}
class Node{
int id;
List<Node> edge = new ArrayList<Node>();
public Node(int id){
this.id = id;
}
public void createEdge(Node node){
edge.add(node);
}
}
class ContestScanner{
private BufferedReader reader;
private String[] line;
private int idx;
public ContestScanner() throws FileNotFoundException{
reader = new BufferedReader(new InputStreamReader(System.in));
}
public ContestScanner(String filename) throws FileNotFoundException{
reader = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
}
public String nextToken() throws IOException{
if(line == null || line.length <= idx){
line = reader.readLine().trim().split(" ");
idx = 0;
}
return line[idx++];
}
public long nextLong() throws IOException, NumberFormatException{
return Long.parseLong(nextToken());
}
public int nextInt() throws NumberFormatException, IOException{
return (int)nextLong();
}
public double nextDouble() throws NumberFormatException, IOException{
return Double.parseDouble(nextToken());
}
} | Java | ["4 0 0\n1 1\n2 2\n2 0\n-1 -1", "2 1 2\n1 1\n1 0"] | 1 second | ["2", "1"] | NoteExplanation to the first and second samples from the statement, respectively: | Java 7 | standard input | [
"geometry",
"math",
"implementation",
"data structures",
"brute force"
] | 8d2845c33645ac45d4d37f9493b0c380 | The first line contains three integers n, x0 и y0 (1 ≤ n ≤ 1000, - 104 ≤ x0, y0 ≤ 104) — the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point. | 1,400 | Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers. | standard output | |
PASSED | 3b44535fc573052aa448e361e42524c6 | train_003.jsonl | 1423931400 | There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location. | 256 megabytes | import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
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);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
boolean bool=false;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int x = in.nextInt();
int y = in.nextInt();
boolean[] vis = new boolean[n];
int res=0;
pair[] op = new pair[n];
for(int i = 0; i < n; i++){
op[i] = new pair(in.nextInt(),in.nextInt());
}
int ma=0,mb=0;
for(int i = 0; i < n; i++){
if(!vis[i])
res++;
for(int j = i+1; j < n; j++){
ma = (op[i].second-y)*(op[j].first-x);
mb = (op[j].second-y)*(op[i].first-x);
if(ma == mb)
vis[j]=true;
}
}
out.println(res);
}
}
class pair{
int first;
int second;
public pair(){}
public pair(int a,int b){
this.first = a;
this.second = b;
}
public static void main(String...args){
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public Long nextLong() {
return Long.parseLong(next());
}
public Double nextDouble() {
return Double.parseDouble(next());
}
public float nextFloat() {
return Float.parseFloat(next());
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public int[] nextIntegerArray(int n) {
int[] a = new int[n];
for(int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nextLongArray(int n) {
long[] a = new long[n];
for(int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
} | Java | ["4 0 0\n1 1\n2 2\n2 0\n-1 -1", "2 1 2\n1 1\n1 0"] | 1 second | ["2", "1"] | NoteExplanation to the first and second samples from the statement, respectively: | Java 7 | standard input | [
"geometry",
"math",
"implementation",
"data structures",
"brute force"
] | 8d2845c33645ac45d4d37f9493b0c380 | The first line contains three integers n, x0 и y0 (1 ≤ n ≤ 1000, - 104 ≤ x0, y0 ≤ 104) — the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point. | 1,400 | Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers. | standard output | |
PASSED | 88ac566873cd9a336dbecdbde33ff00a | train_003.jsonl | 1423931400 | There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location. | 256 megabytes | import java.util.*;
public class Laser {
static HashMap<Double, Integer> key = new HashMap<Double, Integer>();
static int res = 0;
static boolean inf = false;
static boolean zer = false;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a = sc.nextInt();
int b = sc.nextInt();
for (int i = 0; i < n; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
calculateM(a, b, x, y);
}
System.out.println(res);
}
public static void calculateM(int a, int b, int x, int y) {
if (x == a) { //vertical line case
if (!inf) { //has not shoot
res++;
inf = true;
}
} else if (y == b) { //horizontal line case
if (!zer) {
res++;
zer = true;
}
} else {
double m = (double)(y-b) / (double) (x-a);
if (!key.containsKey(m)) {
res++;
key.put(m, 1);
}
}
}
} | Java | ["4 0 0\n1 1\n2 2\n2 0\n-1 -1", "2 1 2\n1 1\n1 0"] | 1 second | ["2", "1"] | NoteExplanation to the first and second samples from the statement, respectively: | Java 7 | standard input | [
"geometry",
"math",
"implementation",
"data structures",
"brute force"
] | 8d2845c33645ac45d4d37f9493b0c380 | The first line contains three integers n, x0 и y0 (1 ≤ n ≤ 1000, - 104 ≤ x0, y0 ≤ 104) — the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point. | 1,400 | Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers. | standard output | |
PASSED | 5b09d102c72adcc59d5695039d3c816c | train_003.jsonl | 1423931400 | There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.StringTokenizer;
public class TB {
public static void main(String[] args) {
FastScanner in=new FastScanner();
int i,n,x0,y0,x,y;
double k;
n=in.nextInt();
x0=in.nextInt();
y0=in.nextInt();
HashSet<Double> set=new HashSet<Double>();
for(i=0;i<n;i++){
x=in.nextInt();
y=in.nextInt();
if(y==y0){
k=Double.MAX_VALUE;
}else if(x==x0){
k=Double.MIN_VALUE;
}else{
k=(x-x0)*1.0/(y-y0);
}
set.add(k);
}
System.out.println(set.size());
}
static class FastScanner{
BufferedReader br;
StringTokenizer st;
public FastScanner(){br=new BufferedReader(new InputStreamReader(System.in));}
String nextToken(){
while(st==null||!st.hasMoreElements())
try{st=new StringTokenizer(br.readLine());}catch(Exception e){}
return st.nextToken();
}
int nextInt(){return Integer.parseInt(nextToken());}
long nextLong(){return Long.parseLong(nextToken());}
double nextDouble(){return Double.parseDouble(nextToken());}
}
}
| Java | ["4 0 0\n1 1\n2 2\n2 0\n-1 -1", "2 1 2\n1 1\n1 0"] | 1 second | ["2", "1"] | NoteExplanation to the first and second samples from the statement, respectively: | Java 7 | standard input | [
"geometry",
"math",
"implementation",
"data structures",
"brute force"
] | 8d2845c33645ac45d4d37f9493b0c380 | The first line contains three integers n, x0 и y0 (1 ≤ n ≤ 1000, - 104 ≤ x0, y0 ≤ 104) — the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point. | 1,400 | Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers. | standard output | |
PASSED | 8015264acd3f81e0b02b152ff028e202 | train_003.jsonl | 1423931400 | There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.StringTokenizer;
public class Main {
public static void main(String args[]) throws NumberFormatException,
IOException {
Stdin in = new Stdin();
PrintWriter out = new PrintWriter(System.out);
int n = in.readInt();
int x0 = in.readInt();
int y0 = in.readInt();
HashMap<Integer, HashMap<Integer, Integer>> map = new HashMap<Integer, HashMap<Integer, Integer>>();
HashMap<Integer, Integer> t;
int x, y;
int a, b, gcd;
int cnt = 0, cnt_b = 0,cnt_a=0;
for (int i = 0; i < n; i++) {
x = in.readInt();
y = in.readInt();
a = y - y0;
b = x - x0;
if (b != 0 && a != 0) {
gcd = gcd(a, b);
a /= gcd;
b /= gcd;
if (b < 0) {
a *= -1;
b *= -1;
}
}
if (a == 0 || b == 0){
if(a==0&&b==0)
cnt=1;
else{
if(a==0)
cnt_a=1;
else
cnt_b=1;
}
}
else {
if (map.containsKey(a)) {
if (!map.get(a).containsKey(b)) {
map.get(a).put(b, 1);
}
} else {
t = new HashMap<Integer, Integer>();
t.put(b, 1);
map.put(a, t);
}
}
}
int count = 0;
for (HashMap<Integer, Integer> m : map.values())
count += m.size();
if (cnt_b > 0)
count++;
if(cnt_a>0)
count++;
if (count == 0 && cnt > 0)
count++;
out.println(count);
out.flush();
out.close();
}
private static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static class Stdin {
InputStreamReader read;
BufferedReader br;
StringTokenizer st = new StringTokenizer("");
private Stdin() {
read = new InputStreamReader(System.in);
br = new BufferedReader(read);
}
private String readNext() throws IOException {
while (!st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
private int readInt() throws IOException, NumberFormatException {
return Integer.parseInt(readNext());
}
private long readLong() throws IOException, NumberFormatException {
return Long.parseLong(readNext());
}
}
}
| Java | ["4 0 0\n1 1\n2 2\n2 0\n-1 -1", "2 1 2\n1 1\n1 0"] | 1 second | ["2", "1"] | NoteExplanation to the first and second samples from the statement, respectively: | Java 7 | standard input | [
"geometry",
"math",
"implementation",
"data structures",
"brute force"
] | 8d2845c33645ac45d4d37f9493b0c380 | The first line contains three integers n, x0 и y0 (1 ≤ n ≤ 1000, - 104 ≤ x0, y0 ≤ 104) — the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point. | 1,400 | Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers. | standard output | |
PASSED | 6c083eaa5094e62d522edc7baf82b7cc | train_003.jsonl | 1423931400 | There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class MainB {
MyScanner sc = new MyScanner();
Scanner sc2 = new Scanner(System.in);
final int MOD = 1000000007;
int[] dx = { 1, 0, 0, -1 };
int[] dy = { 0, 1, -1, 0 };
void run() {
int n = sc.nextInt();
long[][] target = new long[n][2];
long nx = sc.nextLong();
long ny = sc.nextLong();
for (int i = 0; i < n; i++) {
target[i][0] = sc.nextLong();
target[i][1] = sc.nextLong();
}
boolean[] death = new boolean[n];
int cnt = 0;
for (int i = 0; i < n; i++) {
if (!death[i]) {
death[i] = true;
cnt++;
long x = target[i][0];
long y = target[i][1];
if (ny - y == 0) {
for (int j = 0; j < n; j++) {
if (target[j][1] == ny) {
death[j] = true;
}
}
} else if (nx - x == 0) {
for (int j = 0; j < n; j++) {
if (target[j][0] == nx) {
death[j] = true;
}
}
} else {
long xx = nx - x;
long yy = ny - y;
for (int j = 0; j < n; j++) {
if (xx * target[j][1] == yy * target[j][0]
+ (ny * xx - yy * nx)) {
death[j] = true;
}
}
}
}
}
System.out.println(cnt);
}
public static void main(String[] args) {
new MainB().run();
}
void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
void debug2(int[][] array) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j]);
}
System.out.println();
}
}
boolean inner(int h, int w, int limH, int limW) {
return 0 <= h && h < limH && 0 <= w && w < limW;
}
void swap(int[] x, int a, int b) {
int tmp = x[a];
x[a] = x[b];
x[b] = tmp;
}
// find minimum i (a[i] >= border)
int lower_bound(int a[], int border) {
int l = -1;
int r = a.length;
while (r - l > 1) {
int mid = (l + r) / 2;
if (border <= a[mid]) {
r = mid;
} else {
l = mid;
}
}
// r = l + 1
return r;
}
boolean palindrome(String s) {
for (int i = 0; i < s.length() / 2; i++) {
if (s.charAt(i) != s.charAt(s.length() - 1 - i)) {
return false;
}
}
return true;
}
class MyScanner {
int nextInt() {
try {
int c = System.in.read();
while (c != '-' && (c < '0' || '9' < c))
c = System.in.read();
if (c == '-')
return -nextInt();
int res = 0;
do {
res *= 10;
res += c - '0';
c = System.in.read();
} while ('0' <= c && c <= '9');
return res;
} catch (Exception e) {
return -1;
}
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
String next() {
try {
StringBuilder res = new StringBuilder("");
int c = System.in.read();
while (Character.isWhitespace(c))
c = System.in.read();
do {
res.append((char) c);
} while (!Character.isWhitespace(c = System.in.read()));
return res.toString();
} catch (Exception e) {
return null;
}
}
int[] nextIntArray(int n) {
int[] in = new int[n];
for (int i = 0; i < n; i++) {
in[i] = nextInt();
}
return in;
}
int[][] nextInt2dArray(int n, int m) {
int[][] in = new int[n][m];
for (int i = 0; i < n; i++) {
in[i] = nextIntArray(m);
}
return in;
}
double[] nextDoubleArray(int n) {
double[] in = new double[n];
for (int i = 0; i < n; i++) {
in[i] = nextDouble();
}
return in;
}
long[] nextLongArray(int n) {
long[] in = new long[n];
for (int i = 0; i < n; i++) {
in[i] = nextLong();
}
return in;
}
char[][] nextCharField(int n, int m) {
char[][] in = new char[n][m];
for (int i = 0; i < n; i++) {
String s = sc.next();
for (int j = 0; j < m; j++) {
in[i][j] = s.charAt(j);
}
}
return in;
}
}
}
| Java | ["4 0 0\n1 1\n2 2\n2 0\n-1 -1", "2 1 2\n1 1\n1 0"] | 1 second | ["2", "1"] | NoteExplanation to the first and second samples from the statement, respectively: | Java 7 | standard input | [
"geometry",
"math",
"implementation",
"data structures",
"brute force"
] | 8d2845c33645ac45d4d37f9493b0c380 | The first line contains three integers n, x0 и y0 (1 ≤ n ≤ 1000, - 104 ≤ x0, y0 ≤ 104) — the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point. | 1,400 | Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers. | standard output | |
PASSED | d86581ecab711c50d32c2ccf15ab5c05 | train_003.jsonl | 1423931400 | There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location. | 256 megabytes | import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
public class MainB {
MyScanner sc = new MyScanner();
Scanner sc2 = new Scanner(System.in);
final int MOD = 1000000007;
int[] dx = { 1, 0, 0, -1 };
int[] dy = { 0, 1, -1, 0 };
void run() {
int n = sc.nextInt();
int x0 = sc.nextInt();
int y0 = sc.nextInt();
HashSet<String> set = new HashSet<String>();
for (int i = 0; i < n; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
if (y - y0 == 0) {
set.add("00_00");
} else if (x - x0 == 0) {
set.add("11_11");
} else {
int g = gcd(x - x0, y - y0);
set.add((x - x0) / g + "_" + (y - y0) / g);
}
}
System.out.println(set.size());
}
int gcd(int a, int b) {
return a % b == 0 ? b : gcd(b, a % b);
}
public static void main(String[] args) {
new MainB().run();
}
void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
void debug2(int[][] array) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j]);
}
System.out.println();
}
}
boolean inner(int h, int w, int limH, int limW) {
return 0 <= h && h < limH && 0 <= w && w < limW;
}
void swap(int[] x, int a, int b) {
int tmp = x[a];
x[a] = x[b];
x[b] = tmp;
}
// find minimum i (a[i] >= border)
int lower_bound(int a[], int border) {
int l = -1;
int r = a.length;
while (r - l > 1) {
int mid = (l + r) / 2;
if (border <= a[mid]) {
r = mid;
} else {
l = mid;
}
}
// r = l + 1
return r;
}
boolean palindrome(String s) {
for (int i = 0; i < s.length() / 2; i++) {
if (s.charAt(i) != s.charAt(s.length() - 1 - i)) {
return false;
}
}
return true;
}
class MyScanner {
int nextInt() {
try {
int c = System.in.read();
while (c != '-' && (c < '0' || '9' < c))
c = System.in.read();
if (c == '-')
return -nextInt();
int res = 0;
do {
res *= 10;
res += c - '0';
c = System.in.read();
} while ('0' <= c && c <= '9');
return res;
} catch (Exception e) {
return -1;
}
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
String next() {
try {
StringBuilder res = new StringBuilder("");
int c = System.in.read();
while (Character.isWhitespace(c))
c = System.in.read();
do {
res.append((char) c);
} while (!Character.isWhitespace(c = System.in.read()));
return res.toString();
} catch (Exception e) {
return null;
}
}
int[] nextIntArray(int n) {
int[] in = new int[n];
for (int i = 0; i < n; i++) {
in[i] = nextInt();
}
return in;
}
int[][] nextInt2dArray(int n, int m) {
int[][] in = new int[n][m];
for (int i = 0; i < n; i++) {
in[i] = nextIntArray(m);
}
return in;
}
double[] nextDoubleArray(int n) {
double[] in = new double[n];
for (int i = 0; i < n; i++) {
in[i] = nextDouble();
}
return in;
}
long[] nextLongArray(int n) {
long[] in = new long[n];
for (int i = 0; i < n; i++) {
in[i] = nextLong();
}
return in;
}
char[][] nextCharField(int n, int m) {
char[][] in = new char[n][m];
for (int i = 0; i < n; i++) {
String s = sc.next();
for (int j = 0; j < m; j++) {
in[i][j] = s.charAt(j);
}
}
return in;
}
}
}
| Java | ["4 0 0\n1 1\n2 2\n2 0\n-1 -1", "2 1 2\n1 1\n1 0"] | 1 second | ["2", "1"] | NoteExplanation to the first and second samples from the statement, respectively: | Java 7 | standard input | [
"geometry",
"math",
"implementation",
"data structures",
"brute force"
] | 8d2845c33645ac45d4d37f9493b0c380 | The first line contains three integers n, x0 и y0 (1 ≤ n ≤ 1000, - 104 ≤ x0, y0 ≤ 104) — the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point. | 1,400 | Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers. | standard output | |
PASSED | 2b67670336335a5069ddb47834a0a854 | train_003.jsonl | 1423931400 | There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location. | 256 megabytes | import static java.lang.System.in;
import static java.lang.System.out;
import java.io.*;
import java.util.*;
public class B514 {
/*
* You can generate hash object with string by concatenating integers.
* ToDO hashcode of 3 integers.
*/
static final double EPS = 1e-10;
static final double INF = 1 << 31;
static final double PI = Math.PI;
public static Scanner sc = new Scanner(in);
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
long lcd (long x, long y){
if (x<y) return lcd(y, x);
if (y==0) return x;
else return lcd(y, x%y);
}
class line{
long A, B, C;
line(long a, long b, long c){
A=a; B=b; C=c;
}
public boolean equals(line xy) {
if (xy.A==A && xy.B==B && xy.C==C) return true;
return false;
}
}
public void run() throws IOException {
String input;
String[] inputArray;
input = br.readLine();
inputArray = input.split(" ");
int n = Integer.valueOf(inputArray[0]);
int x0 = Integer.valueOf(inputArray[1]);
int y0 = Integer.valueOf(inputArray[2]);
HashSet <Long> set = new HashSet<Long>();
long base = 10000;
for (int i=0; i<n; i++){
input = br.readLine();
inputArray = input.split(" ");
int x = Integer.valueOf(inputArray[0]);
int y = Integer.valueOf(inputArray[1]);
long A = y-y0;
long B = x0-x;
long C = x*y0 - x0*y;
long d = lcd(lcd(Math.abs(A), Math.abs(B)), Math.abs(C));
if (A<0) d=-d;
A/=d;
B/=d;
C/=d;
if (A==0 && B<0) {
B=-B; C=-C;
}
set.add(A*base*base*base*3 + B*base*base*3+ C);
// set.add(A+"" +B +"" +C);
}
sb.append(set.size());
ln(sb);
}
public static void main(String[] args) throws IOException {
new B514().run();
}
public static void ln(Object obj) {
out.println(obj);
}
}
| Java | ["4 0 0\n1 1\n2 2\n2 0\n-1 -1", "2 1 2\n1 1\n1 0"] | 1 second | ["2", "1"] | NoteExplanation to the first and second samples from the statement, respectively: | Java 7 | standard input | [
"geometry",
"math",
"implementation",
"data structures",
"brute force"
] | 8d2845c33645ac45d4d37f9493b0c380 | The first line contains three integers n, x0 и y0 (1 ≤ n ≤ 1000, - 104 ≤ x0, y0 ≤ 104) — the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point. | 1,400 | Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers. | standard output | |
PASSED | 63d79bffafa0f9e7eafdec6ba467a4cf | train_003.jsonl | 1423931400 | There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location. | 256 megabytes | import static java.lang.System.in;
import static java.lang.System.out;
import java.io.*;
import java.util.*;
public class B514 {
static final double EPS = 1e-10;
static final double INF = 1 << 31;
static final double PI = Math.PI;
public static Scanner sc = new Scanner(in);
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
long lcd (long x, long y){
if (x<y) return lcd(y, x);
if (y==0) return x;
else return lcd(y, x%y);
}
class line{
long A, B, C;
line(long a, long b, long c){
A=a; B=b; C=c;
}
public boolean equals(line xy) {
if (xy.A==A && xy.B==B && xy.C==C) return true;
return false;
}
}
public void run() throws IOException {
String input;
String[] inputArray;
input = br.readLine();
inputArray = input.split(" ");
int n = Integer.valueOf(inputArray[0]);
int x0 = Integer.valueOf(inputArray[1]);
int y0 = Integer.valueOf(inputArray[2]);
HashSet <String> set = new HashSet<String>();
// long base = 20000;
for (int i=0; i<n; i++){
input = br.readLine();
inputArray = input.split(" ");
int x = Integer.valueOf(inputArray[0]);
int y = Integer.valueOf(inputArray[1]);
long A = y-y0;
long B = x0-x;
long C = x*y0 - x0*y;
long d = lcd(lcd(Math.abs(A), Math.abs(B)), Math.abs(C));
if (A<0) d=-d;
A/=d;
B/=d;
C/=d;
if (A==0 && B<0) {
B=-B; C=-C;
}
set.add(A+"" +B +"" +C);
}
sb.append(set.size());
ln(sb);
}
public static void main(String[] args) throws IOException {
new B514().run();
}
public static void ln(Object obj) {
out.println(obj);
}
}
| Java | ["4 0 0\n1 1\n2 2\n2 0\n-1 -1", "2 1 2\n1 1\n1 0"] | 1 second | ["2", "1"] | NoteExplanation to the first and second samples from the statement, respectively: | Java 7 | standard input | [
"geometry",
"math",
"implementation",
"data structures",
"brute force"
] | 8d2845c33645ac45d4d37f9493b0c380 | The first line contains three integers n, x0 и y0 (1 ≤ n ≤ 1000, - 104 ≤ x0, y0 ≤ 104) — the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point. | 1,400 | Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers. | standard output | |
PASSED | fd74301fe01c2c03b6b8307e23468565 | train_003.jsonl | 1423931400 | There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location. | 256 megabytes | import java.util.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] in = br.readLine().split(" ");
int n = Integer.parseInt(in[0]);
double x0 = Double.parseDouble(in[1]);
double y0 = Double.parseDouble(in[2]);
double x ;
double y ;
Set<Double> slopes = new HashSet<>();
int cnt1 = 0;
int cnt2 = 0;
for(int i = 0; i < n; i++)
{
in = br.readLine().split(" ");
x = Integer.parseInt(in[0]);
y = Integer.parseInt(in[1]);
if(x == x0)
cnt1 = 1;
else if(y == y0)
cnt2 = 1;
else
slopes.add((y - y0)/(x - x0));
}
System.out.println(slopes.size() + cnt1 + cnt2);
}
} | Java | ["4 0 0\n1 1\n2 2\n2 0\n-1 -1", "2 1 2\n1 1\n1 0"] | 1 second | ["2", "1"] | NoteExplanation to the first and second samples from the statement, respectively: | Java 7 | standard input | [
"geometry",
"math",
"implementation",
"data structures",
"brute force"
] | 8d2845c33645ac45d4d37f9493b0c380 | The first line contains three integers n, x0 и y0 (1 ≤ n ≤ 1000, - 104 ≤ x0, y0 ≤ 104) — the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point. | 1,400 | Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers. | standard output | |
PASSED | 14ea1059a9e968f5685705bee223b372 | train_003.jsonl | 1423931400 | There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location. | 256 megabytes | import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
public class Solution{
///////////////////////////////////////////////////////////////////////////
static class FastScanner{
BufferedReader s;
StringTokenizer st;
public FastScanner(InputStream InputStream){
st = new StringTokenizer("");
s = new BufferedReader(new InputStreamReader(InputStream));
}
public FastScanner(File f) throws FileNotFoundException{
st = new StringTokenizer("");
s = new BufferedReader (new FileReader(f));
}
public int nextInt() throws IOException{
if(st.hasMoreTokens())
return Integer.parseInt(st.nextToken());
else{
st = new StringTokenizer(s.readLine());
return nextInt();
}
}
public BigInteger big() throws IOException{
if(st.hasMoreTokens())
return new BigInteger(st.nextToken());
else{
st = new StringTokenizer(s.readLine());
return big();
}
}
public double nextDouble() throws IOException{
if(st.hasMoreTokens())
return Double.parseDouble(st.nextToken());
else{
st = new StringTokenizer(s.readLine());
return nextDouble();
}
}
public long nextLong() throws IOException{
if(st.hasMoreTokens())
return Long.parseLong(st.nextToken());
else{
st = new StringTokenizer(s.readLine());
return nextLong();
}
}
public String nextString() throws IOException{
if(st.hasMoreTokens())
return st.nextToken();
else{
st = new StringTokenizer(s.readLine());
return nextString();
}
}
public String readLine() throws IOException{
return s.readLine();
}
public void close() throws IOException{
s.close();
}
}
////////////////////////////////////////////////////////////////////
// Number Theory
long pow(long a,long b,long mod){
long x = 1; long y = a;
while(b > 0){
if(b % 2 == 1){
x = (x*y);
x %= mod;
}
y = (y*y);
y %= mod;
b /= 2;
}
return x;
}
int divisor(long x,long[] a){
long limit = x;
int numberOfDivisors = 0;
for (int i=1; i < limit; ++i) {
if (x % i == 0) {
limit = x / i;
if (limit != i) {
numberOfDivisors++;
}
numberOfDivisors++;
}
}
return numberOfDivisors;
}
void findSubsets(int array[]){
long numOfSubsets = 1 << array.length;
for(int i = 0; i < numOfSubsets; i++){
@SuppressWarnings("unused")
int pos = array.length - 1;
int bitmask = i;
while(bitmask > 0){
if((bitmask & 1) == 1)
// ww.print(array[pos]+" ");
bitmask >>= 1;
pos--;
}
// ww.println();
}
}
public static long gcd(long a, long b){
return b == 0 ? a : gcd(b,a%b);
}
public static int lcm(int a,int b, int c){
return lcm(lcm(a,b),c);
}
public static int lcm(int a, int b){
return (int) (a*b/gcd(a,b));
}
public static long invl(long a, long mod) {
long b = mod;
long p = 1, q = 0;
while (b > 0) {
long c = a / b;
long d;
d = a;
a = b;
b = d % b;
d = p;
p = q;
q = d - c * q;
}
return p < 0 ? p + mod : p;
}
////////////////////////////////////////////////////////////////////
// FastScanner s = new FastScanner(new File("input.txt"));
// PrintWriter ww = new PrintWriter(new FileWriter("output.txt"));
static InputStream inputStream = System.in;
static FastScanner s = new FastScanner(inputStream);
static OutputStream outputStream = System.out;
static PrintWriter ww = new PrintWriter(new OutputStreamWriter(outputStream));
// private static Scanner s = new Scanner(System.in);
@SuppressWarnings("unused")
private static int[][] states = { {-1,0} , {1,0} , {0,-1} , {0,1} };
////////////////////////////////////////////////////////////////////
public static void main(String[] args) throws IOException{
new Solution().solve();
s.close();
ww.close();
}
////////////////////////////////////////////////////////////////////
void solve() throws IOException{
int n = s.nextInt();
int x = s.nextInt();
int y = s.nextInt();
Set<Double> st = new HashSet<Double>();
for(int i=0;i<n;i++){
double a = s.nextInt();
double b = s.nextInt();
if(b-y == 0) st.add(9090.9090);
else if(a-x == 0) st.add(6767.6767);
else st.add((b-y)/(a-x));
}
ww.println(st.size());
}
}
| Java | ["4 0 0\n1 1\n2 2\n2 0\n-1 -1", "2 1 2\n1 1\n1 0"] | 1 second | ["2", "1"] | NoteExplanation to the first and second samples from the statement, respectively: | Java 7 | standard input | [
"geometry",
"math",
"implementation",
"data structures",
"brute force"
] | 8d2845c33645ac45d4d37f9493b0c380 | The first line contains three integers n, x0 и y0 (1 ≤ n ≤ 1000, - 104 ≤ x0, y0 ≤ 104) — the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point. | 1,400 | Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers. | standard output | |
PASSED | ee36acf28a2eb743f683a17f6b37f601 | train_003.jsonl | 1423931400 | There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location. | 256 megabytes | 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;
//package C291Div2;
public class B {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(in, out);
out.close();
}
}
class TaskA {
public void solve(InputReader in, PrintWriter out) {
int n = in.nextInt();
int a = in.nextInt();
int b = in.nextInt();
int[] x = new int[n];
int[] y = new int[n];
double[] sl = new double[n];
for(int i = 0; i < n; i++) {
x[i] = in.nextInt();
y[i] = in.nextInt();
}
for(int i = 0; i < n; i++) {
if(x[i] ==a && y[i] == b)
sl[i] = Integer.MAX_VALUE;
else if(x[i] == a)
sl[i] = Integer.MIN_VALUE;
else
sl[i] = ((double)(y[i] - b))/((double)(x[i]-a));
}
sort(sl);
int count = 1;
for(int i=1; i < n; i++) {
if(sl[i] == Integer.MAX_VALUE) {
out.println(count);
return;
}
if(sl[i] != sl[i-1])
count++;
}
out.println(count);
}
private static void sort(double[] a) {
double[] b = new double[a.length];
sort(a, b, 0, a.length - 1);
}
private static void sort(double[] a, double[] b, int begin, int end) {
if (begin == end) {
return;
}
int mid = (begin + end) / 2;
sort(a, b, begin, mid);
sort(a, b, mid + 1, end);
merge(a, b, begin, end);
}
private static void merge(double[] a, double[] b, int begin, int end) {
int mid = (begin + end) / 2;
int i = begin;
int j = mid + 1;
int k = begin;
while (i <= mid && j <= end) {
if (a[i] > a[j]) {
b[k] = a[j];
j++;
} else {
b[k] = a[i];
i++;
}
k++;
}
if (j <= end) {
while (j <= end) {
b[k] = a[j];
k++;
j++;
}
}
if (i <= mid) {
while (i <= mid) {
b[k] = a[i];
i++;
k++;
}
}
i = begin;
while (i <= end) {
a[i] = b[i];
i++;
}
}
}
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());
}
}
| Java | ["4 0 0\n1 1\n2 2\n2 0\n-1 -1", "2 1 2\n1 1\n1 0"] | 1 second | ["2", "1"] | NoteExplanation to the first and second samples from the statement, respectively: | Java 7 | standard input | [
"geometry",
"math",
"implementation",
"data structures",
"brute force"
] | 8d2845c33645ac45d4d37f9493b0c380 | The first line contains three integers n, x0 и y0 (1 ≤ n ≤ 1000, - 104 ≤ x0, y0 ≤ 104) — the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point. | 1,400 | Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers. | standard output | |
PASSED | 4b0b5684bf110190ea973ce4839616aa | train_003.jsonl | 1423931400 | There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location. | 256 megabytes | import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Locale;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) throws Exception {
//int T = StdIn.readInt();
solve(1);
}
public static void solve(int testCases) throws Exception{
int n = StdIn.readInt();
int hanX = StdIn.readInt();
int hanY = StdIn.readInt();
ST<Double,Integer> st = new ST<Double,Integer>();
for(int i = 1 ; i <= n ; i++){
int x = StdIn.readInt();
int y = StdIn.readInt();
int dy = hanY - y;
int dx = hanX - x;
double slope = 0.0;
if(dx == 0){
slope = Double.MIN_VALUE;
}else if(dy == 0){
slope = 0.0;
}else{
slope = (dy/(double)dx);
}
st.put(slope, 1);
}
/*for(double d : st){
StdOut.println(d);
}*/
StdOut.println(st.size());
}
}
class ST<Key extends Comparable<Key>, Value> implements Iterable<Key> {
private TreeMap<Key, Value> st;
public ST() {
st = new TreeMap<Key, Value>();
}
public Value get(Key key) {
if (key == null) throw new NullPointerException("called get() with null key");
return st.get(key);
}
public void put(Key key, Value val) {
if (key == null) throw new NullPointerException("called put() with null key");
if (val == null) st.remove(key);
else st.put(key, val);
}
public void delete(Key key) {
if (key == null) throw new NullPointerException("called delete() with null key");
st.remove(key);
}
public boolean contains(Key key) {
if (key == null) throw new NullPointerException("called contains() with null key");
return st.containsKey(key);
}
public int size() {
return st.size();
}
public boolean isEmpty() {
return size() == 0;
}
public Iterable<Key> keys() {
return st.keySet();
}
public Iterator<Key> iterator() {
return st.keySet().iterator();
}
public Key min() {
if (isEmpty()) throw new NoSuchElementException("called min() with empty symbol table");
return st.firstKey();
}
public Key max() {
if (isEmpty()) throw new NoSuchElementException("called max() with empty symbol table");
return st.lastKey();
}
public Key ceiling(Key key) {
if (key == null) throw new NullPointerException("called ceiling() with null key");
Key k = st.ceilingKey(key);
if (k == null) throw new NoSuchElementException("all keys are less than " + key);
return k;
}
public Key floor(Key key) {
if (key == null) throw new NullPointerException("called floor() with null key");
Key k = st.floorKey(key);
if (k == null) throw new NoSuchElementException("all keys are greater than " + key);
return k;
}
}
final class StdIn {
private StdIn() { }
private static Scanner scanner;
private static final String CHARSET_NAME = "UTF-8";
private static final Locale LOCALE = Locale.US;
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\p{javaWhitespace}+");
private static final Pattern EMPTY_PATTERN = Pattern.compile("");
private static final Pattern EVERYTHING_PATTERN = Pattern.compile("\\A");
public static boolean isEmpty() {
return !scanner.hasNext();
}
public static boolean hasNextLine() {
return scanner.hasNextLine();
}
public static boolean hasNextChar() {
scanner.useDelimiter(EMPTY_PATTERN);
boolean result = scanner.hasNext();
scanner.useDelimiter(WHITESPACE_PATTERN);
return result;
}
public static String readLine() {
String line;
try { line = scanner.nextLine(); }
catch (Exception e) { line = null; }
return line;
}
public static char readChar() {
scanner.useDelimiter(EMPTY_PATTERN);
String ch = scanner.next();
assert (ch.length() == 1) : "Internal (Std)In.readChar() error!"
+ " Please contact the authors.";
scanner.useDelimiter(WHITESPACE_PATTERN);
return ch.charAt(0);
}
public static String readAll() {
if (!scanner.hasNextLine())
return "";
String result = scanner.useDelimiter(EVERYTHING_PATTERN).next();
// not that important to reset delimeter, since now scanner is empty
scanner.useDelimiter(WHITESPACE_PATTERN); // but let's do it anyway
return result;
}
public static String readString() {
return scanner.next();
}
public static int readInt() {
return scanner.nextInt();
}
public static double readDouble() {
return scanner.nextDouble();
}
public static float readFloat() {
return scanner.nextFloat();
}
public static long readLong() {
return scanner.nextLong();
}
public static short readShort() {
return scanner.nextShort();
}
public static byte readByte() {
return scanner.nextByte();
}
public static boolean readBoolean() {
String s = readString();
if (s.equalsIgnoreCase("true")) return true;
if (s.equalsIgnoreCase("false")) return false;
if (s.equals("1")) return true;
if (s.equals("0")) return false;
throw new InputMismatchException();
}
public static String[] readAllStrings() {
// we could use readAll.trim().split(), but that's not consistent
// because trim() uses characters 0x00..0x20 as whitespace
String[] tokens = WHITESPACE_PATTERN.split(readAll());
if (tokens.length == 0 || tokens[0].length() > 0)
return tokens;
// don't include first token if it is leading whitespace
String[] decapitokens = new String[tokens.length-1];
for (int i = 0; i < tokens.length - 1; i++)
decapitokens[i] = tokens[i+1];
return decapitokens;
}
public static String[] readAllLines() {
ArrayList<String> lines = new ArrayList<String>();
while (hasNextLine()) {
lines.add(readLine());
}
return lines.toArray(new String[0]);
}
public static int[] readAllInts() {
String[] fields = readAllStrings();
int[] vals = new int[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Integer.parseInt(fields[i]);
return vals;
}
public static double[] readAllDoubles() {
String[] fields = readAllStrings();
double[] vals = new double[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Double.parseDouble(fields[i]);
return vals;
}
static {
resync();
}
private static void resync() {
setScanner(new Scanner(new java.io.BufferedInputStream(System.in), CHARSET_NAME));
}
private static void setScanner(Scanner scanner) {
StdIn.scanner = scanner;
StdIn.scanner.useLocale(LOCALE);
}
public static int[] readInts() {
return readAllInts();
}
public static double[] readDoubles() {
return readAllDoubles();
}
public static String[] readStrings() {
return readAllStrings();
}
}
final class StdOut {
private static final String CHARSET_NAME = "UTF-8";
private static final Locale LOCALE = Locale.US;
private static PrintWriter out;
static {
try {
out = new PrintWriter(new OutputStreamWriter(System.out, CHARSET_NAME), true);
}
catch (UnsupportedEncodingException e) { System.out.println(e); }
}
private StdOut() { }
public static void close() {
out.close();
}
public static void println() {
out.println();
}
public static void println(Object x) {
out.println(x);
}
public static void println(boolean x) {
out.println(x);
}
public static void println(char x) {
out.println(x);
}
public static void println(double x) {
out.println(x);
}
public static void println(float x) {
out.println(x);
}
public static void println(int x) {
out.println(x);
}
public static void println(long x) {
out.println(x);
}
public static void println(short x) {
out.println(x);
}
public static void println(byte x) {
out.println(x);
}
public static void print() {
out.flush();
}
public static void print(Object x) {
out.print(x);
out.flush();
}
public static void print(boolean x) {
out.print(x);
out.flush();
}
public static void print(char x) {
out.print(x);
out.flush();
}
public static void print(double x) {
out.print(x);
out.flush();
}
public static void print(float x) {
out.print(x);
out.flush();
}
public static void print(int x) {
out.print(x);
out.flush();
}
public static void print(long x) {
out.print(x);
out.flush();
}
public static void print(short x) {
out.print(x);
out.flush();
}
public static void print(byte x) {
out.print(x);
out.flush();
}
public static void printf(String format, Object... args) {
out.printf(LOCALE, format, args);
out.flush();
}
public static void printf(Locale locale, String format, Object... args) {
out.printf(locale, format, args);
out.flush();
}
} | Java | ["4 0 0\n1 1\n2 2\n2 0\n-1 -1", "2 1 2\n1 1\n1 0"] | 1 second | ["2", "1"] | NoteExplanation to the first and second samples from the statement, respectively: | Java 7 | standard input | [
"geometry",
"math",
"implementation",
"data structures",
"brute force"
] | 8d2845c33645ac45d4d37f9493b0c380 | The first line contains three integers n, x0 и y0 (1 ≤ n ≤ 1000, - 104 ≤ x0, y0 ≤ 104) — the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point. | 1,400 | Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers. | standard output | |
PASSED | d4736553654ddb5bf61c6e35c76d27b4 | train_003.jsonl | 1423931400 | There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location. | 256 megabytes | import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
import java.util.TreeSet;
public class CF_291_Q2 {
public static int mod=(int)1e9+7;
public static void main(String[] args)
{
FasterScanner s=new FasterScanner();
PrintWriter out=new PrintWriter(System.out);
int n=s.nextInt();
int x0=s.nextInt();
int y0=s.nextInt();
int[] x=new int[n];
int[] y=new int[n];
for(int i=0;i<n;i++)
{
x[i]=s.nextInt()-x0;
y[i]=s.nextInt()-y0;
}
boolean[] b=new boolean[n];
int ans=0;
for(int i=0;i<n;i++)
{
if(b[i])
continue;
ans++;
for(int j=i;j<n;j++)
{
if(y[j]*x[i]==y[i]*x[j])
b[j]=true;
}
}
System.out.println(ans);
out.close();
}
public static int pow(int x, int n, int mod) {
int res = 1;
for (long p = x; n > 0; n >>= 1, p = (p * p) % mod) {
if ((n & 1) != 0) {
res = (int) (res * p % mod);
}
}
return res;
}
public static class FasterScanner {
private byte[] buf = new byte[1024];
private int tmp_curChar;
private int tmp_numChars;
public int read() {
if (tmp_numChars == -1)
throw new InputMismatchException();
if (tmp_curChar >= tmp_numChars) {
tmp_curChar = 0;
try {
tmp_numChars = System.in.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (tmp_numChars <= 0)
return -1;
}
return buf[tmp_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;
}
}
} | Java | ["4 0 0\n1 1\n2 2\n2 0\n-1 -1", "2 1 2\n1 1\n1 0"] | 1 second | ["2", "1"] | NoteExplanation to the first and second samples from the statement, respectively: | Java 7 | standard input | [
"geometry",
"math",
"implementation",
"data structures",
"brute force"
] | 8d2845c33645ac45d4d37f9493b0c380 | The first line contains three integers n, x0 и y0 (1 ≤ n ≤ 1000, - 104 ≤ x0, y0 ≤ 104) — the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point. | 1,400 | Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers. | standard output | |
PASSED | ddafd2f33a05c4d07cf6013a58021b40 | train_003.jsonl | 1423931400 | There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location. | 256 megabytes |
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int x0= sc.nextInt();
int y0=sc.nextInt();
int x=0,y=0;
Set<Double> slopeSet = new HashSet<>();
Double slope;
for(int i=0;i<n;i++){
x=sc.nextInt();
y=sc.nextInt();
slope= (double) (y-y0)/(x-x0);
if(slope==Double.NEGATIVE_INFINITY )
slopeSet.add(Double.POSITIVE_INFINITY);
else if(slope==-0.0)
slopeSet.add(0.0);
else slopeSet.add(slope);
}
System.out.println(slopeSet.size());
}
} | Java | ["4 0 0\n1 1\n2 2\n2 0\n-1 -1", "2 1 2\n1 1\n1 0"] | 1 second | ["2", "1"] | NoteExplanation to the first and second samples from the statement, respectively: | Java 7 | standard input | [
"geometry",
"math",
"implementation",
"data structures",
"brute force"
] | 8d2845c33645ac45d4d37f9493b0c380 | The first line contains three integers n, x0 и y0 (1 ≤ n ≤ 1000, - 104 ≤ x0, y0 ≤ 104) — the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point. | 1,400 | Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers. | standard output | |
PASSED | c77d4af0ab58e4aac282f449d621d8ee | train_003.jsonl | 1423931400 | There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location. | 256 megabytes | import java.util.HashSet;
import java.util.Scanner;
public class Main {
private static double x,y;
private static Double k=0d,c=0d;
private static boolean vertical=false,lastWasVertical=false;
public static void main(String[] args) {
Scanner S=new Scanner(System.in);
Integer n=S.nextInt();
x=S.nextInt();
y=S.nextInt();
HashSet KC=new HashSet<String>(n);
int rez=0;
for (int a=0;a<n;a++) {
count(S.nextInt(),S.nextInt());
if (!lastWasVertical) {
KC.add(k.toString()+c.toString());
}
lastWasVertical=false;
}
rez=KC.size();
if (vertical) rez++;
System.out.println(rez);
}
static void count(double xx,double yy){
if (xx==x) {
vertical=true;
lastWasVertical=true;
return;
}
k= (yy - y) / (xx - x);
if (yy==y) k=0d;
c=y-k*x;
}
} | Java | ["4 0 0\n1 1\n2 2\n2 0\n-1 -1", "2 1 2\n1 1\n1 0"] | 1 second | ["2", "1"] | NoteExplanation to the first and second samples from the statement, respectively: | Java 7 | standard input | [
"geometry",
"math",
"implementation",
"data structures",
"brute force"
] | 8d2845c33645ac45d4d37f9493b0c380 | The first line contains three integers n, x0 и y0 (1 ≤ n ≤ 1000, - 104 ≤ x0, y0 ≤ 104) — the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point. | 1,400 | Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers. | standard output | |
PASSED | 261113a12de0816a562175148d49a837 | train_003.jsonl | 1423931400 | There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location. | 256 megabytes | import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n =in.nextInt();
int x= in.nextInt();
int y=in.nextInt();
Set<Double> set = new HashSet<Double>();
int vertical=0;
int horizontal = 0;
for(int i =0; i<n; i++){
int x1= in.nextInt();
int y1= in.nextInt();
int yd= y-y1;
int xd= x-x1;
if(xd==0){
vertical=1;
}
else if(yd==0){
horizontal=1;
}
else {
set.add((double)yd/xd);
}
}
System.out.println(set.size()+vertical+horizontal);
}
} | Java | ["4 0 0\n1 1\n2 2\n2 0\n-1 -1", "2 1 2\n1 1\n1 0"] | 1 second | ["2", "1"] | NoteExplanation to the first and second samples from the statement, respectively: | Java 7 | standard input | [
"geometry",
"math",
"implementation",
"data structures",
"brute force"
] | 8d2845c33645ac45d4d37f9493b0c380 | The first line contains three integers n, x0 и y0 (1 ≤ n ≤ 1000, - 104 ≤ x0, y0 ≤ 104) — the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point. | 1,400 | Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers. | standard output | |
PASSED | 88e850682eb3c97fb91413491fae3d65 | train_003.jsonl | 1423931400 | There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException{
FastScanner in = new FastScanner();
int n = in.nextInt();
Tuple<Long, Long> pooshka = new Tuple<Long, Long>(in.nextLong(), in.nextLong());
ArrayList<Tuple<Long, Long>> shs = new ArrayList<Tuple<Long, Long>>();
for (int i = 0; i < n; ++i)
shs.add(new Tuple<Long, Long>(in.nextLong(), in.nextLong()));
boolean[] used = new boolean[n];
int ans = 0;
for (int i = 0; i < n; ++i){
if (!used[i]){
for (int j = i; j < n; ++j)
if (isLine(pooshka, shs.get(i), shs.get(j)))
used[j] = true;
ans++;
}
}
System.out.println(ans);
}
private static boolean isLine(Tuple<Long, Long> a, Tuple<Long, Long> b, Tuple<Long, Long> c){
long x1 = a.first;
long x2 = b.first;
long x3 = c.first;
long y1 = a.second;
long y2 = b.second;
long y3 = c.second;
return (x2 - x1) * (y3 - y1) == (x3 - x1) * (y2 - y1);
}
private static class Tuple<A, B>{
A first;
B second;
public Tuple(A a, B b){
first = a;
second = b;
}
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastScanner(FileInputStream fis){
br = new BufferedReader(new InputStreamReader(fis));
}
String next(){
while (st == null || !st.hasMoreTokens()){
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
int read() throws IOException{
return br.read();
}
}
} | Java | ["4 0 0\n1 1\n2 2\n2 0\n-1 -1", "2 1 2\n1 1\n1 0"] | 1 second | ["2", "1"] | NoteExplanation to the first and second samples from the statement, respectively: | Java 7 | standard input | [
"geometry",
"math",
"implementation",
"data structures",
"brute force"
] | 8d2845c33645ac45d4d37f9493b0c380 | The first line contains three integers n, x0 и y0 (1 ≤ n ≤ 1000, - 104 ≤ x0, y0 ≤ 104) — the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point. | 1,400 | Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers. | standard output | |
PASSED | 4d0748050d8cff7eb7326c31a21e1e52 | train_003.jsonl | 1423931400 | There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
public class ProblemB {
BufferedReader rd;
private ProblemB() throws IOException {
rd = new BufferedReader(new InputStreamReader(System.in));
compute();
}
private void compute() throws IOException {
int[] a = intarr();
int n = a[0];
double x0 = a[1];
double y0 = a[2];
int horiz = 0;
int vert = 0;
Set<Long> elements = new HashSet<>();
for(int i=0;i<n;i++) {
a = intarr();
int x = a[0];
int y = a[1];
if(x == x0) {
vert = 1;
} else if(y == y0) {
horiz = 1;
} else {
elements.add(Math.round((x-x0)/(y-y0)*10000000000.0));
}
}
out(elements.size() + horiz + vert);
}
private int[] intarr() throws IOException {
return intarr(rd.readLine());
}
private int[] intarr(String s) {
String[] q = split(s);
int n = q.length;
int[] a = new int[n];
for(int i=0;i<n;i++) {
a[i] = Integer.parseInt(q[i]);
}
return a;
}
private String[] split(String s) {
int n = s.length();
int sp = 0;
for(int i=0;i<n;i++) {
if(s.charAt(i)==' ') {
sp++;
}
}
String[] res = new String[sp+1];
int last = 0;
int x = 0;
for(int i=0;i<n;i++) {
char c = s.charAt(i);
if(c == ' ') {
res[x++] = s.substring(last,i);
last = i+1;
}
}
res[x] = s.substring(last,n);
return res;
}
private static void out(Object x) {
System.out.println(x);
}
public static void main(String[] args) throws IOException {
new ProblemB();
}
}
| Java | ["4 0 0\n1 1\n2 2\n2 0\n-1 -1", "2 1 2\n1 1\n1 0"] | 1 second | ["2", "1"] | NoteExplanation to the first and second samples from the statement, respectively: | Java 7 | standard input | [
"geometry",
"math",
"implementation",
"data structures",
"brute force"
] | 8d2845c33645ac45d4d37f9493b0c380 | The first line contains three integers n, x0 и y0 (1 ≤ n ≤ 1000, - 104 ≤ x0, y0 ≤ 104) — the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point. | 1,400 | Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers. | standard output | |
PASSED | 3b304230d438d603055def258a2c2ed1 | train_003.jsonl | 1520696100 | Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation π such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds. | 512 megabytes | //package codeforces.R470;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class C
{
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
int[] a = new int[n];
int[] p = new int[n];
for (int i = 0; i < n; i++)
a[i] = sc.nextInt();
for (int i = 0; i < n; i++)
p[i] = sc.nextInt();
Trie t = new Trie();
for (int i = 0; i < p.length; i++)
{
char[] add = get(p[i]).toCharArray();
t.addWord(add, 0);
}
for (int i = 0; i < a.length; i++)
{
int res = t.find(get(a[i]).toCharArray(), 0, 0);
pw.print(res + " ");
}
pw.flush();
pw.close();
}
static String get(int n)
{
StringBuilder sb = new StringBuilder("");
String tmp = Integer.toBinaryString(n);
for (int i = 0; i < 30-tmp.length(); i++)
sb.append("0");
sb.append(tmp);
return sb.toString();
}
static class Trie
{
Trie[] next;
int words;
public Trie()
{
words = 0;
next = new Trie[2];
}
public void addWord(char[] word, int idx)
{
if(idx == word.length)
{
this.words++;
}
else
{
this.words ++;
if(next[word[idx]-'0'] == null)
next[word[idx]-'0'] = new Trie();
next[word[idx]-'0'].addWord(word, idx+1);
}
}
public int find(char[] num, int idx, int res)
{
this.words--;
if(idx == num.length)
return res;
int first = 0;
int second = 1;
if(num[idx] == '1')
{
int tmp = first;
first = second;
second = tmp;
}
// try to get first
if(this.next[first] != null && this.next[first].words > 0)
return this.next[first].find(num, idx+1, res);
// res += (1<< (30-idx-1));
return this.next[second].find(num, idx+1, res + (1<< (30-idx-1)));
}
}
static class Scanner
{
StringTokenizer st; BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException {while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());return st.nextToken();}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public boolean ready() throws IOException {return br.ready();}
}
}
| Java | ["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"] | 3.5 seconds | ["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"] | NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution. | Java 8 | standard input | [
"data structures",
"greedy",
"trees",
"strings"
] | dc778193a126009f545d1d6f307bba83 | The first line contains a single integer N (1 ≤ N ≤ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≤ Ai < 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≤ Pi < 230) representing the permuted encryption key. | 1,800 | Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative. | standard output | |
PASSED | 00b55d2fbcff8f0d0763881d20720755 | train_003.jsonl | 1520696100 | Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation π such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.util.StringTokenizer;
import java.io.Writer;
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 palayutm
*/
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);
ProblemCPerfectSecurity solver = new ProblemCPerfectSecurity();
solver.solve(1, in, out);
out.close();
}
static class ProblemCPerfectSecurity {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int[] a = in.nextIntArray(n);
int[] b = in.nextIntArray(n);
int[][] ch = new int[(n + 1) * 30][2];
int[] cnt = new int[(n + 1) * 30];
int top = 1;
for (int v : b) {
for (int i = 29, now = 0; i >= 0; i--) {
int c = (((1 << i) & v) > 0 ? 1 : 0);
if (ch[now][c] == 0) {
ch[now][c] = top++;
}
now = ch[now][c];
cnt[now]++;
}
}
for (int v : a) {
int z = 0;
for (int i = 29, now = 0; i >= 0; i--) {
int c = (((1 << i) & v) > 0 ? 1 : 0);
if (ch[now][c] > 0 && cnt[ch[now][c]] > 0) {
now = ch[now][c];
} else {
now = ch[now][c ^ 1];
z |= (1 << i);
}
cnt[now]--;
}
out.print(z + " ");
}
}
}
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 int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
}
static class OutputWriter extends PrintWriter {
public OutputWriter(OutputStream out) {
super(out);
}
public OutputWriter(Writer out) {
super(out);
}
public void close() {
super.close();
}
}
}
| Java | ["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"] | 3.5 seconds | ["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"] | NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution. | Java 8 | standard input | [
"data structures",
"greedy",
"trees",
"strings"
] | dc778193a126009f545d1d6f307bba83 | The first line contains a single integer N (1 ≤ N ≤ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≤ Ai < 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≤ Pi < 230) representing the permuted encryption key. | 1,800 | Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative. | standard output | |
PASSED | d0fb5859cb74c998532803864beabbe4 | train_003.jsonl | 1520696100 | Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation π such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds. | 512 megabytes | import java.util.*;
public class C {
public C () {
int N = sc.nextInt();
int [] A = sc.nextInts();
int [] P = sc.nextInts();
TreeMap<Integer, Integer> M = new TreeMap<>();
for (int p : P)
M.put(p, (M.containsKey(p) ? M.get(p) : 0) + 1);
int [] res = new int [N];
for (int i : rep(N)) {
SortedMap<Integer, Integer> L = M;
int first = L.firstKey(), last = L.lastKey();
for (int j : sep(30)) {
int B = first, bit = (1 << j);
if ((B & bit) == 0) {
B |= bit; B &= ~(bit - 1);
if ((A[i] & bit) == 0) {
if (first < B && B <= last) {
L = L.headMap(B);
last = L.lastKey();
}
} else if (B <= last) {
L = L.tailMap(B);
first = L.firstKey();
}
}
}
int z = L.firstKey();
M.put(z, M.get(z) - 1);
if (M.get(z) == 0)
M.remove(z);
res[i] = z ^ A[i];
}
exit(res);
}
private static int [] rep(int N) { return rep(0, N); }
private static int [] rep(int S, int T) { if (T <= S) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; }
private static int [] sep(int N) { return sep(0, N); }
private static int [] sep(int S, int T) { if (T <= S) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[T-1-i] = i; return res; }
////////////////////////////////////////////////////////////////////////////////////
private final static IOUtils.MyScanner sc = new IOUtils.MyScanner();
private static void exit (Object o, Object ... A) { IOUtils.print(o, A); IOUtils.exit(); }
private static class IOUtils {
public static class MyScanner {
public String next() { newLine(); return line[index++]; }
public int nextInt() { return Integer.parseInt(next()); }
public String nextLine() { line = null; return readLine(); }
public String [] nextStrings() { return split(nextLine()); }
public int [] nextInts() {
String [] L = nextStrings();
int [] res = new int [L.length];
for (int i = 0; i < L.length; ++i)
res[i] = Integer.parseInt(L[i]);
return res;
}
//////////////////////////////////////////////
private boolean eol() { return index == line.length; }
private String readLine() {
try {
return r.readLine();
} catch (Exception e) {
throw new Error (e);
}
}
private final java.io.BufferedReader r;
private MyScanner () { this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in))); }
private MyScanner (java.io.BufferedReader r) {
try {
this.r = r;
while (!r.ready())
Thread.sleep(1);
start();
} catch (Exception e) {
throw new Error(e);
}
}
private String [] line;
private int index;
private void newLine() {
if (line == null || eol()) {
line = split(readLine());
index = 0;
}
}
private String [] split(String s) { return s.length() > 0 ? s.split(" ") : new String [0]; }
}
private static String build(Object o, Object ... A) { return buildDelim(" ", o, A); }
private static String buildDelim(String delim, Object o, Object ... A) {
StringBuilder b = new StringBuilder();
append(b, o, delim);
for (Object p : A)
append(b, p, delim);
return b.substring(delim.length());
}
//////////////////////////////////////////////////////////////////////////////////
private static void start() { if (t == 0) t = millis(); }
private static void append(StringBuilder b, Object o, String delim) {
if (o.getClass().isArray()) {
int len = java.lang.reflect.Array.getLength(o);
for (int i = 0; i < len; ++i)
append(b, java.lang.reflect.Array.get(o, i), delim);
} else if (o instanceof Iterable<?>)
for (Object p : (Iterable<?>) o)
append(b, p, delim);
else {
if (o instanceof Double)
o = new java.text.DecimalFormat("#.############").format(o);
b.append(delim).append(o);
}
}
private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out);
private static void print(Object o, Object ... A) { pw.println(build(o, A)); }
private static void err(Object o, Object ... A) { System.err.println(build(o, A)); }
private static void exit() {
IOUtils.pw.close();
System.out.flush();
err("------------------");
err(IOUtils.time());
System.exit(0);
}
private static long t;
private static long millis() { return System.currentTimeMillis(); }
private static String time() { return "Time: " + (millis() - t) / 1000.0; }
}
public static void main (String[] args) { new C(); IOUtils.exit(); }
}
| Java | ["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"] | 3.5 seconds | ["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"] | NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution. | Java 8 | standard input | [
"data structures",
"greedy",
"trees",
"strings"
] | dc778193a126009f545d1d6f307bba83 | The first line contains a single integer N (1 ≤ N ≤ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≤ Ai < 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≤ Pi < 230) representing the permuted encryption key. | 1,800 | Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative. | standard output | |
PASSED | 02847a92a34d7e9d53cc6f4445a3f638 | train_003.jsonl | 1520696100 | Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation π such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds. | 512 megabytes | import java.util.*;
public class C {
public C () {
int N = sc.nextInt();
int [] A = sc.nextInts();
int [] P = sc.nextInts();
Counter<Integer> M = new Counter<>();
for (int p : P)
M.inc(p);
int [] res = new int [N];
for (int i : rep(N)) {
int from = M.firstKey(), to = M.lastKey();
for (int j : sep(30)) {
int B = from, bit = (1 << j);
if ((B & bit) == 0) {
B |= bit; B &= ~(bit - 1);
if ((A[i] & bit) == 0) {
if (from < B && B <= to)
to = M.lowerKey(B);
} else if (B <= to)
from = M.ceilingKey(B);
}
}
assert from == to;
M.dec(from);
res[i] = from ^ A[i];
}
exit(res);
}
private static int [] rep(int N) { return rep(0, N); }
private static int [] rep(int S, int T) { if (T <= S) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; }
private static int [] sep(int N) { return sep(0, N); }
private static int [] sep(int S, int T) { if (T <= S) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[T-1-i] = i; return res; }
private interface AbstractCounter<K> extends Map<K, Long> {
default boolean safeContainsKey(Object key) { if (!isEmpty()) keySet().iterator().next().getClass().cast(key); return containsKey(key); }
default void dec (K key) { dec(key, 1); }
default void dec (K key, long value) { inc(key, -value); }
default void inc (K key) { inc(key, 1); }
default void inc (K key, long value) { put(key, get(key) + value); }
}
private static class Counter<K> extends TreeMap<K, Long> implements AbstractCounter<K> {
private static final long serialVersionUID = 1L;
public Long get (Object key) { return safeContainsKey(key) ? super.get(key) : 0L; }
public Long put (K key, Long value) {
long res = get(key);
if (value != 0)
super.put(key, value);
else
remove(key);
return res;
}
}
////////////////////////////////////////////////////////////////////////////////////
private final static IOUtils.MyScanner sc = new IOUtils.MyScanner();
private static void exit (Object o, Object ... A) { IOUtils.print(o, A); IOUtils.exit(); }
private static class IOUtils {
public static class MyScanner {
public String next() { newLine(); return line[index++]; }
public int nextInt() { return Integer.parseInt(next()); }
public String nextLine() { line = null; return readLine(); }
public String [] nextStrings() { return split(nextLine()); }
public int [] nextInts() {
String [] L = nextStrings();
int [] res = new int [L.length];
for (int i = 0; i < L.length; ++i)
res[i] = Integer.parseInt(L[i]);
return res;
}
//////////////////////////////////////////////
private boolean eol() { return index == line.length; }
private String readLine() {
try {
return r.readLine();
} catch (Exception e) {
throw new Error (e);
}
}
private final java.io.BufferedReader r;
private MyScanner () { this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in))); }
private MyScanner (java.io.BufferedReader r) {
try {
this.r = r;
while (!r.ready())
Thread.sleep(1);
start();
} catch (Exception e) {
throw new Error(e);
}
}
private String [] line;
private int index;
private void newLine() {
if (line == null || eol()) {
line = split(readLine());
index = 0;
}
}
private String [] split(String s) { return s.length() > 0 ? s.split(" ") : new String [0]; }
}
private static String build(Object o, Object ... A) { return buildDelim(" ", o, A); }
private static String buildDelim(String delim, Object o, Object ... A) {
StringBuilder b = new StringBuilder();
append(b, o, delim);
for (Object p : A)
append(b, p, delim);
return b.substring(delim.length());
}
//////////////////////////////////////////////////////////////////////////////////
private static void start() { if (t == 0) t = millis(); }
private static void append(StringBuilder b, Object o, String delim) {
if (o.getClass().isArray()) {
int len = java.lang.reflect.Array.getLength(o);
for (int i = 0; i < len; ++i)
append(b, java.lang.reflect.Array.get(o, i), delim);
} else if (o instanceof Iterable<?>)
for (Object p : (Iterable<?>) o)
append(b, p, delim);
else {
if (o instanceof Double)
o = new java.text.DecimalFormat("#.############").format(o);
b.append(delim).append(o);
}
}
private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out);
private static void print(Object o, Object ... A) { pw.println(build(o, A)); }
private static void err(Object o, Object ... A) { System.err.println(build(o, A)); }
private static void exit() {
IOUtils.pw.close();
System.out.flush();
err("------------------");
err(IOUtils.time());
System.exit(0);
}
private static long t;
private static long millis() { return System.currentTimeMillis(); }
private static String time() { return "Time: " + (millis() - t) / 1000.0; }
}
public static void main (String[] args) { new C(); IOUtils.exit(); }
}
| Java | ["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"] | 3.5 seconds | ["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"] | NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution. | Java 8 | standard input | [
"data structures",
"greedy",
"trees",
"strings"
] | dc778193a126009f545d1d6f307bba83 | The first line contains a single integer N (1 ≤ N ≤ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≤ Ai < 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≤ Pi < 230) representing the permuted encryption key. | 1,800 | Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative. | standard output | |
PASSED | f2892e070be2e936f294f4e270ad1a3e | train_003.jsonl | 1520696100 | Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation π such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
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(in, out);
out.close();
}
static class TaskC {
static long MOD = 1_000_000_007;
class Trie {
private class TrieEnd extends Trie {
long value = 0;
public TrieEnd() {
super(0);
}
@Override
public void addValue(long l) {
value = l;
count++;
}
@Override
public long removeBest(long l) {
count--;
return value;
}
}
long bitChecker = 1 << 30;
private int checkBit(long l) {
return (bitChecker & l) == 0 ? 0 : 1;
}
Trie[] children = new Trie[2];
int count = 0;
Trie(long[] list) {
for (long l : list) addValue(l);
}
private Trie(long bitChecker) {
this.bitChecker = bitChecker;
}
public void addValue(long l) {
count++;
int k = checkBit(l);
if (children[k] == null) {
if ((bitChecker >> 1) != 0) {
children[k] = new Trie(bitChecker >> 1);
} else {
children[k] = new TrieEnd();
}
}
children[k].addValue(l);
}
long removeBest(long l) {
count--;
int k = checkBit(l);
if (children[k] == null) k ^= 1;
long res = children[k].removeBest(l);
if (children[k].count == 0) {
children[k] = null;
}
return res;
}
}
void Solve(InputReader in, PrintWriter out) {
int n = in.NextInt();
long[] A = in.NextLongArray(n);
Trie P = new Trie(in.NextLongArray(n));
for (int i = 0; i < n; i++) {
out.print((A[i] ^ P.removeBest(A[i])) + " ");
}
out.println();
}
}
private static int GetMax(int[] ar) {
int max = Integer.MIN_VALUE;
for (int a : ar) {
max = Math.max(max, a);
}
return max;
}
public static int GetMin(int[] ar) {
int min = Integer.MAX_VALUE;
for (int a : ar) {
min = Math.min(min, a);
}
return min;
}
public static long GetSum(int[] ar) {
long s = 0;
for (int a : ar) s += a;
return s;
}
public static int[] GetCount(int[] ar) {
return GetCount(ar, GetMax(ar));
}
public static int[] GetCount(int[] ar, int maxValue) {
int[] dp = new int[maxValue + 1];
for (int a : ar) {
dp[a]++;
}
return dp;
}
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(), " \t\n\r\f,");
} 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 int[] NextIntArray(int n) {
return NextIntArray(n, 0);
}
public int[] NextIntArray(int n, int offset) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = NextInt() - offset;
}
return a;
}
public int[][] NextIntMatrix(int n, int m) {
return NextIntMatrix(n, m, 0);
}
public int[][] NextIntMatrix(int n, int m, int offset) {
int[][] a = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = NextInt() - offset;
}
}
return a;
}
public long[] NextLongArray(int n) {
return NextLongArray(n, 0);
}
public long[] NextLongArray(int n, int offset) {
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = NextLong() - offset;
}
return a;
}
public long[][] NextLongMatrix(int n, int m) {
return NextLongMatrix(n, m, 0);
}
public long[][] NextLongMatrix(int n, int m, int offset) {
long[][] a = new long[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = NextLong() - offset;
}
}
return a;
}
}
} | Java | ["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"] | 3.5 seconds | ["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"] | NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution. | Java 8 | standard input | [
"data structures",
"greedy",
"trees",
"strings"
] | dc778193a126009f545d1d6f307bba83 | The first line contains a single integer N (1 ≤ N ≤ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≤ Ai < 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≤ Pi < 230) representing the permuted encryption key. | 1,800 | Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative. | standard output | |
PASSED | c52d312c75d243bd7d4e8d17a0cccc40 | train_003.jsonl | 1520696100 | Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation π such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
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(in, out);
out.close();
}
static class TaskC {
static long MOD = 1_000_000_007;
class Trie {
long bitChecker = 1 << 30;
Trie child1, child0;
int count = 0;
Queue<Long> values;
public Trie(long[] list) {
for (long l : list) addValue(l);
}
public Trie(long bitChecker) {
this.bitChecker = bitChecker;
if (bitChecker == 0) {
values = new LinkedList<>();
}
}
public void addValue(long l) {
count++;
if (bitChecker == 0) {
values.add(l);
} else {
if ((l & bitChecker) == 0) {
if (child0 == null) child0 = new Trie(bitChecker >> 1);
child0.addValue(l);
} else {
if (child1 == null) child1 = new Trie(bitChecker >> 1);
child1.addValue(l);
}
}
}
long removeBest(long l) {
count--;
if (bitChecker == 0) {
return values.poll();
} else {
if (child0 == null) {
long res = child1.removeBest(l);
if (child1.count == 0) {
child1 = null;
}
return res;
} else if (child1 == null) {
long res = child0.removeBest(l);
if (child0.count == 0) {
child0 = null;
}
return res;
} else {
if ((l & bitChecker) == 0) {
long res = child0.removeBest(l);
if (child0.count == 0) {
child0 = null;
}
return res;
} else {
long res = child1.removeBest(l);
if (child1.count == 0) {
child1 = null;
}
return res;
}
}
}
}
}
void Solve(InputReader in, PrintWriter out) {
int n = in.NextInt();
long[] A = in.NextLongArray(n);
Trie P = new Trie(in.NextLongArray(n));
for (int i = 0; i < n; i++) {
out.print((A[i] ^ P.removeBest(A[i])) + " ");
}
out.println();
}
}
public static int GetMax(int[] ar) {
int max = Integer.MIN_VALUE;
for (int a : ar) {
max = Math.max(max, a);
}
return max;
}
public static int GetMin(int[] ar) {
int min = Integer.MAX_VALUE;
for (int a : ar) {
min = Math.min(min, a);
}
return min;
}
public static long GetSum(int[] ar) {
long s = 0;
for (int a : ar) s += a;
return s;
}
public static int[] GetCount(int[] ar) {
return GetCount(ar, GetMax(ar));
}
public static int[] GetCount(int[] ar, int maxValue) {
int[] dp = new int[maxValue + 1];
for (int a : ar) {
dp[a]++;
}
return dp;
}
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(), " \t\n\r\f,");
} 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 int[] NextIntArray(int n) {
return NextIntArray(n, 0);
}
public int[] NextIntArray(int n, int offset) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = NextInt() - offset;
}
return a;
}
public int[][] NextIntMatrix(int n, int m) {
return NextIntMatrix(n, m, 0);
}
public int[][] NextIntMatrix(int n, int m, int offset) {
int[][] a = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = NextInt() - offset;
}
}
return a;
}
public long[] NextLongArray(int n) {
return NextLongArray(n, 0);
}
public long[] NextLongArray(int n, int offset) {
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = NextLong() - offset;
}
return a;
}
public long[][] NextLongMatrix(int n, int m) {
return NextLongMatrix(n, m, 0);
}
public long[][] NextLongMatrix(int n, int m, int offset) {
long[][] a = new long[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = NextLong() - offset;
}
}
return a;
}
}
} | Java | ["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"] | 3.5 seconds | ["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"] | NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution. | Java 8 | standard input | [
"data structures",
"greedy",
"trees",
"strings"
] | dc778193a126009f545d1d6f307bba83 | The first line contains a single integer N (1 ≤ N ≤ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≤ Ai < 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≤ Pi < 230) representing the permuted encryption key. | 1,800 | Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative. | standard output | |
PASSED | 24d950665c1c44c74960daa963e2e620 | train_003.jsonl | 1520696100 | Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation π such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileNotFoundException;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Asgar Javadov
*/
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public static final int BITS = 30;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int[] a = in.readIntArray(n);
int[] p = in.readIntArray(n);
TaskD.TrieNode root = new TaskD.TrieNode();
for (int pi : p)
insert(root, pi);
for (int i = 0; i < a.length; ++i) {
if (i > 0) out.print(' ');
int res = match(root, a[i]);
out.print(res ^ a[i]);
// out.flush();
}
out.println();
}
private int match(TaskD.TrieNode root, int a) {
TaskD.TrieNode node = root;
int ans = 0;
for (int i = BITS - 1; i >= 0; --i) {
int bit = (a >> i) & 1;
if (!node.hasSon(bit))
bit ^= 1;
if (bit == 1)
ans |= (1 << i);
node = node.son[bit];
--node.count;
}
return ans;
}
private void insert(TaskD.TrieNode root, int p) {
TaskD.TrieNode node = root;
for (int i = BITS - 1; i >= 0; --i) {
int bit = (p >> i) & 1;
node.add(bit);
node = node.son[bit];
}
}
static class TrieNode {
TaskD.TrieNode[] son = new TaskD.TrieNode[2];
int count = 0;
public void add(int bit) {
// count++;
if (son[bit] == null) {
son[bit] = new TaskD.TrieNode();
}
son[bit].count++;
}
public boolean hasSon(int bit) {
return (son[bit] != null && son[bit].count > 0);
}
}
}
static class InputReader extends BufferedReader {
StringTokenizer tokenizer;
public InputReader(InputStream inputStream) {
super(new InputStreamReader(inputStream), 32768);
}
public InputReader(String filename) {
super(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(filename)));
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(readLine());
} catch (IOException e) {
throw new RuntimeException();
}
}
return tokenizer.nextToken();
}
public Integer nextInt() {
return Integer.valueOf(next());
}
public int[] readIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = nextInt();
return array;
}
}
static class OutputWriter extends PrintWriter {
public OutputWriter(OutputStream outputStream) {
super(outputStream);
}
public OutputWriter(Writer writer) {
super(writer);
}
public OutputWriter(String filename) throws FileNotFoundException {
super(filename);
}
public void close() {
super.close();
}
}
}
| Java | ["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"] | 3.5 seconds | ["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"] | NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution. | Java 8 | standard input | [
"data structures",
"greedy",
"trees",
"strings"
] | dc778193a126009f545d1d6f307bba83 | The first line contains a single integer N (1 ≤ N ≤ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≤ Ai < 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≤ Pi < 230) representing the permuted encryption key. | 1,800 | Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative. | standard output | |
PASSED | 3c7194750b0520b56b8c56192f4df372 | train_003.jsonl | 1520696100 | Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation π such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileNotFoundException;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Asgar Javadov
*/
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public static final int BITS = 30;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int[] a = in.readIntArray(n);
int[] p = in.readIntArray(n);
lightSolution(a, p, out);
// TrieNode root = new TrieNode();
//
// for (int pi : p)
// insert(root, pi);
//
// for (int i = 0; i < a.length; ++i) {
// if (i > 0) out.print(' ');
// int res = match(root, a[i]);
// out.print(res ^ a[i]);
// }
// out.println();
}
private void lightSolution(int[] a, int[] p, OutputWriter out) {
int[][] trie = new int[a.length * BITS + 1][2];
int[] cnt = new int[trie.length];
int sz = 0;
for (int pi : p) {
int node = 0;
for (int i = BITS - 1; i >= 0; --i) {
int bit = (pi >> i) & 1;
if (trie[node][bit] == 0)
trie[node][bit] = ++sz;
node = trie[node][bit];
cnt[node]++;
}
}
cnt[0] = a.length;
for (int i = 0; i < a.length; ++i) {
int node = 0;
int ans = 0;
for (int j = BITS - 1; j >= 0; --j) {
int bit = (a[i] >> j) & 1;
if (trie[node][bit] != 0 && cnt[trie[node][bit]] > 0) {
} else {
bit ^= 1;
}
if (bit == 1)
ans |= (1 << j);
node = trie[node][bit];
--cnt[node];
}
if (i > 0) out.print(' ');
out.print(ans ^ a[i]);
}
out.println();
}
}
static class OutputWriter extends PrintWriter {
public OutputWriter(OutputStream outputStream) {
super(outputStream);
}
public OutputWriter(Writer writer) {
super(writer);
}
public OutputWriter(String filename) throws FileNotFoundException {
super(filename);
}
public void close() {
super.close();
}
}
static class InputReader extends BufferedReader {
StringTokenizer tokenizer;
public InputReader(InputStream inputStream) {
super(new InputStreamReader(inputStream), 32768);
}
public InputReader(String filename) {
super(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(filename)));
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(readLine());
} catch (IOException e) {
throw new RuntimeException();
}
}
return tokenizer.nextToken();
}
public Integer nextInt() {
return Integer.valueOf(next());
}
public int[] readIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = nextInt();
return array;
}
}
}
| Java | ["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"] | 3.5 seconds | ["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"] | NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution. | Java 8 | standard input | [
"data structures",
"greedy",
"trees",
"strings"
] | dc778193a126009f545d1d6f307bba83 | The first line contains a single integer N (1 ≤ N ≤ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≤ Ai < 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≤ Pi < 230) representing the permuted encryption key. | 1,800 | Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative. | standard output | |
PASSED | ea991e2103fb5aa76cf72031b7a63984 | train_003.jsonl | 1520696100 | Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation π such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileNotFoundException;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Asgar Javadov
*/
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public static final int BITS = 30;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int[] a = in.readIntArray(n);
int[] p = in.readIntArray(n);
lightSolution(a, p, out);
// TrieNode root = new TrieNode();
//
// for (int pi : p)
// insert(root, pi);
//
// for (int i = 0; i < a.length; ++i) {
// if (i > 0) out.print(' ');
// int res = match(root, a[i]);
// out.print(res ^ a[i]);
// }
// out.println();
}
private void lightSolution(int[] a, int[] p, OutputWriter out) {
int[][] trie = new int[Trie.estimateSize(a.length, 2, 30)][2];
int[] cnt = new int[trie.length];
int sz = 0;
for (int pi : p) {
int node = 0;
for (int i = BITS - 1; i >= 0; --i) {
int bit = (pi >> i) & 1;
if (trie[node][bit] == 0)
trie[node][bit] = ++sz;
node = trie[node][bit];
cnt[node]++;
}
}
cnt[0] = a.length;
for (int i = 0; i < a.length; ++i) {
int node = 0;
int ans = 0;
for (int j = BITS - 1; j >= 0; --j) {
int bit = (a[i] >> j) & 1;
if (trie[node][bit] == 0 || cnt[trie[node][bit]] <= 0) {
bit ^= 1;
}
if (bit == 1)
ans |= (1 << j);
node = trie[node][bit];
--cnt[node];
}
if (i > 0) out.print(' ');
out.print(ans ^ a[i]);
}
out.println();
}
}
static class Trie {
static String[] strings = new String[128];
static int numOfNodes = 0;
private Trie.TrieNode root;
static {
strings[0] = "";
for (int i = 1; i < strings.length; i++) {
strings[i] = strings[i - 1] + " ";
}
}
public Trie() {
root = new Trie.TrieNode();
}
public static int estimateSize(int numOfNodes, int branching, int depth) {
int trieSize = depth * numOfNodes + 1;
int temp = branching;
while (temp < numOfNodes) {
trieSize -= (numOfNodes - temp);
temp *= branching;
}
return trieSize;
}
static class TrieNode {
private static final int ALPHABET_SIZE = 26;
protected Trie.TrieNode[] children;
protected boolean isLeaf;
public TrieNode() {
this.children = new Trie.TrieNode[ALPHABET_SIZE];
this.isLeaf = false;
numOfNodes++;
}
}
}
static class OutputWriter extends PrintWriter {
public OutputWriter(OutputStream outputStream) {
super(outputStream);
}
public OutputWriter(Writer writer) {
super(writer);
}
public OutputWriter(String filename) throws FileNotFoundException {
super(filename);
}
public void close() {
super.close();
}
}
static class InputReader extends BufferedReader {
StringTokenizer tokenizer;
public InputReader(InputStream inputStream) {
super(new InputStreamReader(inputStream), 32768);
}
public InputReader(String filename) {
super(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(filename)));
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(readLine());
} catch (IOException e) {
throw new RuntimeException();
}
}
return tokenizer.nextToken();
}
public Integer nextInt() {
return Integer.valueOf(next());
}
public int[] readIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = nextInt();
return array;
}
}
}
| Java | ["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"] | 3.5 seconds | ["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"] | NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution. | Java 8 | standard input | [
"data structures",
"greedy",
"trees",
"strings"
] | dc778193a126009f545d1d6f307bba83 | The first line contains a single integer N (1 ≤ N ≤ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≤ Ai < 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≤ Pi < 230) representing the permuted encryption key. | 1,800 | Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative. | standard output | |
PASSED | dbce915de8cb8f4938752d281e049354 | train_003.jsonl | 1520696100 | Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation π such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds. | 512 megabytes | 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 << 27);
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);
CPerfectSecurity solver = new CPerfectSecurity();
solver.solve(1, in, out);
out.close();
}
}
static class CPerfectSecurity {
static final int HEIGHT = 29;
public void solve(int testNumber, FastInput in, FastOutput out) {
int n = in.readInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.readInt();
}
int[] p = new int[n];
for (int i = 0; i < n; i++) {
p[i] = in.readInt();
}
BNode root = new BNode();
for (int i = 0; i < n; i++) {
root.add(p[i], HEIGHT);
}
for (int i = 0; i < n; i++) {
int ans = root.pop(a[i], 0, HEIGHT);
out.append(ans ^ a[i]).append(' ');
}
}
}
static class BNode {
BNode[] next = new BNode[2];
int size;
public BNode get(int i) {
if (next[i] == null) {
next[i] = new BNode();
}
return next[i];
}
public boolean isEmpty(int i) {
return next[i] == null || next[i].size == 0;
}
public int pop(int x, int trace, int k) {
size--;
if (k < 0) {
return trace;
}
int bit = Bits.bitAt(x, k);
if (!isEmpty(bit)) {
return get(bit).pop(x, Bits.setBit(trace, k, bit == 1), k - 1);
} else {
return get(1 - bit).pop(x, Bits.setBit(trace, k, (1 - bit) == 1), k - 1);
}
}
public void add(int x, int k) {
size++;
if (k < 0) {
return;
}
get(Bits.bitAt(x, k)).add(x, k - 1);
}
}
static class Bits {
private Bits() {
}
public static int bitAt(int x, int i) {
return (x >>> i) & 1;
}
public static int setBit(int x, int i, boolean v) {
if (v) {
x |= 1 << i;
} else {
x &= ~(1 << i);
}
return x;
}
}
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 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();
}
}
static class FastInput {
private final InputStream is;
private byte[] buf = new byte[1 << 20];
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;
}
}
}
| Java | ["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"] | 3.5 seconds | ["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"] | NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution. | Java 8 | standard input | [
"data structures",
"greedy",
"trees",
"strings"
] | dc778193a126009f545d1d6f307bba83 | The first line contains a single integer N (1 ≤ N ≤ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≤ Ai < 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≤ Pi < 230) representing the permuted encryption key. | 1,800 | Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative. | standard output | |
PASSED | ad3e9dcd7f71197cfc857a21bdc6fe18 | train_003.jsonl | 1520696100 | Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation π such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds. | 512 megabytes | import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
public class C {
static BufferedReader br;
static StringTokenizer st;
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 qq = 1;
int qq = Integer.MAX_VALUE;
//int qq = readInt();
for(int casenum = 1; casenum <= qq; casenum++) {
int n = readInt();
int[] orig = new int[n];
for(int i = 0; i < n; i++) {
orig[i] = readInt();
}
root = new Node();
for(int i = 0; i < n; i++) {
addInt(readInt());
}
for(int i = 0; i < n; i++) {
pw.print(orig[i] ^ query(orig[i]));
if(i == n-1) pw.println();
else pw.print(" ");
}
}
pw.close();
}
static Node root;
public static int query(int x) {
Node curr = root;
curr.count--;
int ret = 0;
for(int i = 29; i >= 0; i--) {
int want = 0;
int val = 0;
if((x&(1<<i)) != 0) {
want = 1;
val = 1 << i;
}
if(curr.child[want] != null && curr.child[want].count > 0) {
curr = curr.child[want];
ret |= val;
}
else {
curr = curr.child[1-want];
ret |= (val^(1<<i));
}
curr.count--;
}
return ret;
}
public static void addInt(int x) {
Node curr = root;
curr.count++;
for(int i = 29; i >= 0; i--) {
int want = 0;
if((x&(1<<i)) != 0) {
want = 1;
}
if(curr.child[want] == null) {
curr.child[want] = new Node();
}
curr = curr.child[want];
curr.count++;
}
}
static class Node {
public int count;
public Node[] child;
public Node() {
count = 0;
child = new Node[2];
}
}
public static void exitImmediately() {
pw.close();
System.exit(0);
}
public static int readInt() throws IOException {
return Integer.parseInt(nextToken());
}
public static double readDouble() throws IOException {
return Double.parseDouble(nextToken());
}
public static long readLong() throws IOException {
return Long.parseLong(nextToken());
}
public static String nextLine() throws IOException {
st = null;
if(!br.ready()) {
exitImmediately();
}
return br.readLine();
}
public static String nextToken() throws IOException {
while(st == null || !st.hasMoreTokens()) {
if(!br.ready()) {
exitImmediately();
}
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
}
| Java | ["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"] | 3.5 seconds | ["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"] | NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution. | Java 8 | standard input | [
"data structures",
"greedy",
"trees",
"strings"
] | dc778193a126009f545d1d6f307bba83 | The first line contains a single integer N (1 ≤ N ≤ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≤ Ai < 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≤ Pi < 230) representing the permuted encryption key. | 1,800 | Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative. | standard output | |
PASSED | 5a55f6e1c7430a489b551208e34a35fb | train_003.jsonl | 1520696100 | Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation π such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds. | 512 megabytes | import java.io.*;
import java.util.*;
public class Test {
int readInt() {
int ans = 0;
boolean neg = false;
try {
boolean start = false;
for (int c = 0; (c = System.in.read()) != -1; ) {
if (c == '-') {
start = true;
neg = true;
continue;
} else if (c >= '0' && c <= '9') {
start = true;
ans = ans * 10 + c - '0';
} else if (start) break;
}
} catch (IOException e) {
}
return neg ? -ans : ans;
}
class N {
N ll, rr;
int cnt;
N(N l, N r, int c) {
ll = l;
rr = r;
cnt = c;
}
void add(int n, int d) {
if (d == -1) {
cnt++;
return;
}
if ((n & (1 << d)) == 0) {
if (ll == null) ll = new N(null, null, 0);
ll.add(n, d - 1);
} else {
if (rr == null) rr = new N(null, null, 0);
rr.add(n, d - 1);
}
}
boolean del(int n, int d) {
if (d == -1) {
cnt--;
return cnt == 0;
}
if ((n & (1 << d)) == 0) {
if (ll.del(n, d - 1)) {
ll = null;
return rr == null;
}
} else {
if (rr.del(n, d - 1)) {
rr = null;
return ll == null;
}
}
return false;
}
boolean has(int n, int d, int lsb) {
if (d == lsb - 1) return true;
if ((n & (1 << d)) == 0) {
return ll != null && ll.has(n, d - 1, lsb);
} else {
return rr != null && rr.has(n, d - 1, lsb);
}
}
}
int n;
N pre = new N(null, null, 0);
int[] m;
PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
void start() {
n = readInt();
m = new int[n];
for (int i = 0; i < n; i++) m[i] = readInt();
for (int i = 0; i < n; i++) {
int k = readInt();
pre.add(k, 29);
}
for (int a : m) {
int t = a;
for (int i = 29; i >= 0; i--) {
if (!pre.has(t, 29, i)) t ^= (1<<i);
}
writer.print((t ^ a) + " ");
pre.del(t, 29);
}
writer.flush();
}
public static void main(String[] args) {
new Test().start();
}
}
| Java | ["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"] | 3.5 seconds | ["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"] | NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution. | Java 8 | standard input | [
"data structures",
"greedy",
"trees",
"strings"
] | dc778193a126009f545d1d6f307bba83 | The first line contains a single integer N (1 ≤ N ≤ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≤ Ai < 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≤ Pi < 230) representing the permuted encryption key. | 1,800 | Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative. | standard output | |
PASSED | 2cc6f745d85fba8ce201a09cd3422c4b | train_003.jsonl | 1520696100 | Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation π such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds. | 512 megabytes | import java.io.*;
import java.util.*;
public class Test {
int readInt() {
int ans = 0;
boolean neg = false;
try {
boolean start = false;
for (int c = 0; (c = System.in.read()) != -1; ) {
if (c == '-') {
start = true;
neg = true;
continue;
} else if (c >= '0' && c <= '9') {
start = true;
ans = ans * 10 + c - '0';
} else if (start) break;
}
} catch (IOException e) {
}
return neg ? -ans : ans;
}
final int N = 300_000*32 + 10;
int n;
int sz = 1;
int[] cnt = new int[N];
int[][] pre = new int[N][2];
int[] m;
PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
void start() {
n = readInt();
m = new int[n];
for (int i = 0; i < N; i++) Arrays.fill(pre[i], -1);
for (int i = 0; i < n; i++) m[i] = readInt();
for (int i = 0; i < n; i++) {
int k = readInt(), r = 0;
for (int j = 29; j >= 0; j--) {
int b = (k >>> j) & 1;
if (pre[r][b] == -1) pre[r][b] = sz++;
r = pre[r][b];
cnt[r]++;
}
}
for (int a : m) {
int ans = 0, r = 0;
for (int i = 29; i >= 0; i--) {
int b = (a >>> i) & 1;
if (pre[r][b] == -1 || cnt[pre[r][b]] == 0) {
ans |= (1 << i);
b ^= 1;
}
r = pre[r][b];
cnt[r]--;
}
writer.print(ans + " ");
}
writer.flush();
}
public static void main(String[] args) {
new Test().start();
}
}
| Java | ["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"] | 3.5 seconds | ["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"] | NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution. | Java 8 | standard input | [
"data structures",
"greedy",
"trees",
"strings"
] | dc778193a126009f545d1d6f307bba83 | The first line contains a single integer N (1 ≤ N ≤ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≤ Ai < 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≤ Pi < 230) representing the permuted encryption key. | 1,800 | Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative. | standard output | |
PASSED | fce9890fba76b656bf34e205d5e6c72a | train_003.jsonl | 1520696100 | Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation π such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds. | 512 megabytes | import java.io.*;
import java.util.*;
/*
3
8 4 13
17 2 7
*/
public class c {
public static void main(String[] arg) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int[] vs = new int[n];
for(int i = 0; i < n; i++) {
vs[i] = in.nextInt();
}
trie = new int[2][32*n];
subtreeSize = new int[32*n];
curSize = 1;
for(int i = 0; i < n; i++) {
int val = in.nextInt();
String bs = Integer.toBinaryString(val);
while(bs.length() < 32) bs = '0'+bs;
add(0, 0, bs);
}
for(int i = 0; i < n; i++) {
if(i != 0) out.print(' ');
String bs = Integer.toBinaryString(vs[i]);
while(bs.length() < 32) bs = '0'+bs;
String s = del(0, 0, bs);
int ans = Integer.parseInt(s, 2);
out.print((vs[i]^ans));
}
out.close();
}
static int[][] trie;
static int[] subtreeSize;
static int curSize;
static void add(int node, int idx, String bs) {
subtreeSize[node]++;
if(idx == bs.length()) {
return;
}
int dir = bs.charAt(idx)-'0';
if(trie[dir][node] == 0) {
trie[dir][node] = curSize;
curSize++;
}
add(trie[dir][node], idx+1, bs);
}
static String del(int node, int idx, String bs) {
subtreeSize[node]--;
if(idx == bs.length()) {
return "";
}
int dir = bs.charAt(idx)-'0';
int to = trie[dir][node];
if(dir == 1) {
if(to != 0 && subtreeSize[to] > 0) {
return '1'+del(to, idx+1, bs);
} else {
return '0'+del(trie[1-dir][node], idx+1, bs);
}
} else {
if(to != 0 && subtreeSize[to] > 0) {
return '0'+del(trie[dir][node], idx+1, bs);
} else {
return '1'+del(trie[1-dir][node], idx+1, bs);
}
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
st = new StringTokenizer("");
}
public String next() throws IOException {
while(!st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
}
}
| Java | ["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"] | 3.5 seconds | ["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"] | NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution. | Java 8 | standard input | [
"data structures",
"greedy",
"trees",
"strings"
] | dc778193a126009f545d1d6f307bba83 | The first line contains a single integer N (1 ≤ N ≤ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≤ Ai < 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≤ Pi < 230) representing the permuted encryption key. | 1,800 | Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative. | standard output | |
PASSED | 9d54d7ac896c92085d624270f8ab04de | train_003.jsonl | 1520696100 | Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation π such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds. | 512 megabytes | import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
public class C {
public static void main(String[] args) throws Exception {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
// Scanner scan = new Scanner(System.in);
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
int n = Integer.parseInt(bf.readLine());
StringTokenizer st = new StringTokenizer(bf.readLine());
int[] a = new int[n];
for(int i=0; i<n; i++) a[i] = Integer.parseInt(st.nextToken());
st = new StringTokenizer(bf.readLine());
int[] b = new int[n];
for(int i=0; i<n; i++) b[i] = Integer.parseInt(st.nextToken());
TreeSet<Integer> p = new TreeSet<Integer>();
Map<Integer, Integer> counts = new HashMap<Integer, Integer>();
for(int i : b) {
if(counts.containsKey(i)) {
counts.put(i, counts.get(i)+1);
}
else {
counts.put(i, 1);
p.add(i);
}
}
int[] ans = new int[n];
for(int i=0; i<n; i++) {
int val = 0;
int cur = 0;
Integer match = null;
for(int bit = 29; bit>=0; bit--) {
// System.out.println(bit);
val += ((a[i] >> bit) & 1) * (1 << bit);
match = p.ceiling(val);
// System.out.println(val + " " + match.toString());
if((match == null) || (match.intValue() > val + (1 << bit) - 1)) {
val -= ((a[i] >> bit) & 1) * (1 << bit);
val += (1 - ((a[i] >> bit) & 1)) * (1 << bit);
match = p.ceiling(val);
cur += 1 << bit;
}
}
ans[i] = cur;
int toRemove = match.intValue();
if(counts.get(toRemove) > 1) {
counts.put(toRemove, counts.get(toRemove)-1);
}
else
p.remove(toRemove);
}
StringBuilder sb = new StringBuilder();
for(int i=0; i<n; i++) sb.append(ans[i] + " ");
out.println(sb.toString());
out.close(); System.exit(0);
}
} | Java | ["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"] | 3.5 seconds | ["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"] | NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution. | Java 8 | standard input | [
"data structures",
"greedy",
"trees",
"strings"
] | dc778193a126009f545d1d6f307bba83 | The first line contains a single integer N (1 ≤ N ≤ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≤ Ai < 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≤ Pi < 230) representing the permuted encryption key. | 1,800 | Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative. | standard output | |
PASSED | 5974a16e43e675986adc993906139f38 | train_003.jsonl | 1520696100 | Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation π such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds. | 512 megabytes | import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
public class C {
public static void main(String[] args) throws Exception {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
// Scanner scan = new Scanner(System.in);
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
int n = Integer.parseInt(bf.readLine());
StringTokenizer st = new StringTokenizer(bf.readLine());
int[] a = new int[n];
for(int i=0; i<n; i++) a[i] = Integer.parseInt(st.nextToken());
st = new StringTokenizer(bf.readLine());
int[] b = new int[n];
for(int i=0; i<n; i++) b[i] = Integer.parseInt(st.nextToken());
TreeSet<Integer> p = new TreeSet<Integer>();
Map<Integer, Integer> counts = new HashMap<Integer, Integer>();
for(int i : b) {
if(p.contains(i)) {
if(counts.containsKey(i)) counts.put(i, counts.get(i)+1);
else counts.put(i, 2);
}
else {
p.add(i);
}
}
int[] ans = new int[n];
for(int i=0; i<n; i++) {
int val = 0;
int cur = 0;
Integer match = null;
for(int bit = 29; bit>=0; bit--) {
// System.out.println(bit);
val += ((a[i] >> bit) & 1) * (1 << bit);
match = p.ceiling(val);
// System.out.println(val + " " + match.toString());
if((match == null) || (match.intValue() > val + (1 << bit) - 1)) {
val -= ((a[i] >> bit) & 1) * (1 << bit);
val += (1 - ((a[i] >> bit) & 1)) * (1 << bit);
match = p.ceiling(val);
cur += 1 << bit;
}
}
ans[i] = cur;
int toRemove = match.intValue();
if(counts.containsKey(toRemove)) {
if(counts.get(toRemove) > 1)
counts.put(toRemove, counts.get(toRemove)-1);
else
p.remove(toRemove);
}
else
p.remove(toRemove);
}
StringBuilder sb = new StringBuilder();
for(int i=0; i<n; i++) sb.append(ans[i] + " ");
out.println(sb.toString());
out.close(); System.exit(0);
}
}
| Java | ["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"] | 3.5 seconds | ["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"] | NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution. | Java 8 | standard input | [
"data structures",
"greedy",
"trees",
"strings"
] | dc778193a126009f545d1d6f307bba83 | The first line contains a single integer N (1 ≤ N ≤ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≤ Ai < 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≤ Pi < 230) representing the permuted encryption key. | 1,800 | Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative. | standard output | |
PASSED | 43a70b8bfa51b9b58cbf492133f82efd | train_003.jsonl | 1520696100 | Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation π such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds. | 512 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ProblemC {
BufferedReader rd;
ProblemC() throws IOException {
rd = new BufferedReader(new InputStreamReader(System.in));
compute();
}
private void compute() throws IOException {
rd.readLine();
int[] a = intarr();
int[] p = intarr();
int n = a.length;
Node root = new Node();
for(int i=0;i<n;i++) {
root.add(p[i], 30);
}
StringBuilder buf = new StringBuilder();
for(int i=0;i<n;i++) {
int x = a[i];
int y = root.poll(x, 30, 0);
int res = x ^ y;
if(i > 0) {
buf.append(' ');
}
buf.append(res);
}
out(buf);
}
class Node {
Node left;
Node right;
int cnt;
public void add(int p, int b) {
cnt++;
if(b >= 0) {
boolean s = (p & (1 << b)) > 0;
if(s) {
if(left == null) {
left = new Node();
}
left.add(p,b-1);
} else {
if(right == null) {
right = new Node();
}
right.add(p,b-1);
}
}
}
public int poll(int p, int b, int res) {
cnt--;
if(b >= 0) {
int u = 1<<b;
boolean s = (p & u) > 0;
if(s) {
if(left == null || left.cnt == 0) {
s = false;
}
} else if(right == null || right.cnt == 0) {
s = true;
}
if(s) {
return left.poll(p,b-1,res + u);
} else {
return right.poll(p,b-1,res);
}
}
return res;
}
}
private int pint() throws IOException {
return pint(rd.readLine());
}
private int pint(String s) {
return Integer.parseInt(s);
}
private int[] intarr() throws IOException {
return intarr(rd.readLine());
}
private int[] intarr(String s) {
String[] q = split(s);
int n = q.length;
int[] a = new int[n];
for(int i=0;i<n;i++) {
a[i] = Integer.parseInt(q[i]);
}
return a;
}
private String[] split(String s) {
if(s == null) {
return new String[0];
}
int n = s.length();
int start = -1;
int end = 0;
int sp = 0;
boolean lastWhitespace = true;
for(int i=0;i<n;i++) {
char c = s.charAt(i);
if(isWhitespace(c)) {
lastWhitespace = true;
} else {
if(lastWhitespace) {
sp++;
}
if(start == -1) {
start = i;
}
end = i;
lastWhitespace = false;
}
}
if(start == -1) {
return new String[0];
}
String[] res = new String[sp];
int last = start;
int x = 0;
lastWhitespace = true;
for(int i=start;i<=end;i++) {
char c = s.charAt(i);
boolean w = isWhitespace(c);
if(w && !lastWhitespace) {
res[x++] = s.substring(last,i);
} else if(!w && lastWhitespace) {
last = i;
}
lastWhitespace = w;
}
res[x] = s.substring(last,end+1);
return res;
}
private boolean isWhitespace(char c) {
return c==' ' || c=='\t';
}
private static void out(Object x) {
System.out.println(x);
}
public static void main(String[] args) throws IOException {
new ProblemC();
}
}
| Java | ["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"] | 3.5 seconds | ["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"] | NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution. | Java 8 | standard input | [
"data structures",
"greedy",
"trees",
"strings"
] | dc778193a126009f545d1d6f307bba83 | The first line contains a single integer N (1 ≤ N ≤ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≤ Ai < 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≤ Pi < 230) representing the permuted encryption key. | 1,800 | Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative. | standard output | |
PASSED | cf74e961dfc451740adc577e04d7a035 | train_003.jsonl | 1520696100 | Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation π such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds. | 512 megabytes | import java.util.*;
import java.io.*;
public class MainD
{
static int mod = (int) (1e9+7);
static InputReader in;
static PrintWriter out;
public static void main(String[] args)
{
in = new InputReader(System.in);
out = new PrintWriter(System.out);
int maxn = 4000000;
int[][] t = new int[maxn][2];
int[] cnt = new int[maxn * 2];
for(int i = 0; i < maxn; i++)
t[i][0] = t[i][1] = -1;
int n = in.nextInt();
int[] a = in.nextIntArray(n);
int[] b = new int[n];
int c = 1;
for(int i = 0; i < n; i++){
b[i] = in.nextInt();
int here = 0;
for(int j = 29; j >= 0; j--){
int x = ((1 << j) & b[i]) == 0 ? 0 : 1;
if(t[here][x] == -1)
t[here][x] = c++;
here = t[here][x];
cnt[here]++;
}
}
for(int i = 0; i < n; i++){
int here = 0;
int res = 0;
for(int j = 29; j >= 0; j--){
int x = ((1 << j) & a[i]) == 0 ? 0 : 1;
if(t[here][x] == -1 || cnt[t[here][x]] == 0){
here = t[here][1 ^ x];
res += 1 << j;
}
else{
here = t[here][x];
}
cnt[here]--;
}
out.print(res + " ");
}
out.println();
out.close();
}
static class Pair implements Comparable<Pair>
{
int x,y;
int i;
Pair (int x,int y)
{
this.x = x;
this.y = y;
}
Pair (int x,int y, int i)
{
this.x = x;
this.y = y;
this.i = i;
}
public int compareTo(Pair o)
{
return Integer.compare(this.i,o.i);
//return 0;
}
public boolean equals(Object o)
{
if (o instanceof Pair)
{
Pair p = (Pair)o;
return p.x == x && p.y==y;
}
return false;
}
@Override
public String toString()
{
return x + " "+ y + " "+i;
}
/*public int hashCode()
{
return new Long(x).hashCode() * 31 + new Long(y).hashCode();
}*/
}
static String rev(String s){
StringBuilder sb=new StringBuilder(s);
sb.reverse();
return sb.toString();
}
static long gcd(long x,long y)
{
if(y==0)
return x;
else
return gcd(y,x%y);
}
static int gcd(int x,int y)
{
if(y==0)
return x;
else
return gcd(y,x%y);
}
static long pow(long n,long p,long m)
{
long result = 1;
if(p==0){
return 1;
}
while(p!=0)
{
if(p%2==1)
result *= n;
if(result >= m)
result %= m;
p >>=1;
n*=n;
if(n >= m)
n%=m;
}
return result;
}
static long pow(long n,long p)
{
long result = 1;
if(p==0)
return 1;
while(p!=0)
{
if(p%2==1)
result *= n;
p >>=1;
n*=n;
}
return result;
}
static void debug(Object... o)
{
System.out.println(Arrays.deepToString(o));
}
static class InputReader
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int snext()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n)
{
long a[] = new long[n];
for (int i = 0; i < n; i++)
{
a[i] = nextLong();
}
return a;
}
public String readString()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"] | 3.5 seconds | ["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"] | NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution. | Java 8 | standard input | [
"data structures",
"greedy",
"trees",
"strings"
] | dc778193a126009f545d1d6f307bba83 | The first line contains a single integer N (1 ≤ N ≤ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≤ Ai < 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≤ Pi < 230) representing the permuted encryption key. | 1,800 | Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative. | standard output | |
PASSED | d8ac16effe6c4f18fa0cb72198f8968b | train_003.jsonl | 1520696100 | Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation π such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Pradyumn
*/
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);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, FastReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = in.nextIntArray(n);
int[] P = in.nextIntArray(n);
TrieBinary trieBinary = new TrieBinary(31);
for (int pp : P) trieBinary.add(pp);
int[] ans = new int[n];
for (int i = 0; i < n; ++i) {
ans[i] = trieBinary.xorMin(a[i]);
trieBinary.remove(ans[i]);
ans[i] ^= a[i];
}
ArrayUtils.printArray(out, ans);
}
}
static class ArrayUtils {
public static void fill(int[][] array, int value) {
for (int[] row : array) {
Arrays.fill(row, value);
}
}
public static void printArray(PrintWriter out, int[] array) {
if (array.length == 0) return;
for (int i = 0; i < array.length; i++) {
if (i != 0) out.print(" ");
out.print(array[i]);
}
out.println();
}
}
static class TrieBinary {
int MAX;
int[][] next;
int[] count;
int states = 1;
int BIT;
public TrieBinary(int bitCount) {
this.BIT = bitCount;
MAX = bitCount * 300000 + 1;
next = new int[2][MAX];
count = new int[MAX];
ArrayUtils.fill(next, -1);
}
public void add(int num) {
int cur = 0;
++count[cur];
for (int bit = BIT - 1; bit >= 0; --bit) {
int c = (num >> bit) & 1;
if (next[c][cur] == -1) {
next[c][cur] = states++;
}
cur = next[c][cur];
++count[cur];
}
}
public boolean search(int num) {
int cur = 0;
for (int bit = BIT - 1; bit >= 0; --bit) {
int c = (num >> bit) & 1;
if (next[c][cur] == -1 || (next[c][cur] != -1 && count[next[c][cur]] == 0)) {
return false;
}
cur = next[c][cur];
}
return true;
}
public int xorMin(int num) {
int cur = 0;
int value = 0;
for (int bit = BIT - 1; bit >= 0; --bit) {
int c = (num >> bit) & 1;
if (next[c][cur] != -1 && count[next[c][cur]] > 0) {
} else {
c ^= 1;
}
cur = next[c][cur];
value = (value << 1) | c;
}
return value;
}
public boolean remove(int num) {
if (!search(num)) return false;
int cur = 0;
--count[cur];
for (int bit = BIT - 1; bit >= 0; --bit) {
int c = (num >> bit) & 1;
cur = next[c][cur];
--count[cur];
}
return true;
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int pnumChars;
public FastReader(InputStream stream) {
this.stream = stream;
}
private int pread() {
if (pnumChars == -1) {
throw new InputMismatchException();
}
if (curChar >= pnumChars) {
curChar = 0;
try {
pnumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (pnumChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = pread();
while (isSpaceChar(c))
c = pread();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = pread();
}
int res = 0;
do {
if (c == ',') {
c = pread();
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = pread();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = nextInt();
}
return array;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
| Java | ["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"] | 3.5 seconds | ["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"] | NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution. | Java 8 | standard input | [
"data structures",
"greedy",
"trees",
"strings"
] | dc778193a126009f545d1d6f307bba83 | The first line contains a single integer N (1 ≤ N ≤ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≤ Ai < 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≤ Pi < 230) representing the permuted encryption key. | 1,800 | Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative. | standard output | |
PASSED | 63c2fd5304d39b14df43fa3f9c6a2224 | train_003.jsonl | 1520696100 | Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation π such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Pradyumn
*/
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);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, FastReader in, PrintWriter out) {
Debug debug = new Debug(out);
int n = in.nextInt();
int[] a = in.nextIntArray(n);
int[] P = in.nextIntArray(n);
TrieBinary trieBinary = new TrieBinary(31);
for (int pp : P) trieBinary.add(pp);
int[] ans = new int[n];
for (int i = 0; i < n; ++i) {
ans[i] = trieBinary.xorMin(a[i]);
trieBinary.remove(ans[i]);
ans[i] ^= a[i];
}
ArrayUtils.printArray(out, ans);
}
}
static class ArrayUtils {
public static void fill(int[][] array, int value) {
for (int[] row : array) {
Arrays.fill(row, value);
}
}
public static void printArray(PrintWriter out, int[] array) {
if (array.length == 0) return;
for (int i = 0; i < array.length; i++) {
if (i != 0) out.print(" ");
out.print(array[i]);
}
out.println();
}
}
static class TrieBinary {
int MAX;
int[][] next;
int[] count;
int states = 1;
int BIT;
public TrieBinary(int bitCount) {
this.BIT = bitCount;
MAX = bitCount * 300000 + 1;
next = new int[2][MAX];
count = new int[MAX];
ArrayUtils.fill(next, -1);
}
public void add(int num) {
int cur = 0;
++count[cur];
for (int bit = BIT - 1; bit >= 0; --bit) {
int c = (num >> bit) & 1;
if (next[c][cur] == -1) {
next[c][cur] = states++;
}
cur = next[c][cur];
++count[cur];
}
}
public boolean search(int num) {
int cur = 0;
for (int bit = BIT - 1; bit >= 0; --bit) {
int c = (num >> bit) & 1;
if (next[c][cur] == -1 || (next[c][cur] != -1 && count[next[c][cur]] == 0)) {
return false;
}
cur = next[c][cur];
}
return true;
}
public int xorMin(int num) {
int cur = 0;
int value = 0;
for (int bit = BIT - 1; bit >= 0; --bit) {
int c = (num >> bit) & 1;
if (next[c][cur] != -1 && count[next[c][cur]] > 0) {
} else {
c ^= 1;
}
cur = next[c][cur];
value = (value << 1) | c;
}
return value;
}
public boolean remove(int num) {
if (!search(num)) return false;
int cur = 0;
--count[cur];
for (int bit = BIT - 1; bit >= 0; --bit) {
int c = (num >> bit) & 1;
cur = next[c][cur];
--count[cur];
}
return true;
}
}
static class Debug {
PrintWriter out;
boolean oj;
boolean system;
long timeBegin;
Runtime runtime;
public Debug(PrintWriter out) {
oj = System.getProperty("ONLINE_JUDGE") != null;
this.out = out;
this.timeBegin = System.currentTimeMillis();
this.runtime = Runtime.getRuntime();
}
public Debug() {
system = true;
oj = System.getProperty("ONLINE_JUDGE") != null;
OutputStream outputStream = System.out;
this.out = new PrintWriter(outputStream);
this.timeBegin = System.currentTimeMillis();
this.runtime = Runtime.getRuntime();
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int pnumChars;
public FastReader(InputStream stream) {
this.stream = stream;
}
private int pread() {
if (pnumChars == -1) {
throw new InputMismatchException();
}
if (curChar >= pnumChars) {
curChar = 0;
try {
pnumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (pnumChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = pread();
while (isSpaceChar(c))
c = pread();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = pread();
}
int res = 0;
do {
if (c == ',') {
c = pread();
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = pread();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = nextInt();
}
return array;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
| Java | ["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"] | 3.5 seconds | ["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"] | NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution. | Java 8 | standard input | [
"data structures",
"greedy",
"trees",
"strings"
] | dc778193a126009f545d1d6f307bba83 | The first line contains a single integer N (1 ≤ N ≤ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≤ Ai < 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≤ Pi < 230) representing the permuted encryption key. | 1,800 | Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative. | standard output | |
PASSED | 630b10d1a460fca939db07d1b43faf4b | train_003.jsonl | 1520696100 | Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation π such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Pradyumn
*/
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);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, FastReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = in.nextIntArray(n);
int[] P = in.nextIntArray(n);
TaskC.TrieArrayBinary trie = new TaskC.TrieArrayBinary(31);
for (int v : P) trie.add(v);
for (int v : a) {
long ret = trie.xormin(v);
out.print(ret + " ");
trie.remove(ret ^ v);
}
}
public static class L {
public int[] a;
public int p = 0;
public L(int n) {
a = new int[n];
}
public TaskC.L add(int n) {
if (p >= a.length) a = Arrays.copyOf(a, a.length * 3 / 2 + 1);
a[p++] = n;
return this;
}
public int[] toArray() {
return Arrays.copyOf(a, p);
}
public String toString() {
return Arrays.toString(toArray());
}
}
public static class TrieArrayBinary {
public TaskC.L next;
public int gen;
public int W;
public TaskC.L hit;
public TrieArrayBinary(int W) {
this.W = W;
this.next = new TaskC.L(2);
this.hit = new TaskC.L(1);
this.gen = 1;
this.next.add(-1).add(-1);
this.hit.add(0);
}
public void add(long s) {
int cur = 0;
for (int d = W - 1; d >= 0; d--) {
int v = (int) (s >>> d & 1);
int nex = next.a[cur * 2 + v];
if (nex == -1) {
nex = next.a[cur * 2 + v] = gen++;
next.add(-1).add(-1);
hit.add(0);
}
cur = nex;
}
hit.a[cur]++;
}
public void remove(long s) {
int cur = 0;
int[] hist = new int[W];
for (int d = W - 1; d >= 0; d--) {
hist[d] = cur;
int v = (int) (s >>> d & 1);
int nex = next.a[cur * 2 + v];
if (nex == -1) {
throw new RuntimeException();
}
cur = nex;
}
if (--hit.a[cur] == 0) {
for (int d = 0; d < W; d++) {
int v = (int) (s >>> d & 1);
next.a[hist[d] * 2 | v] = -1;
if (next.a[hist[d] * 2 | v ^ 1] != -1) break;
}
}
}
public long xormin(long x) {
int cur = 0;
long ret = 0;
for (int d = W - 1; d >= 0; d--) {
if (cur == -1) {
ret |= x << -d >>> -d;
break;
}
int xd = (int) (x >>> d & 1);
if (next.a[cur * 2 | xd] != -1) {
cur = next.a[cur * 2 | xd];
} else {
ret |= 1L << d;
cur = next.a[cur * 2 | xd ^ 1];
}
}
return ret;
}
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int pnumChars;
public FastReader(InputStream stream) {
this.stream = stream;
}
private int pread() {
if (pnumChars == -1) {
throw new InputMismatchException();
}
if (curChar >= pnumChars) {
curChar = 0;
try {
pnumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (pnumChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = pread();
while (isSpaceChar(c))
c = pread();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = pread();
}
int res = 0;
do {
if (c == ',') {
c = pread();
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = pread();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = nextInt();
}
return array;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
| Java | ["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"] | 3.5 seconds | ["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"] | NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution. | Java 8 | standard input | [
"data structures",
"greedy",
"trees",
"strings"
] | dc778193a126009f545d1d6f307bba83 | The first line contains a single integer N (1 ≤ N ≤ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≤ Ai < 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≤ Pi < 230) representing the permuted encryption key. | 1,800 | Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative. | standard output | |
PASSED | d9eae2ae58a9a159ae40125cd273c705 | train_003.jsonl | 1520696100 | Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation π such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Pradyumn
*/
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);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, FastReader in, PrintWriter out) {
Debug debug = new Debug(out);
int n = in.nextInt();
int[] a = in.nextIntArray(n);
int[] P = in.nextIntArray(n);
int BIT = 30;
int MAX = BIT * 300000 + 1;
int[][] next = new int[2][MAX];
int[] count = new int[MAX];
int states = 1;
ArrayUtils.fill(next, -1);
for (int pp : P) {
int cur = 0;
++count[cur];
for (int bit = BIT - 1; bit >= 0; --bit) {
int c = (pp >> bit) & 1;
if (next[c][cur] == -1) {
next[c][cur] = states++;
}
cur = next[c][cur];
++count[cur];
}
}
int[] ans = new int[n];
for (int i = 0; i < n; ++i) {
int cur = 0;
int value = 0;
--count[cur];
for (int bit = BIT - 1; bit >= 0; --bit) {
int c = (a[i] >> bit) & 1;
if (next[c][cur] != -1 && count[next[c][cur]] > 0) {
} else {
c ^= 1;
}
cur = next[c][cur];
--count[cur];
value = (value << 1) | c;
ans[i] = value ^ a[i];
}
}
ArrayUtils.printArray(out, ans);
}
}
static class ArrayUtils {
public static void fill(int[][] array, int value) {
for (int[] row : array) {
Arrays.fill(row, value);
}
}
public static void printArray(PrintWriter out, int[] array) {
if (array.length == 0) return;
for (int i = 0; i < array.length; i++) {
if (i != 0) out.print(" ");
out.print(array[i]);
}
out.println();
}
}
static class Debug {
PrintWriter out;
boolean oj;
boolean system;
long timeBegin;
Runtime runtime;
public Debug(PrintWriter out) {
oj = System.getProperty("ONLINE_JUDGE") != null;
this.out = out;
this.timeBegin = System.currentTimeMillis();
this.runtime = Runtime.getRuntime();
}
public Debug() {
system = true;
oj = System.getProperty("ONLINE_JUDGE") != null;
OutputStream outputStream = System.out;
this.out = new PrintWriter(outputStream);
this.timeBegin = System.currentTimeMillis();
this.runtime = Runtime.getRuntime();
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int pnumChars;
public FastReader(InputStream stream) {
this.stream = stream;
}
private int pread() {
if (pnumChars == -1) {
throw new InputMismatchException();
}
if (curChar >= pnumChars) {
curChar = 0;
try {
pnumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (pnumChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = pread();
while (isSpaceChar(c))
c = pread();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = pread();
}
int res = 0;
do {
if (c == ',') {
c = pread();
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = pread();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = nextInt();
}
return array;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
| Java | ["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"] | 3.5 seconds | ["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"] | NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution. | Java 8 | standard input | [
"data structures",
"greedy",
"trees",
"strings"
] | dc778193a126009f545d1d6f307bba83 | The first line contains a single integer N (1 ≤ N ≤ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≤ Ai < 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≤ Pi < 230) representing the permuted encryption key. | 1,800 | Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.