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 | 332e5802de65de3ec03ea45790419170 | train_107.jsonl | 1651502100 | You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps: Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements. Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements. Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order? | 256 megabytes |
import java.io.*;
import java.math.*;
import java.util.*;
// @author : Dinosparton
public class test {
static class Pair{
long x;
long y;
Pair(long x,long y){
this.x = x;
this.y = y;
}
}
static class Triplet{
long x;
long y;
double ratio;
Triplet(long x,long y,double ratio){
this.x = x;
this.y = y;
this.ratio = ratio;
}
}
static class Sort implements Comparator<Pair>
{
@Override
public int compare(Pair a, Pair b)
{
if(a.x!=b.x)
{
return (int)(a.x - b.x);
}
else
{
return (int)(a.y-b.y);
}
}
}
static class Compare {
void compare(Pair arr[], int n)
{
// Comparator to sort the pair according to second element
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
if(p1.x!=p2.x) {
return (int)(p1.x - p2.x);
}
else {
return (int)(p1.y - p2.y);
}
}
});
// for (int i = 0; i < n; i++) {
// System.out.print(arr[i].x + " " + arr[i].y + " ");
// }
// System.out.println();
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static boolean isSorted(ArrayList<Integer> list) {
for(int i=1;i<list.size();i++) {
if(list.get(i-1)>list.get(i)) {
return false;
}
}
return true;
}
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner();
StringBuilder res = new StringBuilder();
int tc = sc.nextInt();
while(tc-->0) {
int n = sc.nextInt();
int a[] = new int[n];
for(int i=0;i<n;i++) {
a[i] = sc.nextInt();
}
ArrayList<Integer> list = new ArrayList<>();
if(n%2==0) {
int i = 0;
while(i<n) {
if(i%2==0) {
if(a[i]<=a[i+1]) {
list.add(a[i]);
}
else {
list.add(a[i+1]);
list.add(a[i]);
i++;
}
}
else {
list.add(a[i]);
}
i++;
}
}
else {
int i = 0;
while(i<n) {
if(i%2!=0) {
if(a[i]<=a[i+1]) {
list.add(a[i]);
}
else {
list.add(a[i+1]);
list.add(a[i]);
i++;
}
}
else {
list.add(a[i]);
}
i++;
}
}
if(isSorted(list)) {
res.append("YES"+"\n");
}
else {
res.append("NO"+"\n");
}
}
System.out.println(res);
}
}
| Java | ["3\n\n4\n\n3 1 5 3\n\n3\n\n3 2 1\n\n1\n\n7331"] | 2 seconds | ["YES\nNO\nYES"] | NoteIn the first test case, we can do the following for $$$a = [3, 1, 5, 3]$$$:Step $$$1$$$: $$$a$$$$$$[3, 1, 5, 3]$$$$$$\Rightarrow$$$$$$[3, 1, 5]$$$$$$\Rightarrow$$$$$$[3, 1]$$$$$$\Rightarrow$$$$$$[3]$$$$$$\Rightarrow$$$$$$[]$$$$$$b$$$$$$[]$$$$$$[\underline{3}]$$$$$$[3, \underline{5}]$$$$$$[3, \underline{1}, 5]$$$$$$[3, \underline{3}, 1, 5]$$$Step $$$2$$$: $$$b$$$$$$[3, 3, \underline{1}, 5]$$$$$$\Rightarrow$$$$$$[3, \underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{5}]$$$$$$\Rightarrow$$$$$$[]$$$$$$c$$$$$$[]$$$$$$[1]$$$$$$[1, 3]$$$$$$[1, 3, 3]$$$$$$[1, 3, 3, 5]$$$ As a result, array $$$c = [1, 3, 3, 5]$$$ and it's sorted. | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings"
] | 95b35c53028ed0565684713a93910860 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — the array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,200 | For each test, print YES (case-insensitive), if you can make array $$$c$$$ sorted in non-decreasing order. Otherwise, print NO (case-insensitive). | standard output | |
PASSED | 4e87d681a921a36314c9ee68732d78a5 | train_107.jsonl | 1651502100 | You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps: Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements. Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements. Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order? | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private FastWriter wr;
private Reader rd;
public final int MOD = 1000000007;
/************************************************** FAST INPUT IMPLEMENTATION *********************************************/
class Reader {
BufferedReader br;
StringTokenizer st;
public Reader() {
br = new BufferedReader(
new InputStreamReader(System.in));
}
public Reader(String path) throws FileNotFoundException {
br = new BufferedReader(
new InputStreamReader(new FileInputStream(path)));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public int ni() throws IOException {
return rd.nextInt();
}
public long nl() throws IOException {
return rd.nextLong();
}
char nc() throws IOException {
return rd.next().charAt(0);
}
public String ns() throws IOException {
return rd.nextLine();
}
public Double nd() throws IOException {
return rd.nextDouble();
}
public int[] nai(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = ni();
}
return arr;
}
public long[] nal(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nl();
}
return arr;
}
/************************************************** FAST OUTPUT IMPLEMENTATION *********************************************/
public static class FastWriter {
private static final int BUF_SIZE = 1 << 13;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastWriter() {
out = null;
}
public FastWriter(OutputStream os) {
this.out = os;
}
public FastWriter(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastWriter write(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE) innerflush();
return this;
}
public FastWriter write(char c) {
return write((byte) c);
}
public FastWriter write(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
}
return this;
}
public FastWriter write(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
});
return this;
}
private static int countDigits(int l) {
if (l >= 1000000000) return 10;
if (l >= 100000000) return 9;
if (l >= 10000000) return 8;
if (l >= 1000000) return 7;
if (l >= 100000) return 6;
if (l >= 10000) return 5;
if (l >= 1000) return 4;
if (l >= 100) return 3;
if (l >= 10) return 2;
return 1;
}
public FastWriter write(int x) {
if (x == Integer.MIN_VALUE) {
return write((long) x);
}
if (ptr + 12 >= BUF_SIZE) innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L) return 19;
if (l >= 100000000000000000L) return 18;
if (l >= 10000000000000000L) return 17;
if (l >= 1000000000000000L) return 16;
if (l >= 100000000000000L) return 15;
if (l >= 10000000000000L) return 14;
if (l >= 1000000000000L) return 13;
if (l >= 100000000000L) return 12;
if (l >= 10000000000L) return 11;
if (l >= 1000000000L) return 10;
if (l >= 100000000L) return 9;
if (l >= 10000000L) return 8;
if (l >= 1000000L) return 7;
if (l >= 100000L) return 6;
if (l >= 10000L) return 5;
if (l >= 1000L) return 4;
if (l >= 100L) return 3;
if (l >= 10L) return 2;
return 1;
}
public FastWriter write(long x) {
if (x == Long.MIN_VALUE) {
return write("" + x);
}
if (ptr + 21 >= BUF_SIZE) innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
public FastWriter write(double x, int precision) {
if (x < 0) {
write('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
// if(x < 0){ x = 0; }
write((long) x).write(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
write((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastWriter writeln(char c) {
return write(c).writeln();
}
public FastWriter writeln(int x) {
return write(x).writeln();
}
public FastWriter writeln(long x) {
return write(x).writeln();
}
public FastWriter writeln(double x, int precision) {
return write(x, precision).writeln();
}
public FastWriter write(int... xs) {
boolean first = true;
for (int x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter write(long... xs) {
boolean first = true;
for (long x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter writeln() {
return write((byte) '\n');
}
public FastWriter writeln(int... xs) {
return write(xs).writeln();
}
public FastWriter writeln(long... xs) {
return write(xs).writeln();
}
public FastWriter writeln(char[] line) {
return write(line).writeln();
}
public FastWriter writeln(char[]... map) {
for (char[] line : map) write(line).writeln();
return this;
}
public FastWriter writeln(String s) {
return write(s).writeln();
}
private void innerflush() {
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush() {
innerflush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
public FastWriter print(byte b) {
return write(b);
}
public FastWriter print(char c) {
return write(c);
}
public FastWriter print(char[] s) {
return write(s);
}
public FastWriter print(String s) {
return write(s);
}
public FastWriter print(int x) {
return write(x);
}
public FastWriter print(long x) {
return write(x);
}
public FastWriter print(double x, int precision) {
return write(x, precision);
}
public FastWriter println(char c) {
return writeln(c);
}
public FastWriter println(int x) {
return writeln(x);
}
public FastWriter println(long x) {
return writeln(x);
}
public FastWriter println(double x, int precision) {
return writeln(x, precision);
}
public FastWriter print(int... xs) {
return write(xs);
}
public FastWriter print(long... xs) {
return write(xs);
}
public FastWriter println(int... xs) {
return writeln(xs);
}
public FastWriter println(long... xs) {
return writeln(xs);
}
public FastWriter println(char[] line) {
return writeln(line);
}
public FastWriter println(char[]... map) {
return writeln(map);
}
public FastWriter println(String s) {
return writeln(s);
}
public FastWriter println() {
return writeln();
}
}
/********************************************************* USEFUL CODE **************************************************/
boolean[] SAPrimeGenerator(int n) {
// TC-N*LOG(LOG N)
//Create Prime Marking Array and fill it with true value
boolean[] primeMarker = new boolean[n + 1];
Arrays.fill(primeMarker, true);
primeMarker[0] = false;
primeMarker[1] = false;
for (int i = 2; i <= n; i++) {
if (primeMarker[i]) {
// we start from 2*i because i*1 must be prime
for (int j = 2 * i; j <= n; j += i) {
primeMarker[j] = false;
}
}
}
return primeMarker;
}
private void tr(Object... o) {
if (!oj) System.out.println(Arrays.deepToString(o));
}
class Pair<F, S> {
private F first;
private S second;
Pair(F first, S second) {
this.first = first;
this.second = second;
}
public F getFirst() {
return first;
}
public S getSecond() {
return second;
}
@Override
public String toString() {
return "Pair{" +
"first=" + first +
", second=" + second +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair<F, S> pair = (Pair<F, S>) o;
return first == pair.first && second == pair.second;
}
@Override
public int hashCode() {
return Objects.hash(first, second);
}
}
public static void main(String[] args) throws IOException {
new Main().run();
}
public void run() throws IOException {
if (oj) {
rd = new Reader();
wr = new FastWriter(System.out);
} else {
File input = new File("input.txt");
File output = new File("output.txt");
if (input.exists() && output.exists()) {
rd = new Reader(input.getPath());
wr = new FastWriter(output.getPath());
} else {
rd = new Reader();
wr = new FastWriter(System.out);
oj = true;
}
}
long s = System.currentTimeMillis();
solve();
wr.flush();
tr(System.currentTimeMillis() - s + "ms");
}
/***************************************************************************************************************************
*********************************************************** MAIN CODE ******************************************************
****************************************************************************************************************************/
boolean[] sieve;
public void solve() throws IOException {
int t = 1;
t = ni();
while (t-- > 0) {
go();
}
}
/********************************************************* MAIN LOGIC HERE ****************************************************/
long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
public void go() throws IOException {
int n=ni();
int[] arr=nai(n);
int[] tempArr=Arrays.copyOf(arr,n);
Arrays.sort(arr);
int i=n%2==0?0:1;
if(n%2==1 && arr[0]!=tempArr[0]){
wr.println("NO");
return;
}
boolean flag=true;
for(;i<n-1;i+=2){
int num1,num2,num3,num4;
num1=arr[i];
num2=arr[i+1];
num3=tempArr[i];
num4=tempArr[i+1];
if(!((num1==num3 && num2==num4)||(num1==num4&&num2==num3))){
flag=false;
break;
}
}
wr.println(flag?"YES":"NO");
}
} | Java | ["3\n\n4\n\n3 1 5 3\n\n3\n\n3 2 1\n\n1\n\n7331"] | 2 seconds | ["YES\nNO\nYES"] | NoteIn the first test case, we can do the following for $$$a = [3, 1, 5, 3]$$$:Step $$$1$$$: $$$a$$$$$$[3, 1, 5, 3]$$$$$$\Rightarrow$$$$$$[3, 1, 5]$$$$$$\Rightarrow$$$$$$[3, 1]$$$$$$\Rightarrow$$$$$$[3]$$$$$$\Rightarrow$$$$$$[]$$$$$$b$$$$$$[]$$$$$$[\underline{3}]$$$$$$[3, \underline{5}]$$$$$$[3, \underline{1}, 5]$$$$$$[3, \underline{3}, 1, 5]$$$Step $$$2$$$: $$$b$$$$$$[3, 3, \underline{1}, 5]$$$$$$\Rightarrow$$$$$$[3, \underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{5}]$$$$$$\Rightarrow$$$$$$[]$$$$$$c$$$$$$[]$$$$$$[1]$$$$$$[1, 3]$$$$$$[1, 3, 3]$$$$$$[1, 3, 3, 5]$$$ As a result, array $$$c = [1, 3, 3, 5]$$$ and it's sorted. | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings"
] | 95b35c53028ed0565684713a93910860 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — the array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,200 | For each test, print YES (case-insensitive), if you can make array $$$c$$$ sorted in non-decreasing order. Otherwise, print NO (case-insensitive). | standard output | |
PASSED | b26d35b4bd99afa128df9f7ea1dcbb80 | train_107.jsonl | 1651502100 | You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps: Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements. Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements. Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order? | 256 megabytes | import java.io.*;
import java.util.*;
public class D {
public static void main (String[] args) throws IOException {
Kattio io = new Kattio();
int t = io.nextInt();
outer: for (int ii=0; ii<t; ii++) {
int n = io.nextInt();
int[] arr = new int[n];
for (int i=0; i<n; i++) {
arr[i] = io.nextInt();
}
for (int i=n-1; i>=1; i-=2) {
if (arr[i-1] > arr[i]) {
int temp = arr[i-1];
arr[i-1] = arr[i];
arr[i] = temp;
}
}
/*for (int i : arr) {
System.out.println(i);
}*/
for (int i=0; i<n-1; i++) {
if (arr[i] > arr[i+1]) {
System.out.println("NO");
continue outer;
}
}
System.out.println("YES");
}
}
static class Kattio extends PrintWriter {
private BufferedReader r;
private StringTokenizer st;
// standard input
public Kattio() { this(System.in, System.out); }
public Kattio(InputStream i, OutputStream o) {
super(o);
r = new BufferedReader(new InputStreamReader(i));
}
// USACO-style file input
public Kattio(String problemName) throws IOException {
super(new FileWriter(problemName + ".out"));
r = new BufferedReader(new FileReader(problemName + ".in"));
}
// returns null if no more input
public String next() {
try {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(r.readLine());
return st.nextToken();
} catch (Exception e) { }
return null;
}
public int nextInt() { return Integer.parseInt(next()); }
public double nextDouble() { return Double.parseDouble(next()); }
public long nextLong() { return Long.parseLong(next()); }
}
} | Java | ["3\n\n4\n\n3 1 5 3\n\n3\n\n3 2 1\n\n1\n\n7331"] | 2 seconds | ["YES\nNO\nYES"] | NoteIn the first test case, we can do the following for $$$a = [3, 1, 5, 3]$$$:Step $$$1$$$: $$$a$$$$$$[3, 1, 5, 3]$$$$$$\Rightarrow$$$$$$[3, 1, 5]$$$$$$\Rightarrow$$$$$$[3, 1]$$$$$$\Rightarrow$$$$$$[3]$$$$$$\Rightarrow$$$$$$[]$$$$$$b$$$$$$[]$$$$$$[\underline{3}]$$$$$$[3, \underline{5}]$$$$$$[3, \underline{1}, 5]$$$$$$[3, \underline{3}, 1, 5]$$$Step $$$2$$$: $$$b$$$$$$[3, 3, \underline{1}, 5]$$$$$$\Rightarrow$$$$$$[3, \underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{5}]$$$$$$\Rightarrow$$$$$$[]$$$$$$c$$$$$$[]$$$$$$[1]$$$$$$[1, 3]$$$$$$[1, 3, 3]$$$$$$[1, 3, 3, 5]$$$ As a result, array $$$c = [1, 3, 3, 5]$$$ and it's sorted. | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings"
] | 95b35c53028ed0565684713a93910860 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — the array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,200 | For each test, print YES (case-insensitive), if you can make array $$$c$$$ sorted in non-decreasing order. Otherwise, print NO (case-insensitive). | standard output | |
PASSED | 98c774589572c7b2ebb35d21e2140ddd | train_107.jsonl | 1651502100 | You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps: Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements. Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements. Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order? | 256 megabytes | import java.io.*;
import java.util.*;
public class B {
static long TIME_START, TIME_END;
public static class Task {
public void solve(Scanner sc, PrintWriter pw) throws IOException {
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = sc.nextInt();
int temp = 0;
for (int i = n - 2; i >= 0; i -= 2) {
if (arr[i] > arr[i + 1]) {
temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
String res = "YES";
for (int i = 1; i < n; i++) {
if (arr[i - 1] > arr[i]) {
res = "NO";
break;
}
}
pw.println(res);
}
}
public static void main(String[] args) throws IOException {
// Scanner sc = new Scanner(new FileReader(System.getenv("INPUT")));
Scanner sc = new Scanner(System.in);
// PrintWriter pw = new PrintWriter(new BufferedOutputStream(new FileOutputStream(System.getenv("OUTPUT"))));
PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out));
Runtime runtime = Runtime.getRuntime();
long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory();
TIME_START = System.currentTimeMillis();
Task t = new Task();
int T = sc.nextInt();
while (T-- > 0) {
t.solve(sc, pw);
}
TIME_END = System.currentTimeMillis();
long usedMemoryAfter = runtime.totalMemory() - runtime.freeMemory();
pw.close();
System.err.println("Memory increased: " + (usedMemoryAfter - usedMemoryBefore) / 1000000);
System.err.println("Time used: " + (TIME_END - TIME_START) + ".");
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader s) throws FileNotFoundException {
br = new BufferedReader(s);
}
public String next() throws IOException {
while (st == null || ! st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public int[] readIntArray(int n) throws IOException {
int[] arr = new int[n];
String[] a = nextLine().split(" ");
for (int i = 0; i < n; i++)
arr[i] = Integer.parseInt(a[i]);
return arr;
}
public long[] readLongArray(int n) throws IOException {
long[] arr = new long[n];
String[] a = nextLine().split(" ");
for (int i = 0; i < n; i++)
arr[i] = Long.parseLong(a[i]);
return arr;
}
public boolean ready() throws IOException {
return br.ready();
}
}
} | Java | ["3\n\n4\n\n3 1 5 3\n\n3\n\n3 2 1\n\n1\n\n7331"] | 2 seconds | ["YES\nNO\nYES"] | NoteIn the first test case, we can do the following for $$$a = [3, 1, 5, 3]$$$:Step $$$1$$$: $$$a$$$$$$[3, 1, 5, 3]$$$$$$\Rightarrow$$$$$$[3, 1, 5]$$$$$$\Rightarrow$$$$$$[3, 1]$$$$$$\Rightarrow$$$$$$[3]$$$$$$\Rightarrow$$$$$$[]$$$$$$b$$$$$$[]$$$$$$[\underline{3}]$$$$$$[3, \underline{5}]$$$$$$[3, \underline{1}, 5]$$$$$$[3, \underline{3}, 1, 5]$$$Step $$$2$$$: $$$b$$$$$$[3, 3, \underline{1}, 5]$$$$$$\Rightarrow$$$$$$[3, \underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{5}]$$$$$$\Rightarrow$$$$$$[]$$$$$$c$$$$$$[]$$$$$$[1]$$$$$$[1, 3]$$$$$$[1, 3, 3]$$$$$$[1, 3, 3, 5]$$$ As a result, array $$$c = [1, 3, 3, 5]$$$ and it's sorted. | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings"
] | 95b35c53028ed0565684713a93910860 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — the array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,200 | For each test, print YES (case-insensitive), if you can make array $$$c$$$ sorted in non-decreasing order. Otherwise, print NO (case-insensitive). | standard output | |
PASSED | d6ad2a2244291e92f1db5715f76dbe94 | train_107.jsonl | 1651502100 | You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps: Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements. Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements. Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order? | 256 megabytes | //package MyPackage;
import java.util.*;
import java.io.*;
public class A{
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br=new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while(st==null || !st.hasMoreTokens()){
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
String nextLine(){
String str="";
try {
str=br.readLine().trim();
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
}
static class FastWriter {
private final BufferedWriter bw;
public FastWriter() {
this.bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
public void print(Object object) throws IOException {
bw.append("" + object);
}
public void println(Object object) throws IOException {
print(object);
bw.append("\n");
}
public void close() throws IOException {
bw.close();
}
}
public static void main(String[] args) {
try {
FastReader in=new FastReader();
FastWriter out = new FastWriter();
StringBuilder sb = new StringBuilder();
int testCases=in.nextInt();
while(testCases-- > 0){
// write code here
int n = in.nextInt();
int a[] = new int[n];
for(int i = 0; i < n; i++) a[i] = in.nextInt();
if(n <= 2)
{
sb.append("YES" + "\n");
continue;
}
boolean ok = true;
int l = a[n - 1], sl = a[n - 2];
for(int i = n - 3; i >= 0; i -= 2)
{
int min = Math.min(l, sl);
if(a[i] > min || (i > 0 && a[i - 1] > min))
{
ok = false;
break;
}
l = a[i];
if(i > 0) sl = a[i - 1];
}
if(ok) sb.append("YES" + "\n");
else sb.append("NO" + "\n");
}
out.println(sb);
out.close();
} catch (Exception e) {
System.out.println(e);
return;
}
}
} | Java | ["3\n\n4\n\n3 1 5 3\n\n3\n\n3 2 1\n\n1\n\n7331"] | 2 seconds | ["YES\nNO\nYES"] | NoteIn the first test case, we can do the following for $$$a = [3, 1, 5, 3]$$$:Step $$$1$$$: $$$a$$$$$$[3, 1, 5, 3]$$$$$$\Rightarrow$$$$$$[3, 1, 5]$$$$$$\Rightarrow$$$$$$[3, 1]$$$$$$\Rightarrow$$$$$$[3]$$$$$$\Rightarrow$$$$$$[]$$$$$$b$$$$$$[]$$$$$$[\underline{3}]$$$$$$[3, \underline{5}]$$$$$$[3, \underline{1}, 5]$$$$$$[3, \underline{3}, 1, 5]$$$Step $$$2$$$: $$$b$$$$$$[3, 3, \underline{1}, 5]$$$$$$\Rightarrow$$$$$$[3, \underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{5}]$$$$$$\Rightarrow$$$$$$[]$$$$$$c$$$$$$[]$$$$$$[1]$$$$$$[1, 3]$$$$$$[1, 3, 3]$$$$$$[1, 3, 3, 5]$$$ As a result, array $$$c = [1, 3, 3, 5]$$$ and it's sorted. | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings"
] | 95b35c53028ed0565684713a93910860 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — the array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,200 | For each test, print YES (case-insensitive), if you can make array $$$c$$$ sorted in non-decreasing order. Otherwise, print NO (case-insensitive). | standard output | |
PASSED | 0326efc639e36bd15837743271bd9032 | train_107.jsonl | 1651502100 | You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps: Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements. Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements. Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order? | 256 megabytes | import java.io.*;import java.lang.*;import java.util.*;
//* --> number of prime numbers less then or equal to x are --> x/ln(x)
//* --> String concatenation using the + operator within a loop should be avoided. Since the String object is immutable, each call for concatenation will
// result in a new String object being created.
// THE SIEVE USED HERE WILL RETURN A LIST CONTAINING ALL THE PRIME NUMBERS TILL N
public class codechef {static FastScanner sc;static PrintWriter pw;static class FastScanner {InputStreamReader is;BufferedReader br;StringTokenizer st;
public FastScanner() {is = new InputStreamReader(System.in);br = new BufferedReader(is);}
String next() throws Exception {while (st == null || !st.hasMoreElements())st = new StringTokenizer(br.readLine());
return st.nextToken();}int nextInt() throws Exception {return Integer.parseInt(next());}long nextLong() throws Exception {
return Long.parseLong(next());}int[] readArray(int num) throws Exception {int arr[]=new int[num];
for(int i=0;i<num;i++)arr[i]=nextInt();return arr;}String nextLine() throws Exception {return br.readLine();
}} public static boolean power_of_two(int a){if((a&(a-1))==0){ return true;}return false;}
static boolean PS(double x){if (x >= 0) {double i= Math.sqrt(x);if(i%1!=0){
return false;}return ((i * i) == x);}return false;}public static int[] ia(int n){int ar[]=new int[n];
return ar;}public static long[] la(int n){long ar[]=new long[n];return ar;}
public static void print(int ans,int t){System.out.println("Case"+" "+"#"+t+":"+" "+ans);}
static long mod=1000000007;static int max=Integer.MIN_VALUE;static int min=Integer.MAX_VALUE;
public static void sort(long[] arr){//because Arrays.sort() uses quicksort which is dumb
//Collections.sort() uses merge sort
ArrayList<Long> ls = new ArrayList<Long>();for(long x: arr)ls.add(x);Collections.sort(ls);
for(int i=0; i < arr.length; i++)arr[i] = ls.get(i);}public static long fciel(long a, long b) {if (a == 0) return 0;return (a - 1) / b + 1;}
static boolean[] is_prime = new boolean[1000001];static ArrayList<Integer> list = new ArrayList<>();
static long n = 1000000;public static void sieve() {Arrays.fill(is_prime, true);
is_prime[0] = is_prime[1] = false;for (int i = 2; i * i <= n; i++) {
if (is_prime[i]) {for (int j = i * i; j <= n; j += i)is_prime[j] = false;}}for (int i = 2; i <= n; i++) {
if (is_prime[i]) {list.add(i);}}}
// ---------- NCR ---------- \
static int NC=100005;
static long inv[]=new long[NC];
static long fac_inv[]=new long[NC];
static long fac[]=new long[NC];public static void initialize()
{
long MOD=mod;
int i;
inv[1]=1;
for(i=2;i<=NC-2;i++)
inv[i]=(MOD-MOD/i)*inv[(int)MOD%i]%MOD;
fac[0]=fac[1]=1;
for(i=2;i<=NC-2;i++)
fac[i]=i*fac[i-1]%MOD;
fac_inv[0]=fac_inv[1]=1;
for(i=2;i<=NC-2;i++)
fac_inv[i]=inv[i]*fac_inv[i-1]%MOD;
}
public static long ncr(int n,int r)
{
long MOD=mod;
if(n<r) return 0;
return (fac[n]*fac_inv[r]%MOD)*fac_inv[n-r]%MOD;
}
// ---------- NCR ---------- \
// ---------- FACTORS -------- \
static int div[][] = new int[1000001][];
public static void factors()
{
int divCnt[] = new int[1000001];
for(int i = 1000000; i >= 1; --i) {
for(int j = i; j <= 1000000; j += i)
divCnt[j]++;
}
for(int i = 1; i <= 1000000; ++i)
div[i] = new int[divCnt[i]];
int ptr[] = new int[1000001];
for(int i = 1000000; i >= 1; --i) {
for(int j = i; j <= 1000000; j += i)
div[j][ptr[j]++] = i;
}
}
// ---------- FACTORS -------- \
// ------------- DSU ---------------\
static int par[]=new int[1000001];static int size[]=new int[1000001];
public static void make(int v){par[v]=v;size[v]++;}
public static void union(int a,int b){a=find(a);b=find(b);
if(a!=b){if(size[a]<size[b]){int temp=a;a=b;b=temp;}par[b]=a;
size[a]++;}}public static int find(int v)
{if(v==par[v]){return v;}return par[v]=find(par[v]);}
// ------------- DSU ---------------\
public static void main(String args[]) throws java.lang.Exception {
sc = new FastScanner();pw = new PrintWriter(System.out);StringBuilder s = new StringBuilder();
int t=sc.nextInt();
while(t-->0)
{
int n=sc.nextInt();
int ar[]=new int[n];
for(int i=0;i<n;i++)
{
ar[i]=sc.nextInt();
}
int b[]=new int[n];
for(int i=n-1;i>0;i-=2)
{
int x=Math.min(ar[i],ar[i-1]);
int y=Math.max(ar[i],ar[i-1]);
ar[i]=y;
ar[i-1]=x;
}
int f=0;
for(int i=1;i<n;i++)
{
if(ar[i]<ar[i-1])
{
f=1;
break;
}
}
s.append(f==0?"YES":"NO");
if(t>0)
{
s.append("\n");
}}
pw.print(s);pw.close();}}
| Java | ["3\n\n4\n\n3 1 5 3\n\n3\n\n3 2 1\n\n1\n\n7331"] | 2 seconds | ["YES\nNO\nYES"] | NoteIn the first test case, we can do the following for $$$a = [3, 1, 5, 3]$$$:Step $$$1$$$: $$$a$$$$$$[3, 1, 5, 3]$$$$$$\Rightarrow$$$$$$[3, 1, 5]$$$$$$\Rightarrow$$$$$$[3, 1]$$$$$$\Rightarrow$$$$$$[3]$$$$$$\Rightarrow$$$$$$[]$$$$$$b$$$$$$[]$$$$$$[\underline{3}]$$$$$$[3, \underline{5}]$$$$$$[3, \underline{1}, 5]$$$$$$[3, \underline{3}, 1, 5]$$$Step $$$2$$$: $$$b$$$$$$[3, 3, \underline{1}, 5]$$$$$$\Rightarrow$$$$$$[3, \underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{5}]$$$$$$\Rightarrow$$$$$$[]$$$$$$c$$$$$$[]$$$$$$[1]$$$$$$[1, 3]$$$$$$[1, 3, 3]$$$$$$[1, 3, 3, 5]$$$ As a result, array $$$c = [1, 3, 3, 5]$$$ and it's sorted. | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings"
] | 95b35c53028ed0565684713a93910860 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — the array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,200 | For each test, print YES (case-insensitive), if you can make array $$$c$$$ sorted in non-decreasing order. Otherwise, print NO (case-insensitive). | standard output | |
PASSED | 519debe1da06d6341089b78ea43c87f0 | train_107.jsonl | 1651502100 | You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps: Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements. Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements. Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order? | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
static BufferedReader br;
static PrintWriter out;
static StringTokenizer st;
public static void main (String[] args) throws java.lang.Exception
{
br=new BufferedReader(new InputStreamReader(System.in));
out=new PrintWriter(System.out);
int t=nextInt();
while(t-->0)
{
int n=nextInt();
int[] arr=new int[n];
int[] ar=new int[n];
readLine(arr,ar,n);
Arrays.sort(ar);
int f=0;
if((n&1)==0){
for(int i=0;i<n;i+=2)
{
if(((arr[i]!=ar[i])||(arr[i+1]!=ar[i+1]))&&((arr[i]!=ar[i+1])||(arr[i+1]!=ar[i])))
{
f++;
break;
}
}
if(f>0)
out.println("NO");
else
out.println("YES");
}
else
{
f=0;
if(arr[0]==ar[0])
{
for(int i=1;i<n;i+=2)
{
if(((arr[i]!=ar[i])||(arr[i+1]!=ar[i+1]))&&((arr[i]!=ar[i+1])||(arr[i+1]!=ar[i])))
{
f++;
break;
}
}
}
else
f++;
if(f>0)
out.println("NO");
else
out.println("YES");
}
}
out.flush();
}
public static int nextInt()throws Exception
{
return Integer.parseInt(br.readLine());
}
public static long nextLong()throws Exception
{
//br=new BufferedReader(new InputStreamReader(System.in));
return Long.parseLong(br.readLine());
}
public static void readLine(int[] arr,int[] ar,int n)throws Exception
{
// br=new BufferedReader(new InputStreamReader(System.in));
st=new StringTokenizer(br.readLine());
for(int i=0;i<n;i++)
{
arr[i]=Integer.parseInt(st.nextToken());
ar[i]=arr[i];
}
}
public static void next()throws Exception
{
st=new StringTokenizer(br.readLine());
}
public static int readInt()throws Exception
{
return Integer.parseInt(st.nextToken());
}
public static long readLong()throws Exception
{
return Long.parseLong(st.nextToken());
}
}
| Java | ["3\n\n4\n\n3 1 5 3\n\n3\n\n3 2 1\n\n1\n\n7331"] | 2 seconds | ["YES\nNO\nYES"] | NoteIn the first test case, we can do the following for $$$a = [3, 1, 5, 3]$$$:Step $$$1$$$: $$$a$$$$$$[3, 1, 5, 3]$$$$$$\Rightarrow$$$$$$[3, 1, 5]$$$$$$\Rightarrow$$$$$$[3, 1]$$$$$$\Rightarrow$$$$$$[3]$$$$$$\Rightarrow$$$$$$[]$$$$$$b$$$$$$[]$$$$$$[\underline{3}]$$$$$$[3, \underline{5}]$$$$$$[3, \underline{1}, 5]$$$$$$[3, \underline{3}, 1, 5]$$$Step $$$2$$$: $$$b$$$$$$[3, 3, \underline{1}, 5]$$$$$$\Rightarrow$$$$$$[3, \underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{5}]$$$$$$\Rightarrow$$$$$$[]$$$$$$c$$$$$$[]$$$$$$[1]$$$$$$[1, 3]$$$$$$[1, 3, 3]$$$$$$[1, 3, 3, 5]$$$ As a result, array $$$c = [1, 3, 3, 5]$$$ and it's sorted. | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings"
] | 95b35c53028ed0565684713a93910860 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — the array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,200 | For each test, print YES (case-insensitive), if you can make array $$$c$$$ sorted in non-decreasing order. Otherwise, print NO (case-insensitive). | standard output | |
PASSED | 0abd21202089d401fd8c7f24024c64ca | train_107.jsonl | 1651502100 | You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps: Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements. Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements. Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.lang.*;
public class Solution{
static int mod=(int)1e9+7;
static int mod1=998244353;
static FastScanner sc = new FastScanner();
public static void solve(){
int n=sc.nextInt();
int[] a=sc.readArray(n);
if ((n%2)==0) {
int[] b=a.clone();
for (int i=0;i<=n-2;i+=2) {
if (b[i]>b[i+1]) {
int temp=b[i];
b[i]=b[i+1];
b[i+1]=temp;
}
}
for (int i=0;i<n-1;i++) {
if (b[i]>b[i+1]) {
System.out.println("NO");
return;
}
}
System.out.println("YES");
}else{
int[] b=a.clone();
for (int i=1;i<=n-2;i+=2) {
if (b[i]>b[i+1]) {
int temp=b[i];
b[i]=b[i+1];
b[i+1]=temp;
}
}
for (int i=0;i<n-1;i++) {
if (b[i]>b[i+1]) {
System.out.println("NO");
return;
}
}
System.out.println("YES");
}
}
public static void main(String[] args) {
int t = sc.nextInt();
outer: for (int tt = 0; tt < t; tt++) {
solve();
}
}
static boolean isSubSequence(String str1, String str2,
int m, int n)
{
int j = 0;
for (int i = 0; i < n && j < m; i++)
if (str1.charAt(j) == str2.charAt(i))
j++;
return (j == m);
}
static int reverseDigits(int num)
{
int rev_num = 0;
while (num > 0) {
rev_num = rev_num * 10 + num % 10;
num = num / 10;
}
return rev_num;
}
/* Function to check if n is Palindrome*/
static boolean isPalindrome(int n)
{
// get the reverse of n
int rev_n = reverseDigits(n);
// Check if rev_n and n are same or not.
if (rev_n == n)
return true;
else
return false;
}
static boolean isPrime(int n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static int[] LPS(String s){
int[] lps=new int[s.length()];
int i=0,j=1;
while (j<s.length()) {
if(s.charAt(i)==s.charAt(j)){
lps[j]=i+1;
i++;
j++;
continue;
}else{
if (i==0) {
j++;
continue;
}
i=lps[i-1];
while(s.charAt(i)!=s.charAt(j) && i!=0) {
i=lps[i-1];
}
if(s.charAt(i)==s.charAt(j)){
lps[j]=i+1;
i++;
}
j++;
}
}
return lps;
}
static long getPairsCount(int n, double sum,int[] arr)
{
HashMap<Double, Integer> hm = new HashMap<>();
for (int i = 0; i < n; i++) {
if (!hm.containsKey((double)arr[i]))
hm.put((double)arr[i], 0);
hm.put((double)arr[i], hm.get((double)arr[i]) + 1);
}
long twice_count = 0;
for (int i = 0; i < n; i++) {
if (hm.get(sum - arr[i]) != null)
twice_count += hm.get(sum - arr[i]);
if (sum - (double)arr[i] == (double)arr[i])
twice_count--;
}
return twice_count / 2l;
}
static boolean[] sieveOfEratosthenes(int n)
{
boolean prime[] = new boolean[n + 1];
for (int i = 0; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++)
{
if (prime[p] == true)
{
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
prime[1]=false;
return prime;
}
static long power(long x, long y, long p)
{
long res = 1l;
x = x % p;
if (x == 0)
return 0;
while (y > 0)
{
if ((y & 1) != 0)
res = (res * x) % p;
y>>=1;
x = (x * x) % p;
}
return res;
}
public static int log2(int N)
{
int result = (int)(Math.log(N) / Math.log(2));
return result;
}
////////////////////////////////////////////////////////////////////////////////////
////////////////////DO NOT READ AFTER THIS LINE //////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
static long modFact(int n,
int p)
{
if (n >= p)
return 0;
long result = 1l;
for (int i = 2; i <= n; i++)
result = (result * i) % p;
return result;
}
static boolean isPalindrom(char[] arr, int i, int j) {
boolean ok = true;
while (i <= j) {
if (arr[i] != arr[j]) {
ok = false;
break;
}
i++;
j--;
}
return ok;
}
static int max(int a, int b) {
return Math.max(a, b);
}
static int min(int a, int b) {
return Math.min(a, b);
}
static long max(long a, long b) {
return Math.max(a, b);
}
static long min(long a, long b) {
return Math.min(a, b);
}
static int abs(int a) {
return Math.abs(a);
}
static long abs(long a) {
return Math.abs(a);
}
static void swap(long arr[], int i, int j) {
long temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static void swap(int arr[], int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static int maxArr(int arr[]) {
int maxi = Integer.MIN_VALUE;
for (int x : arr)
maxi = max(maxi, x);
return maxi;
}
static int minArr(int arr[]) {
int mini = Integer.MAX_VALUE;
for (int x : arr)
mini = min(mini, x);
return mini;
}
static long maxArr(long arr[]) {
long maxi = Long.MIN_VALUE;
for (long x : arr)
maxi = max(maxi, x);
return maxi;
}
static long minArr(long arr[]) {
long mini = Long.MAX_VALUE;
for (long x : arr)
mini = min(mini, x);
return mini;
}
static int lcm(int a,int b){
return (int)(((long)a*b)/(long)gcd(a,b));
}
static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static void ruffleSort(int[] a) {
int n = a.length;
Random r = new Random();
for (int i = 0; i < a.length; i++) {
int oi = r.nextInt(n);
int temp = a[i];
a[i] = a[oi];
a[oi] = temp;
}
Arrays.sort(a);
}
public static int binarySearch(int a[], int target) {
int left = 0;
int right = a.length - 1;
int mid = (left + right) / 2;
int i = 0;
while (left <= right) {
if (a[mid] <= target) {
i = mid + 1;
left = mid + 1;
} else {
right = mid - 1;
}
mid = (left + right) / 2;
}
return i-1;
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
int[][] read2dArray(int n, int m) {
int arr[][] = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = nextInt();
}
}
return arr;
}
ArrayList<Integer> readArrayList(int n) {
ArrayList<Integer> arr = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
int a = nextInt();
arr.add(a);
}
return arr;
}
long nextLong() {
return Long.parseLong(next());
}
}
static class Pair {
int val;
long coins;
Pair(int val,long coins) {
this.val=val;
this.coins=coins;
}
}
} | Java | ["3\n\n4\n\n3 1 5 3\n\n3\n\n3 2 1\n\n1\n\n7331"] | 2 seconds | ["YES\nNO\nYES"] | NoteIn the first test case, we can do the following for $$$a = [3, 1, 5, 3]$$$:Step $$$1$$$: $$$a$$$$$$[3, 1, 5, 3]$$$$$$\Rightarrow$$$$$$[3, 1, 5]$$$$$$\Rightarrow$$$$$$[3, 1]$$$$$$\Rightarrow$$$$$$[3]$$$$$$\Rightarrow$$$$$$[]$$$$$$b$$$$$$[]$$$$$$[\underline{3}]$$$$$$[3, \underline{5}]$$$$$$[3, \underline{1}, 5]$$$$$$[3, \underline{3}, 1, 5]$$$Step $$$2$$$: $$$b$$$$$$[3, 3, \underline{1}, 5]$$$$$$\Rightarrow$$$$$$[3, \underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{5}]$$$$$$\Rightarrow$$$$$$[]$$$$$$c$$$$$$[]$$$$$$[1]$$$$$$[1, 3]$$$$$$[1, 3, 3]$$$$$$[1, 3, 3, 5]$$$ As a result, array $$$c = [1, 3, 3, 5]$$$ and it's sorted. | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings"
] | 95b35c53028ed0565684713a93910860 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — the array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,200 | For each test, print YES (case-insensitive), if you can make array $$$c$$$ sorted in non-decreasing order. Otherwise, print NO (case-insensitive). | standard output | |
PASSED | d35337ed59d40ca443b1a1b92a6e6102 | train_107.jsonl | 1651502100 | You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps: Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements. Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements. Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order? | 256 megabytes | import java.io.BufferedReader;
import java.math.BigInteger;
import java.util.*;
import static java.lang.System.out;
// Name: Tastan Yernar && Email: 210103376@stu.sdu.edu.kz//
public class Round_780_Div_3 {
static Scanner str = new Scanner(System.in);
static ArrayList<Integer> list;
final int mod = 1000000007;
public static void main(String[] args) {
long T = str.nextLong();
while (T-- > 0) {
solve();
}
}
static void solve() {
int n = str.nextInt();
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = str.nextInt();
}
for (int i = n - 1; i > 0; i -= 2) {
if (a[i] < a[i - 1]) {
int temp = a[i];
a[i] = a[i - 1];
a[i - 1] = temp;
}
}
boolean ans = true;
for (int i = 0; i < n - 1; i++) {
if (a[i] > a[i + 1]) {
ans = false;
}
}
out.println(ans ? "YES" : "NO");
}
}
| Java | ["3\n\n4\n\n3 1 5 3\n\n3\n\n3 2 1\n\n1\n\n7331"] | 2 seconds | ["YES\nNO\nYES"] | NoteIn the first test case, we can do the following for $$$a = [3, 1, 5, 3]$$$:Step $$$1$$$: $$$a$$$$$$[3, 1, 5, 3]$$$$$$\Rightarrow$$$$$$[3, 1, 5]$$$$$$\Rightarrow$$$$$$[3, 1]$$$$$$\Rightarrow$$$$$$[3]$$$$$$\Rightarrow$$$$$$[]$$$$$$b$$$$$$[]$$$$$$[\underline{3}]$$$$$$[3, \underline{5}]$$$$$$[3, \underline{1}, 5]$$$$$$[3, \underline{3}, 1, 5]$$$Step $$$2$$$: $$$b$$$$$$[3, 3, \underline{1}, 5]$$$$$$\Rightarrow$$$$$$[3, \underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{5}]$$$$$$\Rightarrow$$$$$$[]$$$$$$c$$$$$$[]$$$$$$[1]$$$$$$[1, 3]$$$$$$[1, 3, 3]$$$$$$[1, 3, 3, 5]$$$ As a result, array $$$c = [1, 3, 3, 5]$$$ and it's sorted. | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings"
] | 95b35c53028ed0565684713a93910860 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — the array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,200 | For each test, print YES (case-insensitive), if you can make array $$$c$$$ sorted in non-decreasing order. Otherwise, print NO (case-insensitive). | standard output | |
PASSED | 85a5b8acdc5836423bee76f321532cdb | train_107.jsonl | 1651502100 | You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps: Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements. Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements. Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order? | 256 megabytes |
import java.util.*;
import java.io.*;
public class A{
public static void main(String[] args) throws IOException,NumberFormatException{
try {
FastScanner sc=new FastScanner();
PrintWriter out=new PrintWriter(System.out);
int t=sc.nextInt();
outer:while(t-->0) {
int n=sc.nextInt();
int a[]=sc.readArray(n);
int b[]=new int[n];
for(int i=0;i<a.length;i++) {
b[i]=a[i];
}
Arrays.sort(a);
int i=0;
if(a.length%2!=0) {
i++;
}
for(;i<a.length;i+=2) {
if(b[i]>b[i+1]) {
int temp=b[i];
b[i]=b[i+1];
b[i+1]=temp;
}
}
for(int j=0;j<a.length;j++) {
if(a[j]!=b[j]) {
out.println("NO");
continue outer;
}
}
out.println("YES");
}
out.close();
}
catch(Exception e) {
return ;
}
}
public static int GCD(int a, int b) {
if(b==0) {
return a;
}
else {
return GCD(b,a%b);
}
}
public static boolean isPrime(int n) {
if(n==0||n==1) {
return false;
}
for(int i=2;i*i<=n;i++) {
if(n%i==0) {
return false;
}
}
return true;
}
public static class Pair<L,R> {
private L l;
private R r;
public Pair(L l, R r){
this.l = l;
this.r = r;
}
public L getL(){ return l; }
public R getR(){ return r; }
public void setL(L l){ this.l = l; }
public void setR(R r){ this.r = r; }
}
// public static void djikstra(int a[],ArrayList<Node> adj[] ,int src,int n) {
//
// Arrays.fill(a, Integer.MAX_VALUE);
// a[src]=0;
// PriorityQueue<Node> pq=new PriorityQueue<Node>(n, new Node());
// pq.add(new Node(src,0));
//
// while(!pq.isEmpty()) {
// Node node=pq.remove();
// int v=node.getV();
// int weight=node.getWeight();
// for(Node it: adj[v]) {
// if(it.weight+weight<a[it.getV()]) {
// a[it.getV()]=it.weight+weight;
// pq.add(new Node(it.getV(),a[it.getV()]));
// }
// }
// }
// }
static final Random random=new Random();
static void ruffleSort(int[] a) {
int n=a.length;
for(int i=0;i<n;i++) {
int oi=random.nextInt(n),temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
public static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long[] readLongArray(int n) {
long[] a=new long[n];
for(int i=0; i<n ; i++) a[i]=nextLong();
return a;
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
| Java | ["3\n\n4\n\n3 1 5 3\n\n3\n\n3 2 1\n\n1\n\n7331"] | 2 seconds | ["YES\nNO\nYES"] | NoteIn the first test case, we can do the following for $$$a = [3, 1, 5, 3]$$$:Step $$$1$$$: $$$a$$$$$$[3, 1, 5, 3]$$$$$$\Rightarrow$$$$$$[3, 1, 5]$$$$$$\Rightarrow$$$$$$[3, 1]$$$$$$\Rightarrow$$$$$$[3]$$$$$$\Rightarrow$$$$$$[]$$$$$$b$$$$$$[]$$$$$$[\underline{3}]$$$$$$[3, \underline{5}]$$$$$$[3, \underline{1}, 5]$$$$$$[3, \underline{3}, 1, 5]$$$Step $$$2$$$: $$$b$$$$$$[3, 3, \underline{1}, 5]$$$$$$\Rightarrow$$$$$$[3, \underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{5}]$$$$$$\Rightarrow$$$$$$[]$$$$$$c$$$$$$[]$$$$$$[1]$$$$$$[1, 3]$$$$$$[1, 3, 3]$$$$$$[1, 3, 3, 5]$$$ As a result, array $$$c = [1, 3, 3, 5]$$$ and it's sorted. | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings"
] | 95b35c53028ed0565684713a93910860 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — the array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,200 | For each test, print YES (case-insensitive), if you can make array $$$c$$$ sorted in non-decreasing order. Otherwise, print NO (case-insensitive). | standard output | |
PASSED | f770c0585fbe73a0020f4cbf38954d2c | train_107.jsonl | 1651502100 | You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps: Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements. Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements. Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order? | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class ABCSort {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
pls:
while (t-- > 0) {
int n = sc.nextInt();
int[] a = new int[n];
int[] b = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
b[i] = a[i];
}
Arrays.sort(a);
if (n % 2 == 0) {
for (int i = 0; i < n - 1; i+=2) {
if (a[i] != b[i]) {
int p = b[i];
b[i] = b[i + 1];
b[i + 1] = p;
if (!(a[i] == b[i] && a[i + 1] == b[i + 1])) {
System.out.println("NO");
continue pls;
}
} else {
if (a[i + 1] != b[i + 1]) {
System.out.println("NO");
continue pls;
}
}
}
} else {
if (a[0] != b[0]) {
System.out.println("NO");
continue;
} else {
for (int i = 1; i < n - 1; i+=2) {
if (a[i] != b[i]) {
int p = b[i];
b[i] = b[i + 1];
b[i + 1] = p;
if (!(a[i] == b[i] && a[i + 1] == b[i + 1])) {
System.out.println("NO");
continue pls;
}
} else {
if (a[i + 1] != b[i + 1]) {
System.out.println("NO");
continue pls;
}
}
}
}
}
System.out.println("YES");
}
}
} | Java | ["3\n\n4\n\n3 1 5 3\n\n3\n\n3 2 1\n\n1\n\n7331"] | 2 seconds | ["YES\nNO\nYES"] | NoteIn the first test case, we can do the following for $$$a = [3, 1, 5, 3]$$$:Step $$$1$$$: $$$a$$$$$$[3, 1, 5, 3]$$$$$$\Rightarrow$$$$$$[3, 1, 5]$$$$$$\Rightarrow$$$$$$[3, 1]$$$$$$\Rightarrow$$$$$$[3]$$$$$$\Rightarrow$$$$$$[]$$$$$$b$$$$$$[]$$$$$$[\underline{3}]$$$$$$[3, \underline{5}]$$$$$$[3, \underline{1}, 5]$$$$$$[3, \underline{3}, 1, 5]$$$Step $$$2$$$: $$$b$$$$$$[3, 3, \underline{1}, 5]$$$$$$\Rightarrow$$$$$$[3, \underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{5}]$$$$$$\Rightarrow$$$$$$[]$$$$$$c$$$$$$[]$$$$$$[1]$$$$$$[1, 3]$$$$$$[1, 3, 3]$$$$$$[1, 3, 3, 5]$$$ As a result, array $$$c = [1, 3, 3, 5]$$$ and it's sorted. | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings"
] | 95b35c53028ed0565684713a93910860 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — the array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,200 | For each test, print YES (case-insensitive), if you can make array $$$c$$$ sorted in non-decreasing order. Otherwise, print NO (case-insensitive). | standard output | |
PASSED | 1b923d037d9ec5c8728fb747030d47fc | train_107.jsonl | 1651502100 | You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps: Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements. Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements. Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
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 s = new FastReader();
int t = s.nextInt();
while (t-- > 0){
int n = s.nextInt();
int[] ar = new int[n];
for (int i = 0; i < n; i++){
ar[i] = s.nextInt();
}
for (int i = n-1; i >= 1; i -= 2){
if (ar[i-1] > ar[i]){
int temp = ar[i-1];
ar[i-1] = ar[i];
ar[i] = temp;
}
}
boolean flag = true;
for (int i = 0; i < n-1; i++){
if (ar[i] > ar[i+1]){
flag = false;
break;
}
}
if (flag) System.out.println("YES");
else System.out.println("NO");
}
}
} | Java | ["3\n\n4\n\n3 1 5 3\n\n3\n\n3 2 1\n\n1\n\n7331"] | 2 seconds | ["YES\nNO\nYES"] | NoteIn the first test case, we can do the following for $$$a = [3, 1, 5, 3]$$$:Step $$$1$$$: $$$a$$$$$$[3, 1, 5, 3]$$$$$$\Rightarrow$$$$$$[3, 1, 5]$$$$$$\Rightarrow$$$$$$[3, 1]$$$$$$\Rightarrow$$$$$$[3]$$$$$$\Rightarrow$$$$$$[]$$$$$$b$$$$$$[]$$$$$$[\underline{3}]$$$$$$[3, \underline{5}]$$$$$$[3, \underline{1}, 5]$$$$$$[3, \underline{3}, 1, 5]$$$Step $$$2$$$: $$$b$$$$$$[3, 3, \underline{1}, 5]$$$$$$\Rightarrow$$$$$$[3, \underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{5}]$$$$$$\Rightarrow$$$$$$[]$$$$$$c$$$$$$[]$$$$$$[1]$$$$$$[1, 3]$$$$$$[1, 3, 3]$$$$$$[1, 3, 3, 5]$$$ As a result, array $$$c = [1, 3, 3, 5]$$$ and it's sorted. | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings"
] | 95b35c53028ed0565684713a93910860 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — the array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,200 | For each test, print YES (case-insensitive), if you can make array $$$c$$$ sorted in non-decreasing order. Otherwise, print NO (case-insensitive). | standard output | |
PASSED | 3e919edbfb32b4994f49066928d05080 | train_107.jsonl | 1651502100 | You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps: Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements. Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements. Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order? | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static FastReader in=new FastReader();
static final Random random=new Random();
static long mod=1000000007L;
static HashMap<String,Integer>map=new HashMap<>();
public static void main(String args[]) throws IOException {
int t=in.nextInt();
while(t-->0){
int n=in.nextInt();
int arr[]=in.readintarray(n);
int arr1[]=new int[n];
int c=0;
for(int x:arr){
arr1[c++]=x;
}
for(int i=n-2;i>=0;i-=2){
if(arr[i]>arr[i+1]){
int temp=arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
}
Arrays.sort(arr1);
boolean flag=true;
for(int i=0;i<n;i++){
if(arr[i]!=arr1[i]){flag=false;
break;}
}
if(flag)print("YES");
else print("NO");
}
}
static int max(int a, int b)
{
if(a<b)
return b;
return a;
}
static void ruffleSort(int[] a) {
int n=a.length;
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static < E > void print(E res)
{
System.out.println(res);
}
static int gcd(int a,int b)
{
if(b==0)
{
return a;
}
return gcd(b,a%b);
}
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
static int abs(int a)
{
if(a<0)
return -1*a;
return a;
}
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;
}
int [] readintarray(int n) {
int res [] = new int [n];
for(int i = 0; i<n; i++)res[i] = nextInt();
return res;
}
long [] readlongarray(int n) {
long res [] = new long [n];
for(int i = 0; i<n; i++)res[i] = nextLong();
return res;
}
}
}
| Java | ["3\n\n4\n\n3 1 5 3\n\n3\n\n3 2 1\n\n1\n\n7331"] | 2 seconds | ["YES\nNO\nYES"] | NoteIn the first test case, we can do the following for $$$a = [3, 1, 5, 3]$$$:Step $$$1$$$: $$$a$$$$$$[3, 1, 5, 3]$$$$$$\Rightarrow$$$$$$[3, 1, 5]$$$$$$\Rightarrow$$$$$$[3, 1]$$$$$$\Rightarrow$$$$$$[3]$$$$$$\Rightarrow$$$$$$[]$$$$$$b$$$$$$[]$$$$$$[\underline{3}]$$$$$$[3, \underline{5}]$$$$$$[3, \underline{1}, 5]$$$$$$[3, \underline{3}, 1, 5]$$$Step $$$2$$$: $$$b$$$$$$[3, 3, \underline{1}, 5]$$$$$$\Rightarrow$$$$$$[3, \underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{5}]$$$$$$\Rightarrow$$$$$$[]$$$$$$c$$$$$$[]$$$$$$[1]$$$$$$[1, 3]$$$$$$[1, 3, 3]$$$$$$[1, 3, 3, 5]$$$ As a result, array $$$c = [1, 3, 3, 5]$$$ and it's sorted. | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings"
] | 95b35c53028ed0565684713a93910860 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — the array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,200 | For each test, print YES (case-insensitive), if you can make array $$$c$$$ sorted in non-decreasing order. Otherwise, print NO (case-insensitive). | standard output | |
PASSED | 56f4ef3e84569ef487e6155581a78ae2 | train_107.jsonl | 1651502100 | You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps: Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements. Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements. Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order? | 256 megabytes | /*
AUTHOR-> HARSHIT AGGARWAL
CODEFORCES HANDLE-> @harshit_agg
FROM-> MAHARAJA AGRASEN INSTITUE OF TECHNOLOGY
>> YOU CAN DO THIS <<
*/
import java.util.*;
import java.io.*;
public class ABCsort {
public static void main(String[] args) throws Exception {
int t = scn.nextInt();
while (t-- > 0) {
solver();
}
}
public static void solver() {
int n = scn.nextInt();
int[] arr = nextIntArray(n);
if(n <= 2 ){
System.out.println("YES");return;}
if(arr.length % 2 == 0){
int prevmax = Integer.MIN_VALUE;
int prevmin = Integer.MIN_VALUE;
int currmax = Integer.MIN_VALUE;
int currmin = Integer.MIN_VALUE;
for(int i = 0 ; i < n; i+=2){
currmax = Math.max(arr[i], arr[i+1]);
currmin = Math.min(arr[i], arr[i+1]);
if(currmin < prevmax){
System.out.println("NO");
return;
}
prevmax = currmax;
prevmin = currmin;
}
}else{
int prevmax = Integer.MIN_VALUE;
int prevmin = Integer.MIN_VALUE;
int currmax = Integer.MIN_VALUE;
int currmin = Integer.MIN_VALUE;
int wholemin = Integer.MAX_VALUE;
int wholemax = Integer.MIN_VALUE;
for(int i = 1 ; i < n; i+=2){
currmax = Math.max(arr[i], arr[i+1]);
currmin = Math.min(arr[i], arr[i+1]);
wholemax = Math.max(Math.max(arr[i],arr[i+1]),wholemax);
wholemin = Math.min(Math.min(arr[i],arr[i+1]),wholemin);
if(currmin < prevmax){
System.out.println("NO");
return;
}
prevmax = currmax;
prevmin = currmin;
}
if(arr[0] == wholemax && wholemax != wholemin){
System.out.println("No");
return;
}
if(arr[0] > wholemin){
System.out.println("NO");
return;
}
}
System.out.println("YES");
}
//-------------------------------- HO JA BHAI ----------------------------------------------------
/* code ends here*/
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx U T I L I T I E S xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
public static class Debug { public static final boolean LOCAL = System.getProperty("LOCAL")==null; private static <T> String ts(T t) { if(t==null) { return "null"; } try { return ts((Iterable) t); }catch(ClassCastException e) { if(t instanceof int[]) { String s = Arrays.toString((int[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof long[]) { String s = Arrays.toString((long[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof char[]) { String s = Arrays.toString((char[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof double[]) { String s = Arrays.toString((double[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof boolean[]) { String s = Arrays.toString((boolean[]) t); return "{"+s.substring(1, s.length()-1)+"}"; } try { return ts((Object[]) t); }catch(ClassCastException e1) { return t.toString(); } } } private static <T> String ts(T[] arr) { StringBuilder ret = new StringBuilder(); ret.append("{"); boolean first = true; for(T t: arr) { if(!first) { ret.append(", "); } first = false; ret.append(ts(t)); } ret.append("}"); return ret.toString(); } private static <T> String ts(Iterable<T> iter) { StringBuilder ret = new StringBuilder(); ret.append("{"); boolean first = true; for(T t: iter) { if(!first) { ret.append(", "); } first = false; ret.append(ts(t)); } ret.append("}"); return ret.toString(); } public static void dbg(Object... o) { if(LOCAL) { System.err.print("Line #"+Thread.currentThread().getStackTrace()[2].getLineNumber()+": ["); for(int i = 0; i<o.length; i++) { if(i!=0) { System.err.print(", "); } System.err.print(ts(o[i])); } System.err.println("]"); } } }
static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { try { br = new BufferedReader(new FileReader("input.txt")); PrintStream out = new PrintStream(new FileOutputStream("output.txt")); System.setOut(out); } catch (Exception e) { 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()); } float nextFloat() { return Float.parseFloat(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
static int INF = (int) 1e9 + 7; // static int INF = 998244353;
static int MAX = Integer.MAX_VALUE; // static int MAX = 2147483647
static int MIN = Integer.MIN_VALUE; // static int MIN = -2147483647
static class Pair implements Comparable<Pair> { int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } public int compareTo(Pair o) { return this.first- o.first; } }
static class LongPair { long first; long second; LongPair(long a, long b) { this.first = a; this.second = b; } }
public static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); }
public static int LowerBound(long a[], long x) { /* x is the key or target value */int l = -1, r = a.length; while (l + 1 < r) { int m = (l + r) >>> 1; if (a[m] >= x) r = m; else l = m; } return r; }
public static int LowerBound(int a[], int x) { /* x is the key or target value */int l = -1, r = a.length; while (l + 1 < r) { int m = (l + r) >>> 1; if (a[m] >= x) r = m; else l = m; } return r; }
static int LowerBoundList(ArrayList<Integer> a, int x) { /* x is the key or target value */int l = -1, r = a.size(); while (l + 1 < r) { int m = (l + r) >>> 1; if (a.get(m) >= x) r = m; else l = m; } return r; }
static boolean[] prime; public static void sieveOfEratosthenes(int n) { prime = new boolean[n + 1]; for (int i = 0; i < n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { if (prime[p] == true) { for (int i = p * p; i <= n; i += p) prime[i] = false; } } }
public static int UpperBound(long a[], long x) {/* x is the key or target value */int l = -1, r = a.length; while (l + 1 < r) { int m = (l + r) >>> 1; if (a[m] <= x) l = m; else r = m; } return l + 1; }
public static int UpperBound(int a[], int x) {/* x is the key or target value */int l = -1, r = a.length; while (l + 1 < r) { int m = (l + r) >>> 1; if (a[m] <= x) l = m; else r = m; } return l + 1; }
public static long lcm(long a, long b) { return (a * b) / gcd(a, b); }
public static void swap(int[] arr, int i, int j) { if (i != j) { arr[i] ^= arr[j]; arr[j] ^= arr[i]; arr[i] ^= arr[j]; } }
public static long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = scn.nextLong(); return a; }
public static int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = scn.nextInt(); } return a; }
public int[][] nextIntMatrix(int n, int m) { int[][] grid = new int[n][m]; for (int i = 0; i < n; i++) { grid[i] = nextIntArray(m); } return grid; }
public static int smallest_divisor(int n) { int i; for (i = 2; i <= Math.sqrt(n); ++i) { if (n % i == 0) { return i; } } return n; }
public static FastReader scn = new FastReader();
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
}
| Java | ["3\n\n4\n\n3 1 5 3\n\n3\n\n3 2 1\n\n1\n\n7331"] | 2 seconds | ["YES\nNO\nYES"] | NoteIn the first test case, we can do the following for $$$a = [3, 1, 5, 3]$$$:Step $$$1$$$: $$$a$$$$$$[3, 1, 5, 3]$$$$$$\Rightarrow$$$$$$[3, 1, 5]$$$$$$\Rightarrow$$$$$$[3, 1]$$$$$$\Rightarrow$$$$$$[3]$$$$$$\Rightarrow$$$$$$[]$$$$$$b$$$$$$[]$$$$$$[\underline{3}]$$$$$$[3, \underline{5}]$$$$$$[3, \underline{1}, 5]$$$$$$[3, \underline{3}, 1, 5]$$$Step $$$2$$$: $$$b$$$$$$[3, 3, \underline{1}, 5]$$$$$$\Rightarrow$$$$$$[3, \underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{5}]$$$$$$\Rightarrow$$$$$$[]$$$$$$c$$$$$$[]$$$$$$[1]$$$$$$[1, 3]$$$$$$[1, 3, 3]$$$$$$[1, 3, 3, 5]$$$ As a result, array $$$c = [1, 3, 3, 5]$$$ and it's sorted. | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings"
] | 95b35c53028ed0565684713a93910860 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — the array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,200 | For each test, print YES (case-insensitive), if you can make array $$$c$$$ sorted in non-decreasing order. Otherwise, print NO (case-insensitive). | standard output | |
PASSED | fb8c121ea03195512cbe48a0898a76be | train_107.jsonl | 1651502100 | You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps: Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements. Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements. Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order? | 256 megabytes | import java.io.*;
import java.util.Arrays;
public class CodeJam {
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
while(t-- > 0) {
int n = Integer.parseInt(br.readLine());
String[] in = br.readLine().split(" ");
int[] arr = new int[n];
int[] sec = new int[n];
for(int i = 0; i < n ; i++) {
arr[i] = Integer.parseInt(in[i]);
sec[i] = Integer.parseInt(in[i]);
}
for(int i = n-1; i > 0; i -= 2) {
if(arr[i] < arr[i-1]) {
int temp = arr[i-1];
arr[i-1] = arr[i];
arr[i] = temp;
}
}
Arrays.sort(sec);
boolean res = true;
for(int i = 0; i < n; i++) {
if(arr[i] != sec[i]) {
res = false;
break;
}
}
if(n == 1 || res == true) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
}
| Java | ["3\n\n4\n\n3 1 5 3\n\n3\n\n3 2 1\n\n1\n\n7331"] | 2 seconds | ["YES\nNO\nYES"] | NoteIn the first test case, we can do the following for $$$a = [3, 1, 5, 3]$$$:Step $$$1$$$: $$$a$$$$$$[3, 1, 5, 3]$$$$$$\Rightarrow$$$$$$[3, 1, 5]$$$$$$\Rightarrow$$$$$$[3, 1]$$$$$$\Rightarrow$$$$$$[3]$$$$$$\Rightarrow$$$$$$[]$$$$$$b$$$$$$[]$$$$$$[\underline{3}]$$$$$$[3, \underline{5}]$$$$$$[3, \underline{1}, 5]$$$$$$[3, \underline{3}, 1, 5]$$$Step $$$2$$$: $$$b$$$$$$[3, 3, \underline{1}, 5]$$$$$$\Rightarrow$$$$$$[3, \underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{5}]$$$$$$\Rightarrow$$$$$$[]$$$$$$c$$$$$$[]$$$$$$[1]$$$$$$[1, 3]$$$$$$[1, 3, 3]$$$$$$[1, 3, 3, 5]$$$ As a result, array $$$c = [1, 3, 3, 5]$$$ and it's sorted. | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings"
] | 95b35c53028ed0565684713a93910860 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — the array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,200 | For each test, print YES (case-insensitive), if you can make array $$$c$$$ sorted in non-decreasing order. Otherwise, print NO (case-insensitive). | standard output | |
PASSED | ec22181dcda00be0a6c2c86187530ce0 | train_107.jsonl | 1651502100 | You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps: Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements. Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements. Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order? | 256 megabytes | /*
Rating: 1378
Date: 02-05-2022
Time: 20-34-35
Author: Kartik Papney
Linkedin: https://www.linkedin.com/in/kartik-papney-4951161a6/
Leetcode: https://leetcode.com/kartikpapney/
Codechef: https://www.codechef.com/users/kartikpapney
----------------------------Jai Shree Ram----------------------------
*/
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class D_A_B_C_Sort {
public static boolean isSorted(ArrayList<Integer> arr) {
for(int i=1; i<arr.size(); i++) {
if(arr.get(i) < arr.get(i-1)) return false;
}
return true;
}
public static void s() {
int n = sc.nextInt();
int[] arr = sc.readArray(n);
int[] brr = new int[n];
int idx = 0;
for(int i=0; i<brr.length; i++) {
brr[i] = arr[i];
}
Functions.sort(brr);
Deque<Integer> st = new ArrayDeque<>();
for(int val : arr) st.addLast(val);
while(st.size() != 0) {
if(st.size() %2 == 1) {
if(brr[idx] != st.peek()) {
p.writeln("NO");
return;
}
st.removeFirst();
} else {
int a = st.removeFirst();
int b = st.removeFirst();
if(a == brr[idx]) {
st.addFirst(b);
} else if(b == brr[idx]) {
st.addFirst(a);
} else {
p.writeln("NO");
return;
}
}
idx++;
}
p.writeln("YES");
}
public static void main(String[] args) {
int t = 1;
t = sc.nextInt();
while (t-- != 0) {
s();
}
p.print();
}
public static boolean debug = false;
static void debug(String st) {
if(debug) p.writeln(st);
}
static final Integer MOD = (int) 1e9 + 7;
static final FastReader sc = new FastReader();
static final Print p = new Print();
static class Functions {
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 int max(int... a) {
int max = Integer.MIN_VALUE;
for (int val : a) max = Math.max(val, max);
return max;
}
static int min(int... a) {
int min = Integer.MAX_VALUE;
for (int val : a) min = Math.min(val, min);
return min;
}
static long min(long... a) {
long min = Long.MAX_VALUE;
for (long val : a) min = Math.min(val, min);
return min;
}
static long max(long... a) {
long max = Long.MIN_VALUE;
for (long val : a) max = Math.max(val, max);
return max;
}
static long sum(long... a) {
long sum = 0;
for (long val : a) sum += val;
return sum;
}
static int sum(int... a) {
int sum = 0;
for (int val : a) sum += val;
return sum;
}
public static long mod_add(long a, long b) {
return (a % MOD + b % MOD + MOD) % MOD;
}
public static long pow(long a, long b) {
long res = 1;
while (b > 0) {
if ((b & 1) != 0)
res = mod_mul(res, a);
a = mod_mul(a, a);
b >>= 1;
}
return res;
}
public static long mod_mul(long a, long b) {
long res = 0;
a %= MOD;
while (b > 0) {
if ((b & 1) > 0) {
res = mod_add(res, a);
}
a = (2 * a) % MOD;
b >>= 1;
}
return res;
}
public static long gcd(long a, long b) {
if (a == 0) return b;
return gcd(b % a, a);
}
public static long factorial(long n) {
long res = 1;
for (int i = 1; i <= n; i++) {
res = (i % MOD * res % MOD) % MOD;
}
return res;
}
public static int count(int[] arr, int x) {
int count = 0;
for (int val : arr) if (val == x) count++;
return count;
}
public static ArrayList<Integer> generatePrimes(int n) {
boolean[] primes = new boolean[n];
for (int i = 2; i < primes.length; i++) primes[i] = true;
for (int i = 2; i < primes.length; i++) {
if (primes[i]) {
for (int j = i * i; j < primes.length; j += i) {
primes[j] = false;
}
}
}
ArrayList<Integer> arr = new ArrayList<>();
for (int i = 0; i < primes.length; i++) {
if (primes[i]) arr.add(i);
}
return arr;
}
}
static class Print {
StringBuffer strb = new StringBuffer();
public void write(Object str) {
strb.append(str);
}
public void writes(Object str) {
char c = ' ';
strb.append(str).append(c);
}
public void writeln(Object str) {
char c = '\n';
strb.append(str).append(c);
}
public void writeln() {
char c = '\n';
strb.append(c);
}
public void yes() {
char c = '\n';
writeln("YES");
}
public void no() {
writeln("NO");
}
public void writes(int... arr) {
for (int val : arr) {
write(val);
write(' ');
}
}
public void writes(long... arr) {
for (long val : arr) {
write(val);
write(' ');
}
}
public void writeln(int... arr) {
for (int val : arr) {
writeln(val);
}
}
public void print() {
System.out.print(strb);
}
public void println() {
System.out.println(strb);
}
}
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());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
long[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
double[] readArrayDouble(int n) {
double[] a = new double[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
String nextLine() {
String str = new String();
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["3\n\n4\n\n3 1 5 3\n\n3\n\n3 2 1\n\n1\n\n7331"] | 2 seconds | ["YES\nNO\nYES"] | NoteIn the first test case, we can do the following for $$$a = [3, 1, 5, 3]$$$:Step $$$1$$$: $$$a$$$$$$[3, 1, 5, 3]$$$$$$\Rightarrow$$$$$$[3, 1, 5]$$$$$$\Rightarrow$$$$$$[3, 1]$$$$$$\Rightarrow$$$$$$[3]$$$$$$\Rightarrow$$$$$$[]$$$$$$b$$$$$$[]$$$$$$[\underline{3}]$$$$$$[3, \underline{5}]$$$$$$[3, \underline{1}, 5]$$$$$$[3, \underline{3}, 1, 5]$$$Step $$$2$$$: $$$b$$$$$$[3, 3, \underline{1}, 5]$$$$$$\Rightarrow$$$$$$[3, \underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{5}]$$$$$$\Rightarrow$$$$$$[]$$$$$$c$$$$$$[]$$$$$$[1]$$$$$$[1, 3]$$$$$$[1, 3, 3]$$$$$$[1, 3, 3, 5]$$$ As a result, array $$$c = [1, 3, 3, 5]$$$ and it's sorted. | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings"
] | 95b35c53028ed0565684713a93910860 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — the array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,200 | For each test, print YES (case-insensitive), if you can make array $$$c$$$ sorted in non-decreasing order. Otherwise, print NO (case-insensitive). | standard output | |
PASSED | f9855accceb3b69a2b6fd3b59e99a05b | train_107.jsonl | 1651502100 | You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps: Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements. Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements. Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order? | 256 megabytes | import java.lang.*;
import java.io.*;
import java.util.*;
public class codeforces {
static int max = Integer.MAX_VALUE, min = Integer.MIN_VALUE;
long maxl = Long.MAX_VALUE, minl = Long.MIN_VALUE;
static PrintWriter pw = new PrintWriter(System.out);
static StringBuilder sb = new StringBuilder();
static int parent[] = new int[100001];
static int mod = 1000000007;
static boolean b1 = true;
public static void main(String[] args) throws IOException {
// if (System.getProperty("ONLINE_JUDGE") == null) {
// PrintStream ps = new PrintStream(new File("output.txt"));
// InputStream is = new FileInputStream("input.txt");
// System.setIn(is);
// System.setOut(ps);
FastScanner sc = new FastScanner();
int ttt = sc.nextInt();
for (int tt = 1; tt <= ttt; tt++) {
int n = sc.nextInt();
int ar[] = new int[n];
for (int i = 0; i < n; i++)
ar[i] = sc.nextInt();
if (n == 1 || n == 2)
System.out.println("YES");
else {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
if ((n - i) % 2 == 0) {
if (ar[i] > ar[i + 1]) {
a[i] = ar[i + 1];
a[i + 1] = ar[i];
} else {
a[i] = ar[i];
a[i + 1] = ar[i + 1];
}
i++;
} else {
a[i] = ar[i];
}
}
Arrays.sort(ar);
if (Arrays.equals(ar, a))
System.out.println("YES");
else
System.out.println("NO");
}
// }
}
}
static int ceil(int x, int y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
static long ceil(long x, long y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
public static boolean checkPalindrome(int n) {
int v = 0;
int n1 = n;
while (n > 0) {
v = v * 10 + n % 10;
n = n / 10;
}
if (n1 == v)
return true;
else
return false;
}
public static int lis(int arr[], int n) {
int lis[] = new int[n];
int i, j, max = 0;
/* Initialize LIS values for all indexes */
for (i = 0; i < n; i++)
lis[i] = 1;
/*
* Compute optimized LIS values in
* bottom up manner
*/
for (i = 1; i < n; i++)
for (j = 0; j < i; j++)
if (arr[i] > arr[j] && lis[i] < lis[j] + 1)
lis[i] = lis[j] + 1;
/* Pick maximum of all LIS values */
for (i = 0; i < n; i++)
if (max < lis[i])
max = lis[i];
return max;
}
public static void union(int a, int b) {
parent[a] += parent[b];
parent[b] = a;
}
public static int find(int a) {
if (parent[a] < 0)
return a;
return (parent[a] = find(parent[a]));
}
public static Boolean[] primeNo() {
Boolean[] is_prime = new Boolean[100001];
int max = 100000;
for (int i = 2; i <= max; i++)
is_prime[i] = true;
is_prime[0] = is_prime[1] = false;
for (int i = 2; (long) i * i <= max; i++) {
if (is_prime[i] == true) {
for (int j = (i * i); j <= max; j += i)
is_prime[j] = false;
}
}
return is_prime;
}
public static int binarySearch(int arr[], int x) {
int l = 0, r = arr.length - 1;
int result1 = -1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (arr[mid] == x) {
return mid;
} else if (arr[mid] > x) {
r = mid - 1;
} else {
l = mid + 1;
}
}
return result1;
}
public static class Pair {
public int x;
public int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
public static long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
public static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["3\n\n4\n\n3 1 5 3\n\n3\n\n3 2 1\n\n1\n\n7331"] | 2 seconds | ["YES\nNO\nYES"] | NoteIn the first test case, we can do the following for $$$a = [3, 1, 5, 3]$$$:Step $$$1$$$: $$$a$$$$$$[3, 1, 5, 3]$$$$$$\Rightarrow$$$$$$[3, 1, 5]$$$$$$\Rightarrow$$$$$$[3, 1]$$$$$$\Rightarrow$$$$$$[3]$$$$$$\Rightarrow$$$$$$[]$$$$$$b$$$$$$[]$$$$$$[\underline{3}]$$$$$$[3, \underline{5}]$$$$$$[3, \underline{1}, 5]$$$$$$[3, \underline{3}, 1, 5]$$$Step $$$2$$$: $$$b$$$$$$[3, 3, \underline{1}, 5]$$$$$$\Rightarrow$$$$$$[3, \underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{5}]$$$$$$\Rightarrow$$$$$$[]$$$$$$c$$$$$$[]$$$$$$[1]$$$$$$[1, 3]$$$$$$[1, 3, 3]$$$$$$[1, 3, 3, 5]$$$ As a result, array $$$c = [1, 3, 3, 5]$$$ and it's sorted. | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings"
] | 95b35c53028ed0565684713a93910860 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — the array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,200 | For each test, print YES (case-insensitive), if you can make array $$$c$$$ sorted in non-decreasing order. Otherwise, print NO (case-insensitive). | standard output | |
PASSED | 3b9f2801969b4fabe3909ec8dce2cdf0 | train_107.jsonl | 1651502100 | You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps: Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements. Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements. Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order? | 256 megabytes | import java.io.*;
import java.util.*;
import java.io.IOException;
import java.io.InputStream;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
// inputStream = new FileInputStream("intersec1.in");
// outputStream = new FileOutputStream("intersec1.out");
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
solve(in, out);
out.close();
}
public static void solve(InputReader in, PrintWriter out) {
int t = in.nextInt();
a: for (int i = 0; i < t; i++) {
int n = in.nextInt();
int[] a = new int[n];
for (int j = 0; j < n; j++) {
a[j] = in.nextInt();
}
for (int j = n % 2 == 0 ? 0 : 1; j < n - 1; j += 2) {
if (a[j] > a[j + 1]) {
int tmp = a[j];
a[j] = a[j + 1];
a[j + 1] = tmp;
}
}
for (int j = 0; j < n - 1; j++) {
if (a[j] > a[j + 1]) {
out.println("NO");
continue a;
}
}
out.println("YES");
}
}
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();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["3\n\n4\n\n3 1 5 3\n\n3\n\n3 2 1\n\n1\n\n7331"] | 2 seconds | ["YES\nNO\nYES"] | NoteIn the first test case, we can do the following for $$$a = [3, 1, 5, 3]$$$:Step $$$1$$$: $$$a$$$$$$[3, 1, 5, 3]$$$$$$\Rightarrow$$$$$$[3, 1, 5]$$$$$$\Rightarrow$$$$$$[3, 1]$$$$$$\Rightarrow$$$$$$[3]$$$$$$\Rightarrow$$$$$$[]$$$$$$b$$$$$$[]$$$$$$[\underline{3}]$$$$$$[3, \underline{5}]$$$$$$[3, \underline{1}, 5]$$$$$$[3, \underline{3}, 1, 5]$$$Step $$$2$$$: $$$b$$$$$$[3, 3, \underline{1}, 5]$$$$$$\Rightarrow$$$$$$[3, \underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{5}]$$$$$$\Rightarrow$$$$$$[]$$$$$$c$$$$$$[]$$$$$$[1]$$$$$$[1, 3]$$$$$$[1, 3, 3]$$$$$$[1, 3, 3, 5]$$$ As a result, array $$$c = [1, 3, 3, 5]$$$ and it's sorted. | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings"
] | 95b35c53028ed0565684713a93910860 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — the array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,200 | For each test, print YES (case-insensitive), if you can make array $$$c$$$ sorted in non-decreasing order. Otherwise, print NO (case-insensitive). | standard output | |
PASSED | 7a15971e0913fd196bfce3743e772bd8 | train_107.jsonl | 1651502100 | You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps: Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements. Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements. Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order? | 256 megabytes | /*----------- ---------------*
Author : Ryan Ranaut
__Hope is a big word, never lose it__
------------- --------------*/
import java.io.*;
import java.util.*;
public class Codeforces1 {
static PrintWriter out = new PrintWriter(System.out);
static final int mod = 1_000_000_007;
static long min = (long) (-1e16);
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());
}
int[] readIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
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;
}
}
/*--------------------------------------------------------------------------*/
//Try seeing general case
//Minimization Maximization - BS..... Connections - Graphs.....
//Greedy not worthy - Try DP
//Think edge cases
public static void main(String[] args)
{
FastReader s = new FastReader();
int t = s.nextInt();
while(t-->0)
{
int n = s.nextInt();
int[] a = s.readIntArray(n);
out.println(find(n, a));
}
out.close();
}
public static String find(int n, int[] a)
{
if(n <= 2)
return "YES";
int[] b = a.clone();
sort(a);
for(int i=((n&1)==0 ? 1 : 2);i<n;i+=2)
{
int x1 = a[i-1]; int x2 = a[i];
int y1 = b[i-1]; int y2 = b[i];
if(x1 == y1 && x2 == y2)
continue;
if(x1 == y2 && x2 == y1)
continue;
return "NO";
}
if((n&1) == 1)
{
if(b[0]!=a[0])
return "NO";
}
return "YES";
}
/*----------------------------------End of the road--------------------------------------*/
static class DSU {
int[] parent;
int[] ranks;
int[] groupSize;
int size;
public DSU(int n) {
size = n;
parent = new int[n];//0 based
ranks = new int[n];
groupSize = new int[n];//Size of each component
for (int i = 0; i < n; i++) {
parent[i] = i;
ranks[i] = 1;
groupSize[i] = 1;
}
}
public int find(int x)//Path Compression
{
if (parent[x] == x)
return x;
else
return parent[x] = find(parent[x]);
}
public void union(int x, int y)//Union by rank
{
int x_rep = find(x);
int y_rep = find(y);
if (x_rep == y_rep)
return;
if (ranks[x_rep] < ranks[y_rep]) {
parent[x_rep] = y_rep;
groupSize[y_rep] += groupSize[x_rep];
} else if (ranks[x_rep] > ranks[y_rep]) {
parent[y_rep] = x_rep;
groupSize[x_rep] += groupSize[y_rep];
} else {
parent[y_rep] = x_rep;
ranks[x_rep]++;
groupSize[x_rep] += groupSize[y_rep];
}
size--;//Total connected components
}
}
public static int gcd(int x, int y) {
return y == 0 ? x : gcd(y, x % y);
}
public static long gcd(long x, long y) {
return y == 0L ? x : gcd(y, x % y);
}
public static int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
public static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
public static long pow(long a, long b) {
if (b == 0L)
return 1L;
long tmp = 1;
while (b > 1L) {
if ((b & 1L) == 1)
tmp *= a;
a *= a;
b >>= 1;
}
return (tmp * a);
}
public static long modPow(long a, long b, long mod) {
if (b == 0L)
return 1L;
long tmp = 1;
while (b > 1L) {
if ((b & 1L) == 1L)
tmp *= a;
a *= a;
a %= mod;
tmp %= mod;
b >>= 1;
}
return (tmp * a) % mod;
}
static long mul(long a, long b) {
return a * b;
}
static long fact(int n) {
long ans = 1;
for (int i = 2; i <= n; i++) ans = mul(ans, i);
return ans;
}
static long fastPow(long base, long exp) {
if (exp == 0) return 1;
long half = fastPow(base, exp / 2);
if (exp % 2 == 0) return mul(half, half);
return mul(half, mul(half, base));
}
static void debug(int... a) {
for (int x : a)
out.print(x + " ");
out.println();
}
static void debug(long... a) {
for (long x : a)
out.print(x + " ");
out.println();
}
static void debugMatrix(int[][] a) {
for (int[] x : a)
out.println(Arrays.toString(x));
}
static void debugMatrix(long[][] a) {
for (long[] x : a)
out.println(Arrays.toString(x));
}
static void reverseArray(int[] a) {
int n = a.length;
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = a[n - i - 1];
for (int i = 0; i < n; i++)
a[i] = arr[i];
}
static void reverseArray(long[] a) {
int n = a.length;
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = a[n - i - 1];
for (int i = 0; i < n; i++)
a[i] = arr[i];
}
static void sort(int[] a) {
ArrayList<Integer> ls = new ArrayList<>();
for (int x : a) ls.add(x);
Collections.sort(ls);
for (int i = 0; i < a.length; i++)
a[i] = ls.get(i);
}
static void sort(long[] a) {
ArrayList<Long> ls = new ArrayList<>();
for (long x : a) ls.add(x);
Collections.sort(ls);
for (int i = 0; i < a.length; i++)
a[i] = ls.get(i);
}
static class Pair {
int x, y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
} | Java | ["3\n\n4\n\n3 1 5 3\n\n3\n\n3 2 1\n\n1\n\n7331"] | 2 seconds | ["YES\nNO\nYES"] | NoteIn the first test case, we can do the following for $$$a = [3, 1, 5, 3]$$$:Step $$$1$$$: $$$a$$$$$$[3, 1, 5, 3]$$$$$$\Rightarrow$$$$$$[3, 1, 5]$$$$$$\Rightarrow$$$$$$[3, 1]$$$$$$\Rightarrow$$$$$$[3]$$$$$$\Rightarrow$$$$$$[]$$$$$$b$$$$$$[]$$$$$$[\underline{3}]$$$$$$[3, \underline{5}]$$$$$$[3, \underline{1}, 5]$$$$$$[3, \underline{3}, 1, 5]$$$Step $$$2$$$: $$$b$$$$$$[3, 3, \underline{1}, 5]$$$$$$\Rightarrow$$$$$$[3, \underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{5}]$$$$$$\Rightarrow$$$$$$[]$$$$$$c$$$$$$[]$$$$$$[1]$$$$$$[1, 3]$$$$$$[1, 3, 3]$$$$$$[1, 3, 3, 5]$$$ As a result, array $$$c = [1, 3, 3, 5]$$$ and it's sorted. | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings"
] | 95b35c53028ed0565684713a93910860 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — the array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,200 | For each test, print YES (case-insensitive), if you can make array $$$c$$$ sorted in non-decreasing order. Otherwise, print NO (case-insensitive). | standard output | |
PASSED | cfa17df13de34406ce96f4d1382c9bb0 | train_107.jsonl | 1651502100 | You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps: Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements. Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements. Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order? | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main(String args[]) throws IOException{
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw=new PrintWriter(System.out);
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
for(int i=0;i<n;i++){
int m=sc.nextInt();
int arr[]=new int[m];
for(int j=0;j<m;j++){
arr[j]=sc.nextInt();
}
for(int j=m-2;j>=0;j-=2){
if(arr[j]>arr[j+1]){
int a=arr[j];
arr[j]=arr[j+1];
arr[j+1]=a;
}
}
boolean f=true;
for(int j=1;j<m;j++){
if(arr[j]<arr[j-1]){
f=false;
System.out.println("NO");
break;
}
}
if(f){
System.out.println("YES");
}
}
//System.out.println("");
}
} | Java | ["3\n\n4\n\n3 1 5 3\n\n3\n\n3 2 1\n\n1\n\n7331"] | 2 seconds | ["YES\nNO\nYES"] | NoteIn the first test case, we can do the following for $$$a = [3, 1, 5, 3]$$$:Step $$$1$$$: $$$a$$$$$$[3, 1, 5, 3]$$$$$$\Rightarrow$$$$$$[3, 1, 5]$$$$$$\Rightarrow$$$$$$[3, 1]$$$$$$\Rightarrow$$$$$$[3]$$$$$$\Rightarrow$$$$$$[]$$$$$$b$$$$$$[]$$$$$$[\underline{3}]$$$$$$[3, \underline{5}]$$$$$$[3, \underline{1}, 5]$$$$$$[3, \underline{3}, 1, 5]$$$Step $$$2$$$: $$$b$$$$$$[3, 3, \underline{1}, 5]$$$$$$\Rightarrow$$$$$$[3, \underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{5}]$$$$$$\Rightarrow$$$$$$[]$$$$$$c$$$$$$[]$$$$$$[1]$$$$$$[1, 3]$$$$$$[1, 3, 3]$$$$$$[1, 3, 3, 5]$$$ As a result, array $$$c = [1, 3, 3, 5]$$$ and it's sorted. | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings"
] | 95b35c53028ed0565684713a93910860 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — the array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,200 | For each test, print YES (case-insensitive), if you can make array $$$c$$$ sorted in non-decreasing order. Otherwise, print NO (case-insensitive). | standard output | |
PASSED | 0257f372d9228675f93a5d423497e6c3 | train_107.jsonl | 1651502100 | You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps: Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements. Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements. Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order? | 256 megabytes | //some updates in import stuff
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import java.util.*;
import java.io.*;
import java.math.*;
//key points learned
//max space ever that could be alloted in a program to pass in cf
//int[][] prefixSum = new int[201][200_005]; -> not a single array more!!!
//never allocate memory again again to such bigg array, it will give memory exceeded for sure
//believe in your fucking solution and keep improving it!!! (sometimes)
//few things to figure around
//getting better and faster at taking input/output with normal method (buffered reader and printwriter)
//memorise all the key algos! a
public class D{
static int mod = (int) (Math.pow(10, 9)+7);
static final int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 };
static final int[] dx8 = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy8 = { -1, 0, 1, -1, 1, -1, 0, 1 };
static final int[] dx9 = { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, dy9 = { -1, 0, 1, -1, 0, 1, -1, 0, 1 };
static final double eps = 1e-10;
static List<Integer> primeNumbers = new ArrayList<>();
public static void main(String[] args) {
MyScanner sc = new MyScanner(); //pretty important for sure -
out = new PrintWriter(new BufferedOutputStream(System.out)); //dope shit output for sure
//code here
int test = sc.nextInt();
while(test --> 0){
int n = sc.nextInt();
int[] arr = new int[n];
ArrayDeque<Integer> que =new ArrayDeque<>();
for(int i= 0; i < n; i++){
arr[i]= sc.nextInt();
que.add(arr[i]);
}
int smallest = 0;
boolean flag = true;
while(!que.isEmpty()){
if(que.size() % 2 == 0){
int f = que.poll();
int s = que.poll();
if(f < s){
if(f < smallest){
flag = false;
break;
}else{
smallest = f;
}
que.addFirst(s);
}else{
if(s < smallest){
flag = false;
break;
}else{
smallest = s;
}
que.addFirst(f);
}
}else{
int val = que.pop();
if(val < smallest){
flag = false;
break;
}else{
smallest = val;
}
}
// out.println(que);
}
if(flag ){
out.println("YES");
}else{
out.println("NO");
}
}
out.close();
}
//new stuff to learn (whenever this is need for them, then only)
//Lazy Segment Trees
//Persistent Segment Trees
//Square Root Decomposition
//Geometry & Convex Hull
//High Level DP -- yk yk
//String Matching Algorithms
//Heavy light Decomposition
//Updation Required
//Fenwick Tree - both are done (sum)
//Segment Tree - both are done (min, max, sum)
//-----CURRENTLY PRESENT-------//
//Graph
//DSU
//powerMODe
//power
//Segment Tree (work on this one)
//Prime Sieve
//Count Divisors
//Next Permutation
//Get NCR
//isVowel
//Sort (int)
//Sort (long)
//Binomial Coefficient
//Pair
//Triplet
//lcm (int & long)
//gcd (int & long)
//gcd (for binomial coefficient)
//swap (int & char)
//reverse
//primeExponentCounts
//Fast input and output
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//GRAPH (basic structure)
public static class Graph{
public int V;
public ArrayList<ArrayList<Integer>> edges;
//2 -> [0,1,2] (current)
Graph(int V){
this.V = V;
edges = new ArrayList<>(V+1);
for(int i= 0; i <= V; i++){
edges.add(new ArrayList<>());
}
}
public void addEdge(int from , int to){
edges.get(from).add(to);
edges.get(to).add(from);
}
}
//DSU (path and rank optimised)
public static class DisjointUnionSets {
int[] rank, parent;
int n;
public DisjointUnionSets(int n)
{
rank = new int[n];
parent = new int[n];
Arrays.fill(rank, 1);
Arrays.fill(parent,-1);
this.n = n;
}
public int find(int curr){
if(parent[curr] == -1)
return curr;
//path compression optimisation
return parent[curr] = find(parent[curr]);
}
public void union(int a, int b){
int s1 = find(a);
int s2 = find(b);
if(s1 != s2){
//union by size
if(rank[s1] < rank[s2]){
parent[s1] = s2;
rank[s2] += rank[s1];
}else{
parent[s2] = s1;
rank[s1] += rank[s2];
}
}
}
}
//with mod
public static long powerMOD(long x, long y)
{
long res = 1L;
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1) != 0){
x %= mod;
res %= mod;
res = (res * x)%mod;
}
// y must be even now
y = y >> 1; // y = y/2
x%= mod;
x = (x * x)%mod; // Change x to x^2
}
return res%mod;
}
//without mod
public static long power(long x, long y)
{
long res = 1L;
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1) != 0){
res = (res * x);
}
// y must be even now
y = y >> 1; // y = y/
x = (x * x);
}
return res;
}
public static class segmentTree{
//so let's make a constructor function for this bad boi for sure!!!
public long[] arr;
public long[] tree;
//COMPLEXITY (normal segment tree, stuff)
//build -> O(n)
//query -> O(logn)
//update -> O(logn)
//update-range -> O(n) (worst case)
//simple iteration and stuff for sure
public segmentTree(long[] arr){
int n = arr.length;
this.arr = new long[n];
for(int i= 0; i < n; i++){
this.arr[i] = arr[i];
}
tree = new long[4*n + 1];
}
//pretty basic idea if you read the code once
//first make child node once
//then form the parent node using them
public void buildTree(int s, int e, int index){
if(s == e){
tree[index] = arr[s];
return;
}
//recursive case
int mid = (s + e)/2;
buildTree(s, mid, 2 * index);
buildTree(mid + 1, e, 2*index + 1);
//the condition we want from children be like this
tree[index] = min(tree[2 * index], tree[2 * index + 1]);
return;
}
//definitely index based 0 query!!!
//only int index = 1!!
//baaki everything is simple as fuck
public long query(int s, int e, int qs , int qe, int index){
//complete overlap
if(s >= qs && e <= qe){
return tree[index];
}
//no overlap
if(qe < s || qs > e){
return Long.MAX_VALUE;
}
//partial overlap
int mid = (s + e)/2;
long left = query( s, mid , qs, qe, 2*index);
long right = query( mid + 1, e, qs, qe, 2*index + 1);
return min(left, right);
}
//gonna do range updates for sure now!!
//let's do this bois!!! (solve this problem for sure)
public void updateRange(int s, int e, int l, int r, long increment, int index){
//out of bounds
if(l > e || r < s){
return;
}
//leaf node
if(s == e){
tree[index] += increment;
return; //behnchoda return tera baap krvayege?
}
//recursive case
int mid = (s + e)/2;
updateRange(s, mid, l, r, increment, 2 * index);
updateRange(mid + 1, e, l, r, increment, 2 * index + 1);
tree[index] = min(tree[2 * index], tree[2 * index + 1]);
}
}
public static class segmentTreeLazy{
//so let's make a constructor function for this bad boi for sure!!!
public long[] arr;
public long[] tree;
public long[] lazy;
//COMPLEXITY (normal segment tree, stuff)
//build -> O(n)
//query-range -> O(logn)
//lazy update-range -> O(logn) (imp)
//simple iteration and stuff for sure
public segmentTreeLazy(long[] arr){
int n = arr.length;
this.arr = new long[n];
for(int i= 0; i < n; i++){
this.arr[i] = arr[i];
}
tree = new long[4*n + 1];
lazy = new long[1000000]; //pretty big for no inconvenience (no?) NONONONOONON! NO fucker NO!
}
//pretty basic idea if you read the code once
//first make child node once
//then form the parent node using them
public void buildTree(int s, int e, int index){
if(s == e){
tree[index] = arr[s];
return;
}
//recursive case
int mid = (s + e)/2;
buildTree(s, mid, 2 * index);
buildTree(mid + 1, e, 2*index + 1);
//the condition we want from children be like this
tree[index] = min(tree[2 * index], tree[2 * index + 1]);
return;
}
//definitely index based 0 query!!!
//only int index = 1!!
//baaki everything is simple as fuck
public long queryLazy(int s, int e, int qs, int qe, int index){
//before going down resolve if it exist
if(lazy[index] != 0){
tree[index] += lazy[index];
//non leaf node
if(s != e){
lazy[2*index] += lazy[index];
lazy[2*index + 1] += lazy[index];
}
lazy[index] = 0; //clear the lazy value at current node for sure
}
//no overlap
if(s > qe || e < qs){
return Long.MAX_VALUE;
}
//complete overlap
if(s >= qs && e <= qe){
return tree[index];
}
//partial overlap
int mid = (s + e)/2;
long left = queryLazy(s, mid, qs, qe, 2 * index);
long right = queryLazy(mid + 1, e, qs, qe, 2 * index + 1);
return Math.min(left, right);
}
//update range in O(logn) -- using lazy array
public void updateRangeLazy(int s, int e, int l, int r, int inc, int index){
//before going down resolve if it exist
if(lazy[index] != 0){
tree[index] += lazy[index];
//non leaf node
if(s != e){
lazy[2*index] += lazy[index];
lazy[2*index + 1] += lazy[index];
}
lazy[index] = 0; //clear the lazy value at current node for sure
}
//no overlap
if(s > r || l > e){
return;
}
//another case
if(l <= s && e <= r){
tree[index] += inc;
//create a new lazy value for children node
if(s != e){
lazy[2*index] += inc;
lazy[2*index + 1] += inc;
}
return;
}
//recursive case
int mid = (s + e)/2;
updateRangeLazy(s, mid, l, r, inc, 2*index);
updateRangeLazy(mid + 1, e, l, r, inc, 2*index + 1);
//update the tree index
tree[index] = Math.min(tree[2*index], tree[2*index + 1]);
return;
}
}
//prime sieve
public static void primeSieve(int n){
BitSet bitset = new BitSet(n+1);
for(long i = 0; i < n ; i++){
if (i == 0 || i == 1) {
bitset.set((int) i);
continue;
}
if(bitset.get((int) i)) continue;
primeNumbers.add((int)i);
for(long j = i; j <= n ; j+= i)
bitset.set((int)j);
}
}
//number of divisors
public static int countDivisors(long number){
if(number == 1) return 1;
List<Integer> primeFactors = new ArrayList<>();
int index = 0;
long curr = primeNumbers.get(index);
while(curr * curr <= number){
while(number % curr == 0){
number = number/curr;
primeFactors.add((int) curr);
}
index++;
curr = primeNumbers.get(index);
}
if(number != 1) primeFactors.add((int) number);
int current = primeFactors.get(0);
int totalDivisors = 1;
int currentCount = 2;
for (int i = 1; i < primeFactors.size(); i++) {
if (primeFactors.get(i) == current) {
currentCount++;
} else {
totalDivisors *= currentCount;
currentCount = 2;
current = primeFactors.get(i);
}
}
totalDivisors *= currentCount;
return totalDivisors;
}
//primeExponentCounts
public static int primeExponentsCount(int n) {
if (n <= 1)
return 0;
int sqrt = (int) Math.sqrt(n);
int remainingNumber = n;
int result = 0;
for (int i = 2; i <= sqrt; i++) {
while (remainingNumber % i == 0) {
result++;
remainingNumber /= i;
}
}
//in case of prime numbers this would happen
if (remainingNumber > 1) {
result++;
}
return result;
}
//now adding next permutation function to java hehe
public static boolean next_permutation(int[] p) {
for (int a = p.length - 2; a >= 0; --a)
if (p[a] < p[a + 1])
for (int b = p.length - 1;; --b)
if (p[b] > p[a]) {
int t = p[a];
p[a] = p[b];
p[b] = t;
for (++a, b = p.length - 1; a < b; ++a, --b) {
t = p[a];
p[a] = p[b];
p[b] = t;
}
return true;
}
return false;
}
//finding the value of NCR in O(RlogN) time and O(1) space
public static long getNcR(int n, int r)
{
long p = 1, k = 1;
if (n - r < r) r = n - r;
if (r != 0) {
while (r > 0) {
p *= n;
k *= r;
long m = __gcd(p, k);
p /= m;
k /= m;
n--;
r--;
}
}
else {
p = 1;
}
return p;
}
//is vowel function
public static boolean isVowel(char c)
{
return (c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' || c=='u' || c=='U');
}
//to sort the array with better method
public 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);
}
//sort long
public 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);
}
//for calculating binomialCoeff
public static int binomialCoeff(int n, int k)
{
int C[] = new int[k + 1];
// nC0 is 1
C[0] = 1;
for (int i = 1; i <= n; i++) {
// Compute next row of pascal
// triangle using the previous row
for (int j = Math.min(i, k); j > 0; j--)
C[j] = C[j] + C[j - 1];
}
return C[k];
}
//Pair with int int
public static class Pair{
public int a;
public int b;
public int hashCode;
Pair(int a , int b){
this.a = a;
this.b = b;
this.hashCode = Objects.hash(a, b);
}
@Override
public String toString(){
return a + " -> " + b;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Pair that = (Pair) o;
return a == that.a && b == that.b;
}
@Override
public int hashCode() {
return this.hashCode;
}
}
//Triplet with int int int
public static class Triplet{
public int a;
public int b;
public int c;
Triplet(int a , int b, int c){
this.a = a;
this.b = b;
this.c = c;
}
@Override
public String toString(){
return a + " -> " + b;
}
}
//Shortcut function
public static long lcm(long a , long b){
return a * (b/gcd(a,b));
}
//let's make one for calculating lcm basically
public static int lcm(int a , int b){
return (a * b)/gcd(a,b);
}
//int version for gcd
public static int gcd(int a, int b){
if(b == 0)
return a;
return gcd(b , a%b);
}
//long version for gcd
public static long gcd(long a, long b){
if(b == 0)
return a;
return gcd(b , a%b);
}
//for ncr calculator(ignore this code)
public static long __gcd(long n1, long n2)
{
long gcd = 1;
for (int i = 1; i <= n1 && i <= n2; ++i) {
// Checks if i is factor of both integers
if (n1 % i == 0 && n2 % i == 0) {
gcd = i;
}
}
return gcd;
}
//swapping two elements in an array
public static void swap(int[] arr, int left , int right){
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
//for char array
public static void swap(char[] arr, int left , int right){
char temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
//reversing an array
public static void reverse(int[] arr){
int left = 0;
int right = arr.length-1;
while(left <= right){
swap(arr, left,right);
left++;
right--;
}
}
public static long expo(long a, long b, long mod) {
long res = 1;
while (b > 0) {
if ((b & 1) == 1L) res = (res * a) % mod; //think about this one for a second
a = (a * a) % mod;
b = b >> 1;
}
return res;
}
//SOME EXTRA DOPE FUNCTIONS
public static long mminvprime(long a, long b) {
return expo(a, b - 2, b);
}
public static long mod_add(long a, long b, long m) {
a = a % m;
b = b % m;
return (((a + b) % m) + m) % m;
}
public static long mod_sub(long a, long b, long m) {
a = a % m;
b = b % m;
return (((a - b) % m) + m) % m;
}
public static long mod_mul(long a, long b, long m) {
a = a % m;
b = b % m;
return (((a * b) % m) + m) % m;
}
public static long mod_div(long a, long b, long m) {
a = a % m;
b = b % m;
return (mod_mul(a, mminvprime(b, m), m) + m) % m;
}
//O(n) every single time remember that
public static long nCr(long N, long K , long mod){
long upper = 1L;
long lower = 1L;
long lowerr = 1L;
for(long i = 1; i <= N; i++){
upper = mod_mul(upper, i, mod);
}
for(long i = 1; i <= K; i++){
lower = mod_mul(lower, i, mod);
}
for(long i = 1; i <= (N - K); i++){
lowerr = mod_mul(lowerr, i, mod);
}
// out.println(upper + " " + lower + " " + lowerr);
long answer = mod_mul(lower, lowerr, mod);
answer = mod_div(upper, answer, mod);
return answer;
}
// long[] fact = new long[2 * n + 1];
// long[] ifact = new long[2 * n + 1];
// fact[0] = 1;
// ifact[0] = 1;
// for (long i = 1; i <= 2 * n; i++)
// {
// fact[(int)i] = mod_mul(fact[(int)i - 1], i, mod);
// ifact[(int)i] = mminvprime(fact[(int)i], mod);
// }
//ifact is basically inverse factorial in here!!!!!(imp)
public static long combination(long n, long r, long m, long[] fact, long[] ifact) {
long val1 = fact[(int)n];
long val2 = ifact[(int)(n - r)];
long val3 = ifact[(int)r];
return (((val1 * val2) % m) * val3) % m;
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//--------------------------------------------------------
} | Java | ["3\n\n4\n\n3 1 5 3\n\n3\n\n3 2 1\n\n1\n\n7331"] | 2 seconds | ["YES\nNO\nYES"] | NoteIn the first test case, we can do the following for $$$a = [3, 1, 5, 3]$$$:Step $$$1$$$: $$$a$$$$$$[3, 1, 5, 3]$$$$$$\Rightarrow$$$$$$[3, 1, 5]$$$$$$\Rightarrow$$$$$$[3, 1]$$$$$$\Rightarrow$$$$$$[3]$$$$$$\Rightarrow$$$$$$[]$$$$$$b$$$$$$[]$$$$$$[\underline{3}]$$$$$$[3, \underline{5}]$$$$$$[3, \underline{1}, 5]$$$$$$[3, \underline{3}, 1, 5]$$$Step $$$2$$$: $$$b$$$$$$[3, 3, \underline{1}, 5]$$$$$$\Rightarrow$$$$$$[3, \underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{5}]$$$$$$\Rightarrow$$$$$$[]$$$$$$c$$$$$$[]$$$$$$[1]$$$$$$[1, 3]$$$$$$[1, 3, 3]$$$$$$[1, 3, 3, 5]$$$ As a result, array $$$c = [1, 3, 3, 5]$$$ and it's sorted. | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings"
] | 95b35c53028ed0565684713a93910860 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — the array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,200 | For each test, print YES (case-insensitive), if you can make array $$$c$$$ sorted in non-decreasing order. Otherwise, print NO (case-insensitive). | standard output | |
PASSED | 2886815e4301ec46956f7d8b690d2e59 | train_107.jsonl | 1651502100 | You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps: Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements. Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements. Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order? | 256 megabytes | import java.util.*;
import java.io.*;
import java.time.*;
import static java.lang.Math.*;
@SuppressWarnings("unused")
public class D {
static boolean DEBUG = false;
static Reader fs;
static PrintWriter pw;
static void solve() {
int n = fs.nextInt();
int a[] = fs.readArray(n);
int b[] = Arrays.copyOf(a, n);
sort(b);
boolean ans = true;
for (int i = n - 1; i >= 0; i -= 2) {
try {
ans &= ((a[i] == b[i] && a[i - 1] == b[i - 1]) | (a[i - 1] == b[i] && a[i] == b[i - 1]));
} catch (Exception e) {
}
}
lg(a);
lg(b);
if (n % 2 == 1) {
ans &= a[0] == b[0];
}
pw.println(ans ? "YES" : "NO");
}
static void lg(Object o) {
if (DEBUG)
System.err.println(o);
}
static void lg(int a[]) {
if (DEBUG)
System.err.println(Arrays.toString(a));
}
static void lg(char a[]) {
if (DEBUG)
System.err.println(Arrays.toString(a));
}
static void lg(String a) {
if (DEBUG)
System.err.print(a + " -> ");
}
static <T> void lg(T a[]) {
if (DEBUG) {
System.err.print("[");
for (T x : a)
System.err.print(x + " ");
System.err.println("]");
}
}
static <T> void lg(ArrayList<T> a) {
if (DEBUG) {
System.err.print("[");
for (T x : a) {
System.err.print(x + " ");
}
System.err.println("]");
}
}
static <T, V> void lg(Map<T, V> mp) {
if (DEBUG) {
System.err.print(mp);
}
}
public static void main(String[] args) throws IOException {
if (args.length == 2) {
System.setIn(new FileInputStream("D:\\program\\javaCPEclipse\\CodeForces\\src\\input.txt"));
System.setErr(new PrintStream("D:\\program\\javaCPEclipse\\CodeForces\\src\\error.txt"));
DEBUG = true;
}
Instant start = Instant.now();
fs = new Reader();
pw = new PrintWriter(System.out);
int t = fs.nextInt();
while (t-- > 0) {
solve();
}
Instant end = Instant.now();
if (DEBUG) {
pw.println(Duration.between(start, end));
}
pw.close();
}
static void sort(int a[]) {
ArrayList<Integer> l = new ArrayList<Integer>();
for (int x : a)
l.add(x);
Collections.sort(l);
for (int i = 0; i < a.length; i++) {
a[i] = l.get(i);
}
}
public static void print(long a, long b, long c, PrintWriter pw) {
pw.println(a + " " + b + " " + c);
return;
}
static class Reader {
BufferedReader br;
StringTokenizer st;
public Reader() {
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;
}
int[] readArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
int[][] read2Array(int n, int m) {
int a[][] = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = nextInt();
}
}
return a;
}
}
} | Java | ["3\n\n4\n\n3 1 5 3\n\n3\n\n3 2 1\n\n1\n\n7331"] | 2 seconds | ["YES\nNO\nYES"] | NoteIn the first test case, we can do the following for $$$a = [3, 1, 5, 3]$$$:Step $$$1$$$: $$$a$$$$$$[3, 1, 5, 3]$$$$$$\Rightarrow$$$$$$[3, 1, 5]$$$$$$\Rightarrow$$$$$$[3, 1]$$$$$$\Rightarrow$$$$$$[3]$$$$$$\Rightarrow$$$$$$[]$$$$$$b$$$$$$[]$$$$$$[\underline{3}]$$$$$$[3, \underline{5}]$$$$$$[3, \underline{1}, 5]$$$$$$[3, \underline{3}, 1, 5]$$$Step $$$2$$$: $$$b$$$$$$[3, 3, \underline{1}, 5]$$$$$$\Rightarrow$$$$$$[3, \underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{5}]$$$$$$\Rightarrow$$$$$$[]$$$$$$c$$$$$$[]$$$$$$[1]$$$$$$[1, 3]$$$$$$[1, 3, 3]$$$$$$[1, 3, 3, 5]$$$ As a result, array $$$c = [1, 3, 3, 5]$$$ and it's sorted. | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings"
] | 95b35c53028ed0565684713a93910860 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — the array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,200 | For each test, print YES (case-insensitive), if you can make array $$$c$$$ sorted in non-decreasing order. Otherwise, print NO (case-insensitive). | standard output | |
PASSED | 67d3fade087427738d61110544255052 | train_107.jsonl | 1651502100 | You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps: Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements. Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements. Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order? | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
public class D {
//java -Xss515m Solution.java < input.txt
private static final String SPACE = "\\s+";
private static final int MOD = 1_000_000_007;
private static final Reader in = new Reader();
public static void main(String[] args) throws IOException {
int tt = in.readInt();
for (int t = 1; t <= tt; t++) {
int n = in.readInt();
int[] nums = in.readInts();
System.out.println(solve(n, nums) ? "YES" : "NO");
}
}
private static boolean solve(int n, int[] nums) throws IOException {
for (int i = n - 1; i > 0; i-=2) {
if (nums[i] < nums[i-1])
swap(i, i-1, nums);
}
for (int i = 1; i < n; i++) {
if (nums[i] < nums[i-1]) return false;
}
return true;
}
// Utility functions
private static int max(int... nums) {
int max = Integer.MIN_VALUE;
for (int num : nums) {
max = Math.max(max, num);
}
return max;
}
private static int min(int... nums) {
int min = Integer.MAX_VALUE;
for (int num : nums) {
min = Math.min(min, num);
}
return min;
}
private static long max(long... nums) {
long max = Long.MIN_VALUE;
for (long num : nums) {
max = Math.max(max, num);
}
return max;
}
private static long min(long... nums) {
long min = Long.MAX_VALUE;
for (long num : nums) {
min = Math.min(min, num);
}
return min;
}
private static void shuffleSort(int[] nums) {
shuffle(nums);
Arrays.sort(nums);
}
private static void shuffle(int[] nums) {
Random random = ThreadLocalRandom.current();
for (int i = nums.length - 1; i > 0; i--) {
swap(random.nextInt(i), i, nums);
}
}
private static void swap(int a, int b, int[] nums) {
int temp = nums[a];
nums[a] = nums[b];
nums[b] = temp;
}
private static void shuffleSort(long[] nums) {
shuffle(nums);
Arrays.sort(nums);
}
private static void shuffle(long[] nums) {
Random random = ThreadLocalRandom.current();
for (int i = nums.length - 1; i > 0; i--) {
swap(random.nextInt(i), i, nums);
}
}
private static void swap(int a, int b, long[] nums) {
long temp = nums[a];
nums[a] = nums[b];
nums[b] = temp;
}
private static long pow(int base, int exp) {
long res = 1;
while (exp-- > 0) {
res *= base;
}
return res;
}
private static long pow(int base, int exp, Long[][] memo) {
if (exp == 0) return 1;
if (memo[base][exp] != null) return memo[base][exp];
return memo[base][exp] = base * pow(base, exp - 1, memo) % MOD;
}
private static void print(int[] nums) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < nums.length; i++) {
sb.append(nums[i]).append(" ");
}
System.out.println(sb);
}
private static void print(long[] nums) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < nums.length; i++) {
sb.append(nums[i]).append(" ");
}
System.out.println(sb);
}
private static void print(String[] A) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < A.length; i++) {
sb.append(A[i]).append(" ");
}
System.out.println(sb);
}
private static int gcd(int p, int q) {
if (q == 0) return p;
return gcd(q, p % q);
}
private static class Reader {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int index = 0;
String[] tokens = {};
public int readInt() throws IOException {
read();
return Integer.parseInt(tokens[index++]);
}
public long readLong() throws IOException {
read();
return Long.parseLong(tokens[index++]);
}
public String readString() throws IOException {
read();
return tokens[index++];
}
public String readLine() throws IOException {
return in.readLine();
}
public int[] readInts() throws IOException {
return Arrays.stream(in.readLine().split(SPACE)).mapToInt(Integer::parseInt).toArray();
}
public long[] readLongs() throws IOException {
return Arrays.stream(in.readLine().split(SPACE)).mapToLong(Long::parseLong).toArray();
}
public String[] readStrings() throws IOException {
return in.readLine().split(SPACE);
}
private void read() throws IOException {
if (index >= tokens.length) {
tokens = in.readLine().split(SPACE);
index = 0;
}
}
}
private static class UnionFind {
int[] p;
public UnionFind(int n) {
Arrays.fill(p = new int[n], -1);
}
public int find(int i) {
return p[i] < 0 ? i : (p[i] = find(p[i]));
}
public boolean union(int i, int j) {
if ((i = find(i)) == (j = find(j))) return false;
if (p[i] == p[j]) p[i]--;
if (p[i] <= p[j]) p[j] = i; else p[i] = j;
return true;
}
}
}
| Java | ["3\n\n4\n\n3 1 5 3\n\n3\n\n3 2 1\n\n1\n\n7331"] | 2 seconds | ["YES\nNO\nYES"] | NoteIn the first test case, we can do the following for $$$a = [3, 1, 5, 3]$$$:Step $$$1$$$: $$$a$$$$$$[3, 1, 5, 3]$$$$$$\Rightarrow$$$$$$[3, 1, 5]$$$$$$\Rightarrow$$$$$$[3, 1]$$$$$$\Rightarrow$$$$$$[3]$$$$$$\Rightarrow$$$$$$[]$$$$$$b$$$$$$[]$$$$$$[\underline{3}]$$$$$$[3, \underline{5}]$$$$$$[3, \underline{1}, 5]$$$$$$[3, \underline{3}, 1, 5]$$$Step $$$2$$$: $$$b$$$$$$[3, 3, \underline{1}, 5]$$$$$$\Rightarrow$$$$$$[3, \underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{5}]$$$$$$\Rightarrow$$$$$$[]$$$$$$c$$$$$$[]$$$$$$[1]$$$$$$[1, 3]$$$$$$[1, 3, 3]$$$$$$[1, 3, 3, 5]$$$ As a result, array $$$c = [1, 3, 3, 5]$$$ and it's sorted. | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings"
] | 95b35c53028ed0565684713a93910860 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — the array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,200 | For each test, print YES (case-insensitive), if you can make array $$$c$$$ sorted in non-decreasing order. Otherwise, print NO (case-insensitive). | standard output | |
PASSED | 43e33c86ed8afcb72764a1db88161ae4 | train_107.jsonl | 1651502100 | You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps: Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements. Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements. Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order? | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.math.*;
/**
_ _
( _) ( _)
/ / \\ / /\_\_
/ / \\ / / | \ \
/ / \\ / / |\ \ \
/ / , \ , / / /| \ \
/ / |\_ /| / / / \ \_\
/ / |\/ _ '_| \ / / / \ \\
| / |/ 0 \0\ / | | \ \\
| |\| \_\_ / / | \ \\
| | |/ \.\ o\o) / \ | \\
\ | /\\`v-v / | | \\
| \/ /_| \\_| / | | \ \\
| | /__/_ - / ___ | | \ \\
\| [__] \_/ |_________ \ | \ ()
/ [___] ( \ \ |\ | | //
| [___] |\| \| / |/
/| [____] \ |/\ / / ||
( \ [____ / ) _\ \ \ \| | ||
\ \ [_____| / / __/ \ / / //
| \ [_____/ / / \ | \/ //
| / '----| /=\____ _/ | / //
__ / / | / ___/ _/\ \ | ||
(/-(/-\) / \ (/\/\)/ | / | /
(/\/\) / / //
_________/ / /
\____________/ (
@author NTUDragons-Reborn
*/
public class C{
public static void main(String[] args) throws Exception {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(in, out);
out.close();
}
// main solver
static class Task{
double eps= 0.00000001;
static final int MAXN = 100005;
static final int MOD= 1000000007;
// stores smallest prime factor for every number
static int spf[] = new int[MAXN];
static boolean[] prime;
Map<Integer,Set<Integer>> dp= new HashMap<>();
// Calculating SPF (Smallest Prime Factor) for every
// number till MAXN.
// Time Complexity : O(nloglogn)
public void sieve()
{
spf[1] = 1;
for (int i=2; i<MAXN; i++)
// marking smallest prime factor for every
// number to be itself.
spf[i] = i;
// separately marking spf for every even
// number as 2
for (int i=4; i<MAXN; i+=2)
spf[i] = 2;
for (int i=3; i*i<MAXN; i++)
{
// checking if i is prime
if (spf[i] == i)
{
// marking SPF for all numbers divisible by i
for (int j=i*i; j<MAXN; j+=i)
// marking spf[j] if it is not
// previously marked
if (spf[j]==j)
spf[j] = i;
}
}
}
void sieveOfEratosthenes(int n)
{
// Create a boolean array
// "prime[0..n]" and
// initialize all entries
// it as true. A value in
// prime[i] will finally be
// false if i is Not a
// prime, else true.
prime= new boolean[n + 1];
for (int i = 0; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++)
{
// If prime[p] is not changed, then it is a
// prime
if (prime[p] == true)
{
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
}
// A O(log n) function returning primefactorization
// by dividing by smallest prime factor at every step
public Set<Integer> getFactorization(int x)
{
if(dp.containsKey(x)) return dp.get(x);
Set<Integer> ret = new HashSet<>();
while (x != 1)
{
if(spf[x]!=2) ret.add(spf[x]);
x = x / spf[x];
}
dp.put(x,ret);
return ret;
}
public Map<Integer,Integer> getFactorizationPower(int x){
Map<Integer,Integer> map= new HashMap<>();
while(x!=1){
map.put(spf[x], map.getOrDefault(spf[x], 0)+1);
x/= spf[x];
}
return map;
}
// function to find first index >= x
public int lowerIndex(List<Integer> arr, int n, int x)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr.get(mid) >= x)
h = mid - 1;
else
l = mid + 1;
}
return l;
}
public int lowerIndex(int[] arr, int n, int x)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr[mid] >= x)
h = mid - 1;
else
l = mid + 1;
}
return l;
}
// function to find last index <= y
public int upperIndex(List<Integer> arr, int n, int y)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr.get(mid) <= y)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
public int upperIndex(int[] arr, int n, int y)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr[mid] <= y)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
// function to count elements within given range
public int countInRange(List<Integer> arr, int n, int x, int y)
{
// initialize result
int count = 0;
count = upperIndex(arr, n, y) -
lowerIndex(arr, n, x) + 1;
return count;
}
public int add(int a, int b){
a+=b;
while(a>=MOD) a-=MOD;
while(a<0) a+=MOD;
return a;
}
public int mul(int a, int b){
long res= (long)a*(long)b;
return (int)(res%MOD);
}
public int power(int a, int b) {
int ans=1;
while(b>0){
if((b&1)!=0) ans= mul(ans,a);
b>>=1;
a= mul(a,a);
}
return ans;
}
int[] fact= new int[MAXN];
int[] inv= new int[MAXN];
public int Ckn(int n, int k){
if(k<0 || n<0) return 0;
if(n<k) return 0;
return mul(mul(fact[n],inv[k]),inv[n-k]);
}
public int inverse(int a){
return power(a,MOD-2);
}
public void preprocess() {
fact[0]=1;
for(int i=1;i<MAXN;i++) fact[i]= mul(fact[i-1],i);
inv[MAXN-1]= inverse(fact[MAXN-1]);
for(int i=MAXN-2;i>=0;i--){
inv[i]= mul(inv[i+1],i+1);
}
}
/**
* return VALUE of lower bound for unsorted array
*/
public int lowerBoundNormalArray(int[] arr, int x){
TreeSet<Integer> set= new TreeSet<>();
for(int num: arr) set.add(num);
return set.lower(x);
}
/**
* return VALUE of upper bound for unsorted array
*/
public int upperBoundNormalArray(int[] arr, int x){
TreeSet<Integer> set= new TreeSet<>();
for(int num: arr) set.add(num);
return set.higher(x);
}
public void debugArr(int[] arr){
for(int i: arr) out.print(i+" ");
out.println();
}
public int rand(){
int min=0, max= MAXN;
int random_int = (int)Math.floor(Math.random()*(max-min+1)+min);
return random_int;
}
public void suffleSort(int[] arr){
shuffleArray(arr);
Arrays.sort(arr);
}
public void shuffleArray(int[] ar)
{
// If running on Java 6 or older, use new Random() on RHS here
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
InputReader in; PrintWriter out;
Scanner sc= new Scanner(System.in);
CustomFileReader cin;
int[] xor= new int[3*100000+5];
int[] pow2= new int[1000000+1];
public void solve(InputReader in, PrintWriter out) throws Exception {
this.in=in; this.out=out;
sieve();
// pow2[0]=1;
// for(int i=1;i<pow2.length;i++){
// pow2[i]= mul(pow2[i-1],2);
// }
int t=in.nextInt();
// preprocess();
// int t=in.nextInt();
// int t= cin.nextIntArrLine()[0];
for(int i=1;i<=t;i++) solveD(i);
}
final double pi= Math.acos(-1);
static Point base;
// If no tle, quite easy, think too complex -> time-consuming
void solveD(int test){
int n= in.nextInt();
int[] a= in.nextIntArr(n);
for(int i=n-1;i>=0;i-=2){
if(i+1<n && a[i]>a[i+1]) {System.out.println("NO"); return;}
if(i+2<n && a[i]>a[i+2]) {System.out.println("NO"); return;}
if(i-1>=0 && i+1<n && a[i-1]>a[i+1]) {System.out.println("NO"); return;}
if(i-1>=0 && i+2<n && a[i-1]>a[i+2]) {System.out.println("NO"); return;}
}
System.out.println("YES");
}
void solveF(int test) throws Exception{
int n= in.nextInt();
int[] a= in.nextIntArr(n);
Map<Integer,Integer> cnt= new HashMap<>();
int len=0;
for(int i=1;i<n;i++){
if(a[i]==a[i-1]){
len++;
}
else{
cnt.put(len+1,cnt.getOrDefault(len+1, 0)+1);
len=0;
}
}
cnt.put(len+1,cnt.getOrDefault(len+1, 0)+1);
// out.println(cnt);
int res=0;
boolean done=false;
for(Map.Entry<Integer,Integer> entry: cnt.entrySet()){
int key= entry.getKey();
int val= entry.getValue();
if(!done){
val--;
done= true;
res+= (key-1)/2;
}
res+= key/2*val;
}
out.println(res);
}
static class ListNode{
int idx=-1;
ListNode next= null;
public ListNode(int idx){
this.idx= idx;
}
}
public long _gcd(long a, long b)
{
if(b == 0) {
return a;
}
else {
return _gcd(b, a % b);
}
}
public long _lcm(long a, long b){
return (a*b)/_gcd(a,b);
}
}
// static class SEG {
// Pair[] segtree;
// public SEG(int n){
// segtree= new Pair[4*n];
// Arrays.fill(segtree, new Pair(-1,Long.MAX_VALUE));
// }
// // void buildTree(int l, int r, int index) {
// // if (l == r) {
// // segtree[index].y = a[l];
// // return;
// // }
// // int mid = (l + r) / 2;
// // buildTree(l, mid, 2 * index + 1);
// // buildTree(mid + 1, r, 2 * index + 2);
// // segtree[index].y = Math.min(segtree[2 * index + 1].y, segtree[2 * index + 2].y);
// // }
// void update(int l, int r, int index, int pos, Pair val) {
// if (l == r) {
// segtree[index] = val;
// return;
// }
// int mid = (l + r) / 2;
// if (pos <= mid) update(l, mid, 2 * index + 1, pos, val);
// else update(mid + 1, r, 2 * index + 2, pos, val);
// if(segtree[2 * index + 1].y < segtree[2 * index + 2].y){
// segtree[index]= segtree[2 * index + 1];
// }
// else {
// segtree[index]= segtree[2 * index + 2];
// }
// }
// // Pair query(int l, int r, int from, int to, int index) {
// // if (from <= l && r <= to)
// // return segtree[index];
// // if (r < from | to < l)
// // return 0;
// // int mid = (l + r) / 2;
// // Pair left= query(l, mid, from, to, 2 * index + 1);
// // Pair right= query(mid + 1, r, from, to, 2 * index + 2);
// // if(left.y < right.y) return left;
// // else return right;
// // }
// }
static class Venice{
public Map<Long,Long> m= new HashMap<>();
public long base=0;
public long totalValue=0;
private int M= 1000000007;
private long addMod(long a, long b){
a+=b;
if(a>=M) a-=M;
return a;
}
public void reset(){
m= new HashMap<>();
base=0;
totalValue=0;
}
public void update(long add){
base= base+ add;
}
public void add(long key, long val){
long newKey= key-base;
m.put(newKey, addMod(m.getOrDefault(newKey,(long)0),val));
}
}
static class Tuple implements Comparable<Tuple>{
int x, y, z;
public Tuple(int x, int y, int z){
this.x= x;
this.y= y;
this.z=z;
}
@Override
public int compareTo(Tuple o){
return this.z-o.z;
}
}
static class Point implements Comparable<Point>{
public double x;
public long y;
public Point(double x, long y){
this.x= x;
this.y= y;
}
@Override
public int compareTo(Point o) {
if(this.y!=o.y) return (int)(this.y-o.y);
return (int)(this.x-o.x);
}
}
// static class Vector {
// public long x;
// public long y;
// // p1 -> p2
// public Vector(Point p1, Point p2){
// this.x= p2.x-p1.x;
// this.y= p2.y-p1.y;
// }
// }
static class Pair implements Comparable<Pair>{
public int x;
public int y;
public Pair(int x, int y){
this.x= x;
this.y= y;
}
@Override
public int compareTo(Pair o) {
if(this.x!=o.x) return (int)(this.x-o.x);
return (int)(this.y-o.y);
}
}
// public static class compareL implements Comparator<Tuple>{
// @Override
// public int compare(Tuple t1, Tuple t2) {
// return t2.l - t1.l;
// }
// }
// fast input reader class;
static class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream));
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public double nextDouble(){
return Double.parseDouble(nextToken());
}
public long nextLong(){
return Long.parseLong(nextToken());
}
public int[] nextIntArr(int n){
int[] arr= new int[n];
for(int i=0;i<n;i++) arr[i]= nextInt();
return arr;
}
public long[] nextLongArr(int n){
long[] arr= new long[n];
for(int i=0;i<n;i++) arr[i]= nextLong();
return arr;
}
public List<Integer> nextIntList(int n){
List<Integer> arr= new ArrayList<>();
for(int i=0;i<n;i++) arr.add(nextInt());
return arr;
}
public int[][] nextIntMatArr(int n, int m){
int[][] mat= new int[n][m];
for(int i=0;i<n;i++) for(int j=0;j<m;j++) mat[i][j]= nextInt();
return mat;
}
public List<List<Integer>> nextIntMatList(int n, int m){
List<List<Integer>> mat= new ArrayList<>();
for(int i=0;i<n;i++){
List<Integer> temp= new ArrayList<>();
for(int j=0;j<m;j++) temp.add(nextInt());
mat.add(temp);
}
return mat;
}
public char[] nextStringCharArr(){
return nextToken().toCharArray();
}
}
static class CustomFileReader{
String path="";
Scanner sc;
public CustomFileReader(String path){
this.path=path;
try{
sc= new Scanner(new File(path));
}
catch(Exception e){}
}
public String nextLine(){
return sc.nextLine();
}
public int[] nextIntArrLine(){
String line= sc.nextLine();
String[] part= line.split("[\\s+]");
int[] res= new int[part.length];
for(int i=0;i<res.length;i++) res[i]= Integer.parseInt(part[i]);
return res;
}
}
} | Java | ["3\n\n4\n\n3 1 5 3\n\n3\n\n3 2 1\n\n1\n\n7331"] | 2 seconds | ["YES\nNO\nYES"] | NoteIn the first test case, we can do the following for $$$a = [3, 1, 5, 3]$$$:Step $$$1$$$: $$$a$$$$$$[3, 1, 5, 3]$$$$$$\Rightarrow$$$$$$[3, 1, 5]$$$$$$\Rightarrow$$$$$$[3, 1]$$$$$$\Rightarrow$$$$$$[3]$$$$$$\Rightarrow$$$$$$[]$$$$$$b$$$$$$[]$$$$$$[\underline{3}]$$$$$$[3, \underline{5}]$$$$$$[3, \underline{1}, 5]$$$$$$[3, \underline{3}, 1, 5]$$$Step $$$2$$$: $$$b$$$$$$[3, 3, \underline{1}, 5]$$$$$$\Rightarrow$$$$$$[3, \underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{5}]$$$$$$\Rightarrow$$$$$$[]$$$$$$c$$$$$$[]$$$$$$[1]$$$$$$[1, 3]$$$$$$[1, 3, 3]$$$$$$[1, 3, 3, 5]$$$ As a result, array $$$c = [1, 3, 3, 5]$$$ and it's sorted. | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings"
] | 95b35c53028ed0565684713a93910860 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — the array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,200 | For each test, print YES (case-insensitive), if you can make array $$$c$$$ sorted in non-decreasing order. Otherwise, print NO (case-insensitive). | standard output | |
PASSED | 9e40a750c48d6ed6ab42ef590ee99c46 | train_107.jsonl | 1651502100 | You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps: Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements. Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements. Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order? | 256 megabytes | import java.util.*;
public class MergeSort {
static int[][] moveInEight = {{1, 1}, {1, 0}, {1, -1}, {0, 1}, {-1, 1}, {0, -1}, {-1, -1}, {-1, 0}};
static int[][] moveInFour = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
public static void main(String[] args) throws java.lang.Exception {
Scanner sc = new Scanner(System.in);
int test = sc.nextInt();
while(test-->0){
int n=sc.nextInt();
int[] a =new int[n];
for(int i=0;i<n;i++) a[i]=sc.nextInt();
for(int i=n-1;i>0;i-=2){
if(a[i]<a[i-1]){
int temp=a[i];
a[i]=a[i-1];
a[i-1]=temp;
}
}
boolean flag=true;
for(int i=1;i<n;i++){
if(a[i]<a[i-1])
{
flag=false;
break;
}
}
if(flag)
System.out.println("YES");
else
System.out.println("NO");
}
}
static class Group implements Comparable<Group> {
int x;
int y;
Group(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Group o) {
return x - o.x;
}
}
//primes
private static ArrayList<Integer> primeFactUsingSieve(int n) {
int[] a = new int[n + 1];
Arrays.fill(a, 0);
ArrayList<Integer> arrayList = new ArrayList<>();
for (int i = 2; i <= n; i++) {
if (a[i] != 0) continue;
for (int j = 1; i * j <= n; j++) {
if (a[j * i] == 0) a[j * i] = i;
}
}
int x = n;
while (x > 1) {
arrayList.add(a[x]);
x = x / a[x];
}
return arrayList;
}
private static List<Integer> getAllPrimes(int n) {
int[] primeNum = new int[n + 1];
Arrays.fill(primeNum, 0);
for (int i = 2; i * i < n; i++) {
if (primeNum[i] == 1) continue;
for (int j = 2; i * j <= n; j++) primeNum[i * j] = 1;
}
ArrayList<Integer> list = new ArrayList<>();
for (int i = 2; i < n; i++) {
if (primeNum[i] == 0) list.add(i);
}
return list;
}
private static boolean primalityTest(int n) {
if (n == 1) return false;
for (int i = 2; i * i < n; i++) {
if (n % i == 0) return false;
}
return true;
}
//////////Helper Functions////////////////////////////////////
private static char getCharFromASCII(int c) {
return (char) (c + 96);
}
private static boolean isValidPos(long x, long y, long i, long j) {
return i < x && i >= 0 && j >= 0 && j < y;
}
private static int getFactorial(int n) {
int res = 1;
for (int i = 2; i <= n; i++) res = res * i;
return res;
}
private static boolean isPalindrome(char[] s) {
int start = 0, last = s.length - 1;
while (start < last) {
if (s[start] != s[last]) return false;
start++;
last--;
}
return true;
}
private static void swap(int i, int j, long[] arr) {
long temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
private static void swap(int i, int j) {
int temp = i;
i = j;
j = temp;
}
private static boolean isEven(int a) {
return a % 2 == 0;
}
static int findGCD(int x, int y) {
int r = 0, a, b;
a = Math.max(x, y);
b = Math.min(x, y);
r = b;
while (a % b != 0) {
r = a % b;
a = b;
b = r;
}
return r;
}
static int findLcm(int a, int b) {
return (a * b) / findGCD(a, b);
}
private static void swap(int i, int j, char[] arr) {
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
public static Pair asFraction(long a, long b) {
long gcd = gcd(a, b);
return new Pair(a / gcd, b / gcd);
}
static class Pair {
long x, y, z;
Pair(int x, int y) {
this.x = (int) x;
this.y = (int) y;
}
Pair(long x, long y) {
this.x = x;
this.y = y;
}
Pair(long x, long y, long z) {
this.x = x;
this.y = y;
this.z = z;
}
}
}
| Java | ["3\n\n4\n\n3 1 5 3\n\n3\n\n3 2 1\n\n1\n\n7331"] | 2 seconds | ["YES\nNO\nYES"] | NoteIn the first test case, we can do the following for $$$a = [3, 1, 5, 3]$$$:Step $$$1$$$: $$$a$$$$$$[3, 1, 5, 3]$$$$$$\Rightarrow$$$$$$[3, 1, 5]$$$$$$\Rightarrow$$$$$$[3, 1]$$$$$$\Rightarrow$$$$$$[3]$$$$$$\Rightarrow$$$$$$[]$$$$$$b$$$$$$[]$$$$$$[\underline{3}]$$$$$$[3, \underline{5}]$$$$$$[3, \underline{1}, 5]$$$$$$[3, \underline{3}, 1, 5]$$$Step $$$2$$$: $$$b$$$$$$[3, 3, \underline{1}, 5]$$$$$$\Rightarrow$$$$$$[3, \underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{5}]$$$$$$\Rightarrow$$$$$$[]$$$$$$c$$$$$$[]$$$$$$[1]$$$$$$[1, 3]$$$$$$[1, 3, 3]$$$$$$[1, 3, 3, 5]$$$ As a result, array $$$c = [1, 3, 3, 5]$$$ and it's sorted. | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings"
] | 95b35c53028ed0565684713a93910860 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — the array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,200 | For each test, print YES (case-insensitive), if you can make array $$$c$$$ sorted in non-decreasing order. Otherwise, print NO (case-insensitive). | standard output | |
PASSED | 48cf163636ab126827e8d9e43c1cb0fb | train_107.jsonl | 1651502100 | You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps: Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements. Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements. Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order? | 256 megabytes | import java.util.*;
public class Problem1674D {
public static void main(String[] args) {
var sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
boolean flag = true;
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
for (int i = n % 2; i < n; i += 2) {
if (a[i] > a[i + 1]) {
int tmp = a[i];
a[i] = a[i + 1];
a[i + 1] = tmp;
}
}
for (int i = 1; i < n; i++) {
if (a[i] < a[i - 1]) {
flag = false;
break;
}
}
if (flag) System.out.println("YES");
else System.out.println("NO");
}
}
}
| Java | ["3\n\n4\n\n3 1 5 3\n\n3\n\n3 2 1\n\n1\n\n7331"] | 2 seconds | ["YES\nNO\nYES"] | NoteIn the first test case, we can do the following for $$$a = [3, 1, 5, 3]$$$:Step $$$1$$$: $$$a$$$$$$[3, 1, 5, 3]$$$$$$\Rightarrow$$$$$$[3, 1, 5]$$$$$$\Rightarrow$$$$$$[3, 1]$$$$$$\Rightarrow$$$$$$[3]$$$$$$\Rightarrow$$$$$$[]$$$$$$b$$$$$$[]$$$$$$[\underline{3}]$$$$$$[3, \underline{5}]$$$$$$[3, \underline{1}, 5]$$$$$$[3, \underline{3}, 1, 5]$$$Step $$$2$$$: $$$b$$$$$$[3, 3, \underline{1}, 5]$$$$$$\Rightarrow$$$$$$[3, \underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{5}]$$$$$$\Rightarrow$$$$$$[]$$$$$$c$$$$$$[]$$$$$$[1]$$$$$$[1, 3]$$$$$$[1, 3, 3]$$$$$$[1, 3, 3, 5]$$$ As a result, array $$$c = [1, 3, 3, 5]$$$ and it's sorted. | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings"
] | 95b35c53028ed0565684713a93910860 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — the array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,200 | For each test, print YES (case-insensitive), if you can make array $$$c$$$ sorted in non-decreasing order. Otherwise, print NO (case-insensitive). | standard output | |
PASSED | b9b45699e6c16c1e485aa66baf6e5744 | train_107.jsonl | 1651502100 | You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps: Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements. Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements. Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order? | 256 megabytes |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.*;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
/*
@author : sanskarXrawat
@date : 4/18/2022
@time : 4:49 PM
*/
@SuppressWarnings("ALL")
public class Demo {
public static void main(String[] args) throws Throwable {
Thread thread = new Thread (null, new TaskAdapter (), "", 1 << 29);
thread.start ();
thread.join ();
}
static class TaskAdapter implements Runnable {
@Override
public void run() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastInput in = new FastInput (inputStream);
FastOutput out = new FastOutput (outputStream);
Solution solver = new Solution ();
try {
solver.solve (1, in, out);
} catch (Exception e) {
e.printStackTrace ();
}
in.close ();
out.close ();
}
}
@SuppressWarnings("unused")
static class Solution {
static final Debug debug = new Debug (true);
static int[][] dirs = new int[][]{{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
public void solve(int testNumber, FastInput in, FastOutput out) throws Exception {
int test=in.ri ();
outer: while (test-->0){
int n=in.ri ();
int[] arr=new int[n];
for (int i=0;i<n;i++){
arr[i]=in.ri ();
}
int i=n%2;
while (i<n){
if(arr[i]>arr[i+1]){
arr[i]=arr[i]^arr[i+1]^(arr[i+1]=arr[i]);
}
i+=2;
}
boolean flag=true;
for(i=1;i<n;i++){
flag&=arr[i]>=arr[i-1];
}
out.prtl (flag?"YES":"NO");
}
}
}
static class FastOutput implements AutoCloseable, Closeable, Appendable {
private final StringBuilder cache = new StringBuilder (THRESHOLD * 2);
private static final int THRESHOLD = 32 << 10;
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;
}
private void afterWrite() {
if (cache.length () < THRESHOLD) {
return;
}
flush ();
}
public FastOutput(Writer os) {
this.os = os;
}
public FastOutput(OutputStream os) {
this (new OutputStreamWriter (os));
}
public FastOutput append(char c) {
cache.append (c);
afterWrite ();
return this;
}
public FastOutput append(String c) {
cache.append (c);
afterWrite ();
return this;
}
public FastOutput println(String c) {
return append (c).println ();
}
public FastOutput println() {
return append ('\n');
}
final <T> void prt(T a) {
append (a + " ");
}
final <T> void prtl(T a) {
append (a + "\n");
}
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 ();
}
public FastOutput printf(String format, Object... args) {
return append (String.format (format, args));
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L) return 19;
if (l >= 100000000000000000L) return 18;
if (l >= 10000000000000000L) return 17;
if (l >= 1000000000000000L) return 16;
if (l >= 100000000000000L) return 15;
if (l >= 10000000000000L) return 14;
if (l >= 1000000000000L) return 13;
if (l >= 100000000000L) return 12;
if (l >= 10000000000L) return 11;
if (l >= 1000000000L) return 10;
if (l >= 100000000L) return 9;
if (l >= 10000000L) return 8;
if (l >= 1000000L) return 7;
if (l >= 100000L) return 6;
if (l >= 10000L) return 5;
if (l >= 1000L) return 4;
if (l >= 100L) return 3;
if (l >= 10L) return 2;
return 1;
}
private static int countDigits(int l) {
if (l >= 1000000000) return 10;
if (l >= 100000000) return 9;
if (l >= 10000000) return 8;
if (l >= 1000000) return 7;
if (l >= 100000) return 6;
if (l >= 10000) return 5;
if (l >= 1000) return 4;
if (l >= 100) return 3;
if (l >= 10) return 2;
return 1;
}
}
static class FastInput {
private final StringBuilder defaultStringBuf = new StringBuilder (1 << 13);
private final ByteBuffer tokenBuf = new ByteBuffer ();
private final byte[] buf = new byte[1 << 13];
private SpaceCharFilter filter;
private final InputStream is;
private int bufOffset;
private int bufLen;
private int next;
private int ptr;
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 String next() {
return readString ();
}
public int ri() {
return readInt ();
}
public int readInt() {
boolean rev = false;
skipBlank ();
if (next == '+' || next == '-') {
rev = next == '-';
next = read ();
}
int val = 0;
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read ();
}
return rev ? val : -val;
}
public long readLong() {
boolean rev = false;
skipBlank ();
if (next == '+' || next == '-') {
rev = next == '-';
next = read ();
}
long val = 0L;
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read ();
}
return rev ? val : -val;
}
public long rl() {
return readLong ();
}
public String readString(StringBuilder builder) {
skipBlank ();
while (next > 32) {
builder.append ((char) next);
next = read ();
}
return builder.toString ();
}
public String readString() {
defaultStringBuf.setLength (0);
return readString (defaultStringBuf);
}
public int rs(char[] data, int offset) {
return readString (data, offset);
}
public char[] rsc() {
return readString ().toCharArray ();
}
public int rs(char[] data) {
return rs (data, 0);
}
public int readString(char[] data, int offset) {
skipBlank ();
int originalOffset = offset;
while (next > 32) {
data[offset++] = (char) next;
next = read ();
}
return offset - originalOffset;
}
public char rc() {
return readChar ();
}
public char readChar() {
skipBlank ();
char c = (char) next;
next = read ();
return c;
}
public double rd() {
return nextDouble ();
}
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, readInt ());
if (c < '0' || c > '9')
throw new InputMismatchException ();
res *= 10;
res += c - '0';
c = read ();
}
if (c == '.') {
c = read ();
double m = 1;
while (!isSpaceChar (c)) {
if (c == 'e' || c == 'E')
return res * Math.pow (10, readInt ());
if (c < '0' || c > '9')
throw new InputMismatchException ();
m /= 10;
res += (c - '0') * m;
c = read ();
}
}
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar (c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
public final int readByteUnsafe() {
if (ptr < bufLen) return buf[ptr++];
ptr = 0;
try {
bufLen = is.read (buf);
if (bufLen > 0) {
return buf[ptr++];
} else {
return -1;
}
} catch (IOException e) {
throw new UncheckedIOException (e);
}
}
public final int readByte() {
if (ptr < bufLen) return buf[ptr++];
ptr = 0;
try {
bufLen = is.read (buf);
if (bufLen > 0) {
return buf[ptr++];
} else {
throw new java.io.EOFException ();
}
} catch (IOException e) {
throw new UncheckedIOException (e);
}
}
public final String nextLine() {
tokenBuf.clear ();
for (int b = readByte (); b != '\n'; b = readByteUnsafe ()) {
if (b == -1) break;
tokenBuf.append (b);
}
return new String (tokenBuf.getRawBuf (), 0, tokenBuf.size ());
}
public final String nl() {
return nextLine ();
}
public final boolean hasNext() {
for (int b = readByteUnsafe (); b <= 32 || b >= 127; b = readByteUnsafe ()) {
if (b == -1) return false;
}
--ptr;
return true;
}
public void readArray(Object T) {
if (T instanceof int[]) {
int[] arr = (int[]) T;
for (int i = 0; i < arr.length; i++) {
arr[i] = ri ();
}
}
if (T instanceof long[]) {
long[] arr = (long[]) T;
for (int i = 0; i < arr.length; i++) {
arr[i] = rl ();
}
}
if (T instanceof double[]) {
double[] arr = (double[]) T;
for (int i = 0; i < arr.length; i++) {
arr[i] = rd ();
}
}
if (T instanceof char[]) {
char[] arr = (char[]) T;
for (int i = 0; i < arr.length; i++) {
arr[i] = readChar ();
}
}
if (T instanceof String[]) {
String[] arr = (String[]) T;
for (int i = 0; i < arr.length; i++) {
arr[i] = next ();
}
}
if (T instanceof int[][]) {
int[][] arr = (int[][]) T;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
arr[i][j] = ri ();
}
}
}
if (T instanceof char[][]) {
char[][] arr = (char[][]) T;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
arr[i][j] = readChar ();
}
}
}
if (T instanceof long[][]) {
long[][] arr = (long[][]) T;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
arr[i][j] = rl ();
}
}
}
}
public final void close() {
try {
is.close ();
} catch (IOException e) {
throw new UncheckedIOException (e);
}
}
private static final class ByteBuffer {
private static final int DEFAULT_BUF_SIZE = 1 << 12;
private byte[] buf;
private int ptr = 0;
private ByteBuffer(int capacity) {
this.buf = new byte[capacity];
}
private ByteBuffer() {
this (DEFAULT_BUF_SIZE);
}
private ByteBuffer append(int b) {
if (ptr == buf.length) {
int newLength = buf.length << 1;
byte[] newBuf = new byte[newLength];
System.arraycopy (buf, 0, newBuf, 0, buf.length);
buf = newBuf;
}
buf[ptr++] = (byte) b;
return this;
}
private char[] toCharArray() {
char[] chs = new char[ptr];
for (int i = 0; i < ptr; i++) {
chs[i] = (char) buf[i];
}
return chs;
}
private byte[] getRawBuf() {
return buf;
}
private int size() {
return ptr;
}
private void clear() {
ptr = 0;
}
}
}
static class Debug {
private final boolean offline;
private final PrintStream out = System.err;
static int[] empty = new int[0];
public Debug(boolean enable) {
offline = enable && System.getSecurityManager () == null;
}
public Debug debug(String name, Object x) {
return debug (name, x, empty);
}
public Debug debug(String name, long x) {
if (offline) {
debug (name, "" + x);
}
return this;
}
public Debug debug(String name, String x) {
if (offline) {
out.printf ("%s=%s", name, x);
out.println ();
}
return this;
}
public Debug debug(String name, Object x, int... indexes) {
if (offline) {
if (x == null || !x.getClass ().isArray ()) {
out.append (name);
for (int i : indexes) {
out.printf ("[%d]", i);
}
out.append ("=").append ("" + x);
out.println ();
} else {
indexes = Arrays.copyOf (indexes, indexes.length + 1);
if (x instanceof byte[]) {
byte[] arr = (byte[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug (name, arr[i], indexes);
}
} else if (x instanceof short[]) {
short[] arr = (short[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug (name, arr[i], indexes);
}
} else if (x instanceof boolean[]) {
boolean[] arr = (boolean[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug (name, arr[i], indexes);
}
} else if (x instanceof char[]) {
char[] arr = (char[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug (name, arr[i], indexes);
}
} else if (x instanceof int[]) {
int[] arr = (int[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug (name, arr[i], indexes);
}
} else if (x instanceof float[]) {
float[] arr = (float[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug (name, arr[i], indexes);
}
} else if (x instanceof double[]) {
double[] arr = (double[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug (name, arr[i], indexes);
}
} else if (x instanceof long[]) {
long[] arr = (long[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug (name, arr[i], indexes);
}
} else {
Object[] arr = (Object[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug (name, arr[i], indexes);
}
}
}
}
return this;
}
}
} | Java | ["3\n\n4\n\n3 1 5 3\n\n3\n\n3 2 1\n\n1\n\n7331"] | 2 seconds | ["YES\nNO\nYES"] | NoteIn the first test case, we can do the following for $$$a = [3, 1, 5, 3]$$$:Step $$$1$$$: $$$a$$$$$$[3, 1, 5, 3]$$$$$$\Rightarrow$$$$$$[3, 1, 5]$$$$$$\Rightarrow$$$$$$[3, 1]$$$$$$\Rightarrow$$$$$$[3]$$$$$$\Rightarrow$$$$$$[]$$$$$$b$$$$$$[]$$$$$$[\underline{3}]$$$$$$[3, \underline{5}]$$$$$$[3, \underline{1}, 5]$$$$$$[3, \underline{3}, 1, 5]$$$Step $$$2$$$: $$$b$$$$$$[3, 3, \underline{1}, 5]$$$$$$\Rightarrow$$$$$$[3, \underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{5}]$$$$$$\Rightarrow$$$$$$[]$$$$$$c$$$$$$[]$$$$$$[1]$$$$$$[1, 3]$$$$$$[1, 3, 3]$$$$$$[1, 3, 3, 5]$$$ As a result, array $$$c = [1, 3, 3, 5]$$$ and it's sorted. | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings"
] | 95b35c53028ed0565684713a93910860 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — the array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,200 | For each test, print YES (case-insensitive), if you can make array $$$c$$$ sorted in non-decreasing order. Otherwise, print NO (case-insensitive). | standard output | |
PASSED | 56d9bafe2b403aeb1e59a8c256d9a996 | train_107.jsonl | 1651502100 | You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps: Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements. Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements. Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order? | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class pb2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0){
int n = sc.nextInt();
int[] arr = new int[n];
int[] c = new int[n];
for (int i = 0; i< n ; i++){
arr[i] = sc.nextInt();
}
int ind = 0;
if (n%2 != 0){
c[0] = arr[0];
ind++;
}
for (int i = ind ; i < n ; i+=2){
c[ind++] = Math.min(arr[i], arr[i+1]);
c[ind++] = Math.max(arr[i], arr[i+1]);
}
Arrays.sort(arr);
boolean flag = true;
for (int i = 0; i < n ; i++){
if (arr[i] != c[i]){
flag = false;
break;
}
}
if (flag){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
}
}
| Java | ["3\n\n4\n\n3 1 5 3\n\n3\n\n3 2 1\n\n1\n\n7331"] | 2 seconds | ["YES\nNO\nYES"] | NoteIn the first test case, we can do the following for $$$a = [3, 1, 5, 3]$$$:Step $$$1$$$: $$$a$$$$$$[3, 1, 5, 3]$$$$$$\Rightarrow$$$$$$[3, 1, 5]$$$$$$\Rightarrow$$$$$$[3, 1]$$$$$$\Rightarrow$$$$$$[3]$$$$$$\Rightarrow$$$$$$[]$$$$$$b$$$$$$[]$$$$$$[\underline{3}]$$$$$$[3, \underline{5}]$$$$$$[3, \underline{1}, 5]$$$$$$[3, \underline{3}, 1, 5]$$$Step $$$2$$$: $$$b$$$$$$[3, 3, \underline{1}, 5]$$$$$$\Rightarrow$$$$$$[3, \underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{3}, 5]$$$$$$\Rightarrow$$$$$$[\underline{5}]$$$$$$\Rightarrow$$$$$$[]$$$$$$c$$$$$$[]$$$$$$[1]$$$$$$[1, 3]$$$$$$[1, 3, 3]$$$$$$[1, 3, 3, 5]$$$ As a result, array $$$c = [1, 3, 3, 5]$$$ and it's sorted. | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings"
] | 95b35c53028ed0565684713a93910860 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — the array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,200 | For each test, print YES (case-insensitive), if you can make array $$$c$$$ sorted in non-decreasing order. Otherwise, print NO (case-insensitive). | standard output | |
PASSED | baeb54c80a8f8f873d6f35125ad5c310 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.io.*;
import java.util.*;
public class DesktopRearrangement {
private static final char ICON = '*';
private static final char EMPTY = '.';
public static void solve(FastIO io) {
final int N = io.nextInt();
final int M = io.nextInt();
final int Q = io.nextInt();
IntFenwickTreeRangeSum st = IntFenwickTreeRangeSum.newWithSize(N * M);
final char[][] A = new char[N][];
int icons = 0;
for (int r = 0; r < N; ++r) {
A[r] = io.nextLine().toCharArray();
for (int c = 0; c < M; ++c) {
if (A[r][c] == ICON) {
int index = c * N + r;
st.insert(index, 1L);
++icons;
}
}
}
for (int q = 0; q < Q; ++q) {
final int R = io.nextInt() - 1;
final int C = io.nextInt() - 1;
int index = C * N + R;
if (A[R][C] == ICON) {
A[R][C] = EMPTY;
st.insert(index, 0L);
--icons;
} else {
A[R][C] = ICON;
st.insert(index, 1L);
++icons;
}
io.println(icons - st.get(0, icons - 1));
}
}
/*
* Zero-indexed Fenwick Tree to compute range sums.
* You need ceil(log2(N)) bits to store values N values from the range [0, N).
* Commonly used bits values:
* - For N = 10^3, need bits = 10.
* - For N = 10^4, need bits = 14.
* - For N = 10^5, need bits = 17.
* - For N = 10^6, need bits = 20.
*/
public static class IntFenwickTreeRangeSum {
private int[] partial;
public IntFenwickTreeRangeSum(int bits) {
partial = new int[1 << bits];
}
public void insert(int index, long value) {
long delta = value - get(index, index);
increment(index, delta);
}
public void increment(int index, long value) {
int curr = index;
while (curr < partial.length) {
partial[curr] += value;
curr += Integer.lowestOneBit(~curr);
}
}
public int get(int index) {
return get(index, index);
}
public int get(int loInclusive, int hiInclusive) {
int sum = prefixSum(hiInclusive);
if (loInclusive > 0) {
sum -= prefixSum(loInclusive - 1);
}
return sum;
}
private int prefixSum(int hiInclusive) {
int sum = 0;
int curr = hiInclusive;
while (curr >= 0) {
sum += partial[curr];
curr -= Integer.lowestOneBit(~curr);
}
return sum;
}
public static IntFenwickTreeRangeSum newWithSize(int size) {
return new IntFenwickTreeRangeSum(Integer.SIZE - Integer.numberOfLeadingZeros(size));
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.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;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = 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;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 0eb8306c40dca82d3910426f459a2ba6 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
public class DesktopRearrangement {
private static final char ICON = '*';
private static final char EMPTY = '.';
public static void solve(FastIO io) {
final int N = io.nextInt();
final int M = io.nextInt();
final int Q = io.nextInt();
IntFenwickTreeRangeSum st = IntFenwickTreeRangeSum.newWithSize(N * M);
final char[][] A = new char[N][];
int icons = 0;
for (int r = 0; r < N; ++r) {
A[r] = io.nextLine().toCharArray();
for (int c = 0; c < M; ++c) {
if (A[r][c] == ICON) {
int index = c * N + r;
st.insert(index, 1L);
++icons;
}
}
}
for (int q = 0; q < Q; ++q) {
final int R = io.nextInt() - 1;
final int C = io.nextInt() - 1;
int index = C * N + R;
if (A[R][C] == ICON) {
A[R][C] = EMPTY;
st.insert(index, 0L);
--icons;
} else {
A[R][C] = ICON;
st.insert(index, 1L);
++icons;
}
io.println(icons - st.get(0, icons - 1));
}
}
/*
* Zero-indexed Fenwick Tree to compute range sums.
* You need ceil(log2(N)) bits to store values N values from the range [0, N).
* Commonly used bits values:
* - For N = 10^3, need bits = 10.
* - For N = 10^4, need bits = 14.
* - For N = 10^5, need bits = 17.
* - For N = 10^6, need bits = 20.
*/
public static class FenwickTreeRangeSum {
private long[] partial;
public FenwickTreeRangeSum(int bits) {
partial = new long[1 << bits];
}
public void insert(int index, long value) {
long delta = value - get(index, index);
increment(index, delta);
}
public void increment(int index, long value) {
int curr = index;
while (curr < partial.length) {
partial[curr] += value;
curr += Integer.lowestOneBit(~curr);
}
}
public long get(int index) {
return get(index, index);
}
public long get(int loInclusive, int hiInclusive) {
long sum = prefixSum(hiInclusive);
if (loInclusive > 0) {
sum -= prefixSum(loInclusive - 1);
}
return sum;
}
private long prefixSum(int hiInclusive) {
long sum = 0;
int curr = hiInclusive;
while (curr >= 0) {
sum += partial[curr];
curr -= Integer.lowestOneBit(~curr);
}
return sum;
}
public static FenwickTreeRangeSum newWithSize(int size) {
return new FenwickTreeRangeSum(Integer.SIZE - Integer.numberOfLeadingZeros(size));
}
}
/*
* Zero-indexed Fenwick Tree to compute range sums.
* You need ceil(log2(N)) bits to store values N values from the range [0, N).
* Commonly used bits values:
* - For N = 10^3, need bits = 10.
* - For N = 10^4, need bits = 14.
* - For N = 10^5, need bits = 17.
* - For N = 10^6, need bits = 20.
*/
public static class IntFenwickTreeRangeSum {
private int[] partial;
public IntFenwickTreeRangeSum(int bits) {
partial = new int[1 << bits];
}
public void insert(int index, long value) {
long delta = value - get(index, index);
increment(index, delta);
}
public void increment(int index, long value) {
int curr = index;
while (curr < partial.length) {
partial[curr] += value;
curr += Integer.lowestOneBit(~curr);
}
}
public int get(int index) {
return get(index, index);
}
public int get(int loInclusive, int hiInclusive) {
int sum = prefixSum(hiInclusive);
if (loInclusive > 0) {
sum -= prefixSum(loInclusive - 1);
}
return sum;
}
private int prefixSum(int hiInclusive) {
int sum = 0;
int curr = hiInclusive;
while (curr >= 0) {
sum += partial[curr];
curr -= Integer.lowestOneBit(~curr);
}
return sum;
}
public static IntFenwickTreeRangeSum newWithSize(int size) {
return new IntFenwickTreeRangeSum(Integer.SIZE - Integer.numberOfLeadingZeros(size));
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.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;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = 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;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 37f65184368e567e03512270caf01a07 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
public class DesktopRearrangement {
private static final char ICON = '*';
private static final char EMPTY = '.';
public static void solve(FastIO io) {
final int N = io.nextInt();
final int M = io.nextInt();
final int Q = io.nextInt();
FenwickTreeRangeSum st = FenwickTreeRangeSum.newWithSize(N * M);
final char[][] A = new char[N][];
int icons = 0;
for (int r = 0; r < N; ++r) {
A[r] = io.nextLine().toCharArray();
for (int c = 0; c < M; ++c) {
if (A[r][c] == ICON) {
int index = c * N + r;
st.insert(index, 1L);
++icons;
}
}
}
for (int q = 0; q < Q; ++q) {
final int R = io.nextInt() - 1;
final int C = io.nextInt() - 1;
int index = C * N + R;
if (A[R][C] == ICON) {
A[R][C] = EMPTY;
st.insert(index, 0L);
--icons;
} else {
A[R][C] = ICON;
st.insert(index, 1L);
++icons;
}
io.println(icons - st.get(0, icons - 1));
}
}
/*
* Zero-indexed Fenwick Tree to compute range sums.
* You need ceil(log2(N)) bits to store values N values from the range [0, N).
* Commonly used bits values:
* - For N = 10^3, need bits = 10.
* - For N = 10^4, need bits = 14.
* - For N = 10^5, need bits = 17.
* - For N = 10^6, need bits = 20.
*/
public static class FenwickTreeRangeSum {
private long[] partial;
public FenwickTreeRangeSum(int bits) {
partial = new long[1 << bits];
}
public void insert(int index, long value) {
long delta = value - get(index, index);
increment(index, delta);
}
public void increment(int index, long value) {
int curr = index;
while (curr < partial.length) {
partial[curr] += value;
curr += Integer.lowestOneBit(~curr);
}
}
public long get(int index) {
return get(index, index);
}
public long get(int loInclusive, int hiInclusive) {
long sum = prefixSum(hiInclusive);
if (loInclusive > 0) {
sum -= prefixSum(loInclusive - 1);
}
return sum;
}
private long prefixSum(int hiInclusive) {
long sum = 0;
int curr = hiInclusive;
while (curr >= 0) {
sum += partial[curr];
curr -= Integer.lowestOneBit(~curr);
}
return sum;
}
public static FenwickTreeRangeSum newWithSize(int size) {
return new FenwickTreeRangeSum(Integer.SIZE - Integer.numberOfLeadingZeros(size));
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.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;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = 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;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 3149b15ceef70ea567534e786025a484 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
public class DesktopRearrangement {
private static final char ICON = '*';
private static final char EMPTY = '.';
public static void solve(FastIO io) {
final int N = io.nextInt();
final int M = io.nextInt();
final int Q = io.nextInt();
AVLTreeRangeSum st = new AVLTreeRangeSum();
final char[][] A = new char[N][];
int icons = 0;
for (int r = 0; r < N; ++r) {
A[r] = io.nextLine().toCharArray();
for (int c = 0; c < M; ++c) {
if (A[r][c] == ICON) {
long index = c * N + r;
st.insert(index, 1L);
++icons;
}
}
}
for (int q = 0; q < Q; ++q) {
final int R = io.nextInt() - 1;
final int C = io.nextInt() - 1;
long index = C * N + R;
if (A[R][C] == ICON) {
A[R][C] = EMPTY;
st.insert(index, 0L);
--icons;
} else {
A[R][C] = ICON;
st.insert(index, 1L);
++icons;
}
io.println(icons - st.get(0L, icons - 1L));
}
}
/*
* AVLTreeRangeSum performs arbitrary-length range sums in O(log N) time.
*/
public static class AVLTreeRangeSum {
private AVLTreeNode root = new AVLTreeNode(0);
public void insert(long k, long v) {
root.insert(k, v);
root = AVLTreeNode.rebalance(root);
}
public void increment(long k, long v) {
root.increment(k, v);
root = AVLTreeNode.rebalance(root);
}
public long get(long k) {
return root.get(k);
}
public long get(long lo, long hi) {
return root.get(lo, hi);
}
public static class AVLTreeNode {
private long key;
private long val;
private long sum;
private int ht;
private AVLTreeNode left;
private AVLTreeNode right;
public AVLTreeNode(long k) {
this.key = k;
}
public void insert(long k, long v) {
AVLTreeNode[] path = getLeafToRootPath(k);
path[0].val = v;
updatePath(path);
}
public void increment(long k, long v) {
AVLTreeNode[] path = getLeafToRootPath(k);
path[0].val += v;
updatePath(path);
}
public long get(long k) {
return get(k, k);
}
public long get(long lo, long hi) {
AVLTreeNode curr = this;
while (curr != null) {
if (lo <= curr.key && curr.key <= hi) {
break;
}
if (hi < curr.key) {
curr = curr.left;
} else if (lo > curr.key) {
curr = curr.right;
}
}
if (curr == null) {
return 0;
}
long ans = curr.val;
if (curr.left != null) {
ans += curr.left.getSumGTE(lo);
}
if (curr.right != null) {
ans += curr.right.getSumLTE(hi);
}
return ans;
}
private AVLTreeNode[] getLeafToRootPath(long k) {
ArrayList<AVLTreeNode> lst = new ArrayList<>();
AVLTreeNode curr = this;
lst.add(curr);
while (curr.key != k) {
if (k < curr.key) {
curr = curr.left = getOrCreate(curr.left, k);
} else {
curr = curr.right = getOrCreate(curr.right, k);
}
lst.add(curr);
}
Collections.reverse(lst);
return lst.toArray(new AVLTreeNode[0]);
}
private static AVLTreeNode rotateRight(AVLTreeNode root) {
AVLTreeNode pivot = root.left;
root.left = pivot.right;
pivot.right = root;
root.update();
pivot.update();
return pivot;
}
private static AVLTreeNode rotateLeft(AVLTreeNode root) {
AVLTreeNode pivot = root.right;
root.right = pivot.left;
pivot.left = root;
root.update();
pivot.update();
return pivot;
}
private static void updatePath(AVLTreeNode[] path) {
for (AVLTreeNode node : path) {
node.left = rebalance(node.left);
node.right = rebalance(node.right);
node.update();
}
}
private void update() {
computeHeight();
computeSum();
}
private int computeHeight() {
ht = 1 + Math.max(getHeight(left), getHeight(right));
return ht;
}
private long computeSum() {
sum = val + getSum(left) + getSum(right);
return sum;
}
private long getSumLTE(long k) {
AVLTreeNode curr = this;
long sum = 0;
while (curr != null) {
if (k < curr.key) {
curr = curr.left;
} else {
sum += curr.val + getSum(curr.left);
curr = curr.right;
}
}
return sum;
}
private long getSumGTE(long k) {
AVLTreeNode curr = this;
long sum = 0;
while (curr != null) {
if (k > curr.key) {
curr = curr.right;
} else {
sum += curr.val + getSum(curr.right);
curr = curr.left;
}
}
return sum;
}
private static AVLTreeNode rebalance(AVLTreeNode node) {
if (node == null) {
return null;
}
int bf = balanceFactor(node);
if (bf > 1) {
return rotateRight(node);
} else if (bf < -1) {
return rotateLeft(node);
} else {
return node;
}
}
private static int balanceFactor(AVLTreeNode root) {
return getHeight(root.left) - getHeight(root.right);
}
private static AVLTreeNode getOrCreate(AVLTreeNode node, long k) {
if (node != null) {
return node;
}
return new AVLTreeNode(k);
}
private static int getHeight(AVLTreeNode node) {
if (node == null) {
return 0;
}
return node.ht;
}
private static long getSum(AVLTreeNode node) {
if (node == null) {
return 0;
}
return node.sum;
}
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.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;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = 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;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 7c78d9765e996cf563208c2f7b84c70c | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.util.*;
public class ACM {
private static int pre = 0, icon = 0;
private static int rows, cols;
private static char[][] desktop;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
rows = in.nextInt();
cols = in.nextInt();
int q = in.nextInt();
in.nextLine();
desktop = new char[rows][cols];
for (int r = 0; r < rows; r++) {
String s = in.nextLine();
for (int c = 0; c < cols; c++) {
desktop[r][c] = s.charAt(c);
if (desktop[r][c] == '*') icon++;
}
}
for (int r = 0, c = 0, i = 0; i < icon; i++) {
if (desktop[r][c] == '*') pre++;
if (r == rows - 1) {
r = 0; c++;
} else {
r++;
}
}
for (; q > 0; q--) {
int r = in.nextInt();
int c = in.nextInt();
help(r - 1, c - 1);
}
}
private static void help(int r, int c) {
if (desktop[r][c] == '.') {
desktop[r][c] = '*';
icon++;
int cc = icon / rows;
int rr = (icon + rows - 1) % rows;
if (rr == rows - 1) cc--;
if (c * rows + r + 1 <= icon) pre++;
if (desktop[rr][cc] == '*' && (rr != r || cc != c)) pre++;
} else {
int cc = icon / rows;
int rr = (icon + rows - 1) % rows;
if (rr == rows - 1) cc--;
if (c * rows + r + 1 <= icon) pre--;
if (desktop[rr][cc] == '*' && (rr != r || cc != c)) pre--;
desktop[r][c] = '.';
icon--;
}
System.out.println(icon - pre);
}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | b474f8b1a01641e79f0319a65da48e8c | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class A {
public static void main(String[] args) {
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
int m = sc.nextInt();
int q = sc.nextInt();
char[][] arr = new char[n][m];
int cnt = 0;
for (int i = 0; i < n; i++) {
String s = sc.next();
for (int j = 0; j < m; j++) {
arr[i][j] = s.charAt(j);
if (arr[i][j] == '*') cnt++;
}
}
int res = 0;
int cntJ = (cnt + n - 1) / n - 1;
int cntI = (cnt - 1) % n;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (arr[i][j] == '*' && (j > cntJ || j == cntJ && i > cntI)) {
res++;
}
}
}
for (int pp = 0; pp < q; pp++) {
int i = sc.nextInt() - 1;
int j = sc.nextInt() - 1;
if (arr[i][j] == '*') {
arr[i][j] = '.';
cntJ = (cnt + n - 1) / n - 1;
cntI = (cnt - 1) % n;
if (j > cntJ || j == cntJ && i > cntI) {
res--;
}
if (arr[cntI][cntJ] == '*') {
res++;
}
cnt--;
} else {
arr[i][j] = '*';
cnt++;
cntJ = (cnt + n - 1) / n - 1;
cntI = (cnt - 1) % n;
if (j > cntJ || j == cntJ && i >= cntI) {
res++;
}
if (arr[cntI][cntJ] == '*') {
res--;
}
}
out.println(res);
}
out.close();
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | fae8b2db1d12fd08b8252775bf4a0cae | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.System.out;
import java.util.*;
import java.io.*;
import java.math.*;
public class HelloWorld{
public static void main(String []args) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int row=Integer.parseInt(st.nextToken());
int col=Integer.parseInt(st.nextToken());
int q=Integer.parseInt(st.nextToken());
int[] arr=new int[row*col];
boolean[] b=new boolean[row*col];
int sum=0;
for(int i=0;i<row;i++){
st = new StringTokenizer(infile.readLine());
char[] c=st.nextToken().toCharArray();
for(int j=0;j<c.length;j++){
if(c[j]=='*'){
arr[row*j+i]=1;
b[row*j+i]=true;
sum++;
}
}
}
SEG seg=new SEG(4*row*col,arr);
int len=arr.length;
seg.build(1,0,len-1);
for(int i=0;i<q;i++){
st = new StringTokenizer(infile.readLine());
int r=Integer.parseInt(st.nextToken());
int c=Integer.parseInt(st.nextToken());
r--;
c--;
int idx=c*row+r;
if(b[idx]==true){
b[idx]=false;
sum--;
seg.update(1,0,len-1,idx,idx,0);
}
else{
b[idx]=true;
sum++;
seg.update(1,0,len-1,idx,idx,1);
}
int ans=sum-seg.query(1,0,len-1,0,sum-1);
System.out.println(ans);
}
}
}
class SEG{
int[] tr;
int[] arr;
public SEG(int size, int[] a){
tr=new int[size];
arr=a;
}
public void update(int id,int ss,int se,int qs, int qe, int val){
if(ss==qs && se==qe){
tr[id]=val;
return;
}
if(qe<ss || qs>se) return;
int tm = (ss + se) / 2;
update(id*2, ss, tm,qs,qe,val);
update(id*2+1, tm+1, se,qs,qe,val);
tr[id] = tr[id*2] + tr[id*2+1];
}
public int query(int v,int ss,int se,int l, int r){
if (l > r) return 0;
if (l == ss && r == se) {
return tr[v];
}
int tm = (ss + se) / 2;
return query(v*2, ss, tm, l, min(r, tm))
+ query(v*2+1, tm+1, se, max(l, tm+1), r);
}
public void build(int id,int l,int r){
if(l==r){
tr[id]=arr[l];
return;
}
int tm = (l + r) / 2;
build(id*2, l, tm);
build(id*2+1, tm+1, r);
tr[id] = tr[id*2] + tr[id*2+1];
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 2341f2d5e3601890624a14603d608597 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.System.out;
import java.util.*;
import java.io.*;
import java.math.*;
public class HelloWorld{
static int[] arr;
//static int[] tr;
public static void main(String []args) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int row=Integer.parseInt(st.nextToken());
int col=Integer.parseInt(st.nextToken());
int q=Integer.parseInt(st.nextToken());
arr=new int[row*col];
//tr=new int[4*row*col];
boolean[] b=new boolean[row*col];
int sum=0;
for(int i=0;i<row;i++){
st = new StringTokenizer(infile.readLine());
char[] c=st.nextToken().toCharArray();
for(int j=0;j<c.length;j++){
if(c[j]=='*'){
arr[row*j+i]=1;
b[row*j+i]=true;
sum++;
}
}
}
SEG seg=new SEG(4*row*col,arr);
int len=arr.length;
seg.build(1,0,len-1);
for(int i=0;i<q;i++){
st = new StringTokenizer(infile.readLine());
int r=Integer.parseInt(st.nextToken());
int c=Integer.parseInt(st.nextToken());
r--;
c--;
int idx=c*row+r;
if(b[idx]==true){
b[idx]=false;
sum--;
seg.update(1,0,len-1,idx,idx,0);
}
else{
b[idx]=true;
sum++;
seg.update(1,0,len-1,idx,idx,1);
}
int ans=sum-seg.query(1,0,len-1,0,sum-1);
System.out.println(ans);
}
}
}
class SEG{
static int[] tr;
static int[] arr;
public SEG(int size, int[] a){
tr=new int[size];
arr=a;
}
public static void update(int id,int ss,int se,int qs, int qe, int val){
if(ss==qs && se==qe){
tr[id]=val;
return;
}
if(qe<ss || qs>se) return;
int tm = (ss + se) / 2;
update(id*2, ss, tm,qs,qe,val);
update(id*2+1, tm+1, se,qs,qe,val);
tr[id] = tr[id*2] + tr[id*2+1];
}
public static int query(int v,int ss,int se,int l, int r){
if (l > r) return 0;
if (l == ss && r == se) {
return tr[v];
}
int tm = (ss + se) / 2;
return query(v*2, ss, tm, l, min(r, tm))
+ query(v*2+1, tm+1, se, max(l, tm+1), r);
}
public static void build(int id,int l,int r){
if(l==r){
tr[id]=arr[l];
return;
}
int tm = (l + r) / 2;
build(id*2, l, tm);
build(id*2+1, tm+1, r);
tr[id] = tr[id*2] + tr[id*2+1];
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 8e104ffe15fb5d36dfc1d6ded16928dc | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.System.out;
import java.util.*;
import java.io.*;
import java.math.*;
public class HelloWorld{
static int[] arr;
static int[] tr;
public static void main(String []args) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int row=Integer.parseInt(st.nextToken());
int col=Integer.parseInt(st.nextToken());
int q=Integer.parseInt(st.nextToken());
arr=new int[row*col];
tr=new int[4*row*col];
boolean[] b=new boolean[row*col];
int sum=0;
for(int i=0;i<row;i++){
st = new StringTokenizer(infile.readLine());
char[] c=st.nextToken().toCharArray();
for(int j=0;j<c.length;j++){
if(c[j]=='*'){
arr[row*j+i]=1;
b[row*j+i]=true;
sum++;
}
}
}
int len=arr.length;
build(1,0,len-1);
for(int i=0;i<q;i++){
st = new StringTokenizer(infile.readLine());
int r=Integer.parseInt(st.nextToken());
int c=Integer.parseInt(st.nextToken());
r--;
c--;
int idx=c*row+r;
if(b[idx]==true){
b[idx]=false;
sum--;
update(1,0,len-1,idx,idx,0);
}
else{
b[idx]=true;
sum++;
update(1,0,len-1,idx,idx,1);
}
int ans=sum-query(1,0,len-1,0,sum-1);
System.out.println(ans);
}
}
public static void update(int id,int ss,int se,int qs, int qe, int val){
if(ss==qs && se==qe){
tr[id]=val;
return;
}
if(qe<ss || qs>se) return;
int tm = (ss + se) / 2;
update(id*2, ss, tm,qs,qe,val);
update(id*2+1, tm+1, se,qs,qe,val);
tr[id] = tr[id*2] + tr[id*2+1];
}
public static int query(int v,int ss,int se,int l, int r){
if (l > r) return 0;
if (l == ss && r == se) {
return tr[v];
}
int tm = (ss + se) / 2;
return query(v*2, ss, tm, l, min(r, tm))
+ query(v*2+1, tm+1, se, max(l, tm+1), r);
}
public static void build(int id,int l,int r){
if(l==r){
tr[id]=arr[l];
return;
}
int tm = (l + r) / 2;
build(id*2, l, tm);
build(id*2+1, tm+1, r);
tr[id] = tr[id*2] + tr[id*2+1];
}
//public static void build(long[] arr, int n, StringTokenizer st){
// for(int i=0;i<n;i++) arr[i]=Long.parseLong(st.nextToken());
//}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 6f31d345f6ba4e4e098484212461ccd4 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | /**
* help code : https://www.geeksforgeeks.org/segment-tree-efficient-implementation/
*
* @author vivek
* programming is thinking, not typing
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.StringTokenizer;
public class F {
static int []tree;
static int na;
static void build( int []arr)
{
int n=arr.length;
// insert leaf nodes in tree
for (int i = 0; i < n; i++)
tree[n + i] = arr[i];
// build the tree by calculating
// parents
for (int i = n - 1; i > 0; --i)
tree[i] = tree[i << 1] +
tree[i << 1 | 1];
}
static void updateTreeNode(int p, int value)
{
// set value at position p
tree[p + na] = value;
p = p + na;
// move upward and update parents
for (int i = p; i > 1; i >>= 1)
tree[i >> 1] = tree[i] + tree[i^1];
}
static int query(int l, int r)
{
int res = 0;
// loop to find the sum in the range
for (l += na, r += na; l < r;
l >>= 1, r >>= 1)
{
if ((l & 1) > 0)
res += tree[l++];
if ((r & 1) > 0)
res += tree[--r];
}
return res;
}
private static void solveTC(int __) {
/* For Google */
// ans.append("Case #").append(__).append(": ");
//code start
int n = scn.nextInt();
int m = scn.nextInt();
int q = scn.nextInt();
String[] s = new String[n];
for (int i = 0; i < n; i++) {
s[i] = scn.next();
}
int curr = 0;
int[] arr = new int[n * m];
for (int j = 0; j < m; j++) {
for (int i = 0; i < n; i++) {
int ele = s[i].charAt(j) == '*' ? 1 : 0;
arr[j * n + i] = ele;
curr += ele;
}
}
tree = new int[2 * n * m];
na = n * m;
build(arr);
while (q-- > 0) {
int a = scn.nextInt() - 1;
int b = scn.nextInt() - 1;
int index = b * n + a;
int val = query(index, index + 1);
if (val == 0) {
updateTreeNode(index, 1);
curr++;
} else {
updateTreeNode(index, 0);
curr--;
}
System.out.println(curr - query(0, curr));
}
//code end
// print("\n");
}
public static void main(String[] args) {
scn = new Scanner();
ans = new StringBuilder();
// int t = scn.nextInt();
int t = 1;
// int limit= ;
// sieve(limit);
/*
try {
System.setOut(new PrintStream(new File("file_i_o\\output.txt")));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
*/
for (int i = 1; i <= t; i++) {
solveTC(i);
}
System.out.print(ans);
}
//Stuff for prime start
/**
* sorting algos
*/
private static void sort(int[] arr) {
ArrayList<Integer> li = new ArrayList<>(arr.length);
for (int ele : arr) li.add(ele);
Collections.sort(li);
for (int i = 0; i < li.size(); i++) {
arr[i] = li.get(i);
}
}
private static void sort(long[] arr) {
ArrayList<Long> li = new ArrayList<>(arr.length);
for (long ele : arr) li.add(ele);
Collections.sort(li);
for (int i = 0; i < li.size(); i++) {
arr[i] = li.get(i);
}
}
private static void sort(float[] arr) {
ArrayList<Float> li = new ArrayList<>(arr.length);
for (float ele : arr) li.add(ele);
Collections.sort(li);
for (int i = 0; i < li.size(); i++) {
arr[i] = li.get(i);
}
}
private static void sort(double[] arr) {
ArrayList<Double> li = new ArrayList<>(arr.length);
for (double ele : arr) li.add(ele);
Collections.sort(li);
for (int i = 0; i < li.size(); i++) {
arr[i] = li.get(i);
}
}
/**
* List containing prime numbers <br>
* <b>i<sup>th</sup></b> position contains <b>i<sup>th</sup></b> prime number <br>
* 0th index is <b>null</b>
*/
private static ArrayList<Integer> listOfPrimes;
/**
* query <b>i<sup>th</sup></b> element to get if its prime of not
*/
private static boolean[] isPrime;
/**
* Performs Sieve of Erathosnesis and initialise isPrime array and listOfPrimes list
*
* @param limit the number till which sieve is to be performed
*/
private static void sieve(int limit) {
listOfPrimes = new ArrayList<>();
listOfPrimes.add(null);
boolean[] array = new boolean[limit + 1];
Arrays.fill(array, true);
array[0] = false;
array[1] = false;
for (int i = 2; i <= limit; i++) {
if (array[i]) {
for (long j = (long) i * i; j <= limit; j += i) {
array[(int) j] = false;
}
}
}
isPrime = array;
for (int i = 0; i <= limit; i++) {
if (array[i]) {
listOfPrimes.add(i);
}
}
}
//stuff for prime end
/**
* Calculates the Least Common Multiple of two numbers
*
* @param a First number
* @param b Second Number
* @return Least Common Multiple of <b>a</b> and <b>b</b>
*/
private static long lcm(long a, long b) {
return a * b / gcd(a, b);
}
/**
* Calculates the Greatest Common Divisor of two numbers
*
* @param a First number
* @param b Second Number
* @return Greatest Common Divisor of <b>a</b> and <b>b</b>
*/
private static long gcd(long a, long b) {
return (b == 0) ? a : gcd(b, a % b);
}
static void print(Object obj) {
ans.append(obj.toString());
}
static Scanner scn;
static StringBuilder ans;
//Fast Scanner
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() {
br = new BufferedReader(new
InputStreamReader(System.in));
/*
try {
br = new BufferedReader(new
InputStreamReader(new FileInputStream(new File("file_i_o\\input.txt"))));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
*/
}
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;
}
int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = nextInt();
}
return array;
}
Integer[] nextIntegerArray(int n) {
Integer[] array = new Integer[n];
for (int i = 0; i < n; i++) {
array[i] = nextInt();
}
return array;
}
long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; i++) {
array[i] = nextLong();
}
return array;
}
String[] nextStringArray() {
return nextLine().split(" ");
}
String[] nextStringArray(int n) {
String[] array = new String[n];
for (int i = 0; i < n; i++) {
array[i] = next();
}
return array;
}
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | d98610c10f829a73cbb1ab18f6e47a8f | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import static java.lang.Math.*;
import java.util.*;
import java.io.*;
public class x1674F {
public static void main(String args[]) throws Exception {
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
int Q = Integer.parseInt(st.nextToken());
int[][] grid = new int[N][M];
for(int r=0; r < N; r++)
{
String line = infile.readLine().trim();
for(int c=0; c < M; c++)
if(line.charAt(c) == '*')
grid[r][c] = 1;
}
int total = 0;
for(int r=0; r < N; r++)
for(int c=0; c < M; c++)
total += grid[r][c];
int turn = total;
int res = 0;
for(int c=0; c < M; c++)
for(int r=0; r < N; r++)
{
if(turn == 0)
continue;
res += grid[r][c]^1;
turn--;
}
int[] bruhR = new int[1<<20];
int[] bruhC = new int[1<<20];
int tag = 1;
for(int c=0; c < M; c++)
for(int r=0; r < N; r++)
{
bruhR[tag] = r;
bruhC[tag] = c;
tag++;
}
StringBuilder sb = new StringBuilder();
for(int q=0; q < Q; q++)
{
st = new StringTokenizer(infile.readLine());
int r = Integer.parseInt(st.nextToken())-1;
int c = Integer.parseInt(st.nextToken())-1;
if(grid[r][c] == 0)
{
total++;
int tR = bruhR[total];
int tC = bruhC[total];
boolean inside = false;
if(c < tC)
inside = true;
if(c == tC && r < tR)
inside = true;
if(tR == r && tC == c);
else
{
if(grid[tR][tC] == 0)
res++;
if(inside)
res--;
}
}
else
{
int tR = bruhR[total];
int tC = bruhC[total];
boolean inside = false;
if(c < tC)
inside = true;
if(c == tC && r < tR)
inside = true;
if(tR == r && tC == c);
else
{
if(grid[tR][tC] == 0)
res--;
if(inside)
res++;
}
total--;
}
grid[r][c] ^= 1;
sb.append(res+"\n");
}
System.out.print(sb);
}
public static int[] readArr(int N, BufferedReader infile, StringTokenizer st) throws Exception {
int[] arr = new int[N];
st = new StringTokenizer(infile.readLine());
for(int i=0; i < N; i++)
arr[i] = Integer.parseInt(st.nextToken());
return arr;
}
}
/*
3 3 3
...
...
...
1 2
2 1
3 1
*/ | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | afe144c484e5a89758a91019eb3359ea | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static class SegmentTree {
int bound;
int[] a;
int[] f;
public SegmentTree(int bound){
this.bound = bound;
a = new int[bound+1];
f = new int[4*bound+1];
}
void buildTree(int idx, int tl, int tr){
if(tl == tr){
f[idx] = a[tl];
return;
}
int m = tl + (tr - tl) / 2;
buildTree(idx*2, tl, m);
buildTree(idx*2+1, m+1, tr);
f[idx] = f[idx*2] + f[idx*2+1];
}
public void update(int idx, int tl, int tr, int pos, int val){
if(tl == tr){
f[idx] = val;
return;
}
int m = tl + (tr - tl) / 2;
if(pos <= m){
update(idx*2, tl, m, pos, val);
}
else{
update(idx*2+1, m+1, tr, pos, val);
}
f[idx] = f[idx*2] + f[idx*2+1];
}
public void add(int idx, int l, int r, int x, int y){
f[idx] += y;
if(l == r){return;}
int m = ((l+r)>>1);
if(x <= m){
add(idx + idx, l, m, x, y);
}
else{
add(idx + idx + 1, m+1, r, x, y);
}
}
public int rangeSum(int idx, int l, int r, int s, int t){
if(l > r || s > t){
return 0;
}
if(l == s && r == t){
return f[idx];
}
int m = ((l+r)>>1);
if(t <= m){
return rangeSum(idx + idx, l, m, s,t);
}
else {
if (s > m) {
return rangeSum(idx + idx + 1, m + 1, r, s, t);
} else {
return rangeSum(idx + idx, l, m, s, m) + rangeSum(idx + idx + 1, m + 1, r, m + 1, t);
}
}
}
}
private static void solve(int n, int m, int q, char[][] grid, int[][] queries){
int bound = n * m;
int currSum = 0;
SegmentTree sg = new SegmentTree(bound);
for(int col = 0; col < m; col++){
for(int row = 0; row < n; row++){
int idx = 1 + col * n + row;
if(grid[row][col] == '*'){
sg.a[idx] = 1;
currSum++;
}
}
}
sg.buildTree(1, 1, bound);
for(int[] query: queries){
int x = query[0], y = query[1];
int idx = 1 + y * n + x;
int delta = grid[x][y] == '.'? 1: -1;
grid[x][y] = (grid[x][y] == '.')? '*':'.';
sg.add(1,1,bound,idx,delta);
currSum += delta;
if(currSum < 1){
out.println(0);
continue;
}
int prefixSum = sg.rangeSum(1, 1, bound, 1, currSum);
out.println(currSum - prefixSum);
}
}
public static void main(String[] args){
MyScanner scanner = new MyScanner();
int testCount = 1;
for(int testIdx = 1; testIdx <= testCount; testIdx++){
int n = scanner.nextInt();
int m = scanner.nextInt();
int q = scanner.nextInt();
char[][] grid = new char[n][];
for(int i = 0; i < n; i++){
grid[i] = scanner.nextLine().toCharArray();
}
int[][] queries = new int[q][2];
for(int i = 0; i < q; i++){
queries[i][0] = scanner.nextInt() - 1;
queries[i][1] = scanner.nextInt() - 1;
}
solve(n, m, q, grid, queries);
}
out.close();
}
public static void printResult(int idx, long res){
out.println("Case #" + idx + ": " + res);
}
static void print1DArray(int[] arr){
for(int i = 0; i < arr.length; i++){
out.print(arr[i]);
if(i < arr.length - 1){
out.print(' ');
}
}
out.print('\n');
}
static void print1DArrayList(List<Integer> arrayList){
for(int i = 0; i < arrayList.size(); i++){
out.print(arrayList.get(i));
if(i < arrayList.size() - 1){
out.print(' ');
}
}
out.print('\n');
}
public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | dc0d0ff144482c7c273b4a7ca3e56b38 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.util.Scanner;
public class Solution {
public static void print(char[] arr) {
for(char c: arr) {
System.out.print(c + " ");
}
System.out.println();
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int m = scan.nextInt();
int q = scan.nextInt();
char[] desktop = new char[n*m+1];
for(int i=1; i<=n; i++) {
String s = scan.next();
for(int j=1; j<=s.length(); j++) {
desktop[(j-1)*n+i] = s.charAt(j-1);
}
}
int stars = 0;
for(char c: desktop) {
stars += (c=='*')?1:0;
}
int res[] = new int[q+1];
for(int i=1; i<=stars; i++) {
res[0] += (desktop[i]=='.')?1:0;
}
for(int i=1; i<=q; i++) {
int x = scan.nextInt();
int y = scan.nextInt();
int index = (y-1)*n+x;
if(desktop[index] == '*') {
stars--;
res[i] = (desktop[stars+1] == '*')?res[i-1]:res[i-1]-1;
desktop[index] = '.';
if(index <= stars) {
res[i]++;
}
} else {
stars++;
res[i] = (desktop[stars] == '.')?res[i-1]+1:res[i-1];
desktop[index] = '*';
if(index <= stars) {
res[i]--;
}
}
// print(desktop);
}
for(int i=1; i<res.length; i++) {
System.out.println(res[i]);
}
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | b9812cfaa24dd5ee6a57afeaed920f36 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.io.*;
import java.util.*;
public class F_Desktop_Rearrangement {
public static void main(String[] args) {
FastReader in = new FastReader();
PrintWriter out = new PrintWriter(System.out);
// try {
// out = new PrintWriter("output.txt");
// } catch (Exception e) {
// e.printStackTrace();
// }
int n = in.nextInt(), m = in.nextInt(), q = in.nextInt();
int[][] arr = new int[n+1][m+1];
int[][] prefix = new int[n+1][m+1];
int total = 0;
for (int i = 1; i <= n; i++) {
char[] s = in.next().toCharArray();
for (int j = 1; j <= m; j++) {
arr[i][j] = s[j-1] == '.' ? 0 : 1;
prefix[i][j] = prefix[i-1][j] + arr[i][j];
if (s[j-1] == '*') total++;
}
}
while (q-- > 0) {
int x = in.nextInt(), y = in.nextInt();
if (arr[x][y] == 1) {
arr[x][y] = 0;
total--;
} else {
arr[x][y] = 1;
total++;
}
for (int i = x; i <= n; i++) {
prefix[i][y] = prefix[i-1][y] + arr[i][y];
}
int div = total / n;
int rem = total % n;
int sum = 0;
for (int j = 1; j <= div; j++) {
sum += prefix[n][j];
}
if (rem != 0)
sum += prefix[rem][div+1];
out.println(total - sum);
}
// we calc prefix sum for each column in prefix[n] array
// now for good arrangement we have to fill (total / n) columns first
// then the remaining * will be filled in next col, rem will be total % n
// we calc the stars already within these cols and rows
// then subtrat it from total no. of * as only the remaining * are needed to move
// for each query update the total, prefix[] and arr[] then calc. sum of * already within position
out.flush();
out.close();
}
}
// For fast input output
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
// br = new BufferedReader(new InputStreamReader(System.in));
try {
br = new BufferedReader(new FileReader("input.txt"));
} catch(Exception e) {
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;
}
int[] readIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
long[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nextLong();
}
return a;
}
String[] readStringArray(int n) {
String[] a = new String[n];
for (int i = 0; i < n; i++) {
a[i] = next();
}
return a;
}
}
// end of fast i/o code | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 0ad44ae20293ba4a1ced150ef90eba0f | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes |
import java.io.*;
import java.util.*;
public final class Main {
//int 2e9 - long 9e18
static PrintWriter out = new PrintWriter(System.out);
static FastReader in = new FastReader();
static Pair[] moves = new Pair[]{new Pair(-1, 0), new Pair(0, 1), new Pair(1, 0), new Pair(0, -1)};
static int mod = (int) (1e9 + 7);
static int mod2 = 998244353;
public static void main(String[] args) {
int tt = 1;
while (tt-- > 0) {
solve();
}
out.flush();
}
public static void solve() {
int n = i();
int m = i();
int q = i();
BIT bit = new BIT(n * m);
Set<Integer> set = new HashSet<>();
for (int i = 0; i < n; i++) {
String s = s();
for (int j = 0; j < m; j++) {
if (s.charAt(j) == '*') {
int x = j * n + (i + 1);
bit.update(x, 1);
set.add(x);
}
}
}
while (q-- > 0) {
int a = i() - 1 ;
int b = i() - 1 ;
int x = b * n + a + 1;
if (set.contains(x)) {
set.remove(x);
bit.update(x, -1);
} else {
set.add(x);
bit.update(x, 1);
}
out.println(set.size() - bit.query(1, set.size()));
}
}
static class BIT {
int n;
int[] tree;
public BIT(int n) {
this.n = n;
this.tree = new int[n + 1];
}
public static int lowbit(int x) {
return x & (-x);
}
public void update(int x, int value) {
while (x <= n) {
tree[x] += value;
x += lowbit(x);
}
}
public int query(int x) {
int ans = 0;
while (x > 0) {
ans += tree[x];
x -= lowbit(x);
}
return ans;
}
public int query(int x, int y) {
return query(y) - query(x - 1);
}
}
// (10,5) = 2 ,(11,5) = 3
static long upperDiv(long a, long b) {
return (a / b) + ((a % b == 0) ? 0 : 1);
}
static long sum(int[] a) {
long sum = 0;
for (int x : a) {
sum += x;
}
return sum;
}
static int[] preint(int[] a) {
int[] pre = new int[a.length + 1];
pre[0] = 0;
for (int i = 0; i < a.length; i++) {
pre[i + 1] = pre[i] + a[i];
}
return pre;
}
static long[] pre(int[] a) {
long[] pre = new long[a.length + 1];
pre[0] = 0;
for (int i = 0; i < a.length; i++) {
pre[i + 1] = pre[i] + a[i];
}
return pre;
}
static long[] post(int[] a) {
long[] post = new long[a.length + 1];
post[0] = 0;
for (int i = 0; i < a.length; i++) {
post[i + 1] = post[i] + a[a.length - 1 - i];
}
return post;
}
static long[] pre(long[] a) {
long[] pre = new long[a.length + 1];
pre[0] = 0;
for (int i = 0; i < a.length; i++) {
pre[i + 1] = pre[i] + a[i];
}
return pre;
}
static void print(char A[]) {
for (char c : A) {
out.print(c);
}
out.println();
}
static void print(boolean A[]) {
for (boolean c : A) {
out.print(c + " ");
}
out.println();
}
static void print(int A[]) {
for (int c : A) {
out.print(c + " ");
}
out.println();
}
static void print(long A[]) {
for (long i : A) {
out.print(i + " ");
}
out.println();
}
static void print(List<Integer> A) {
for (int a : A) {
out.print(a + " ");
}
}
static int i() {
return in.nextInt();
}
static long l() {
return in.nextLong();
}
static double d() {
return in.nextDouble();
}
static String s() {
return in.nextLine();
}
static String c() {
return in.next();
}
static int[][] inputWithIdx(int N) {
int A[][] = new int[N][2];
for (int i = 0; i < N; i++) {
A[i] = new int[]{i, in.nextInt()};
}
return A;
}
static int[] input(int N) {
int A[] = new int[N];
for (int i = 0; i < N; i++) {
A[i] = in.nextInt();
}
return A;
}
static long[] inputLong(int N) {
long A[] = new long[N];
for (int i = 0; i < A.length; i++) {
A[i] = in.nextLong();
}
return A;
}
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 == 0) {
return a;
} else {
return GCD(b, a % b);
}
}
static long LCM(int a, int b) {
return (long) a / GCD(a, b) * b;
}
static long LCM(long a, long b) {
return a / GCD(a, b) * b;
}
// find highest i which satisfy a[i]<=x
static int lowerbound(int[] a, int x) {
int l = 0;
int r = a.length - 1;
while (l < r) {
int m = (l + r + 1) / 2;
if (a[m] <= x) {
l = m;
} else {
r = m - 1;
}
}
return l;
}
static void shuffle(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int rand = (int) (Math.random() * arr.length);
int temp = arr[rand];
arr[rand] = arr[i];
arr[i] = temp;
}
}
static void shuffleAndSort(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int rand = (int) (Math.random() * arr.length);
int temp = arr[rand];
arr[rand] = arr[i];
arr[i] = temp;
}
Arrays.sort(arr);
}
static void shuffleAndSort(int[][] arr, Comparator<? super int[]> comparator) {
for (int i = 0; i < arr.length; i++) {
int rand = (int) (Math.random() * arr.length);
int[] temp = arr[rand];
arr[rand] = arr[i];
arr[i] = temp;
}
Arrays.sort(arr, comparator);
}
static void shuffleAndSort(long[] arr) {
for (int i = 0; i < arr.length; i++) {
int rand = (int) (Math.random() * arr.length);
long temp = arr[rand];
arr[rand] = arr[i];
arr[i] = temp;
}
Arrays.sort(arr);
}
static boolean isPerfectSquare(double number) {
double sqrt = Math.sqrt(number);
return ((sqrt - Math.floor(sqrt)) == 0);
}
static void swap(int A[], int a, int b) {
int t = A[a];
A[a] = A[b];
A[b] = t;
}
static void swap(char A[], int a, int b) {
char t = A[a];
A[a] = A[b];
A[b] = t;
}
static long pow(long a, long b, int mod) {
long pow = 1;
long x = a;
while (b != 0) {
if ((b & 1) != 0) {
pow = (pow * x) % mod;
}
x = (x * x) % mod;
b /= 2;
}
return pow;
}
static long pow(long a, long b) {
long pow = 1;
long x = a;
while (b != 0) {
if ((b & 1) != 0) {
pow *= x;
}
x = x * x;
b /= 2;
}
return pow;
}
static long modInverse(long x, int mod) {
return pow(x, mod - 2, mod);
}
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 (int i = 5; i * i <= N; i = i + 6) {
if (N % i == 0 || N % (i + 2) == 0) {
return false;
}
}
return true;
}
public static String reverse(String str) {
if (str == null) {
return null;
}
return new StringBuilder(str).reverse().toString();
}
public static void reverse(int[] arr) {
int l = 0;
int r = arr.length - 1;
while (l < r) {
swap(arr, l, r);
l++;
r--;
}
}
public static String repeat(char ch, int repeat) {
if (repeat <= 0) {
return "";
}
final char[] buf = new char[repeat];
for (int i = repeat - 1; i >= 0; i--) {
buf[i] = ch;
}
return new String(buf);
}
public static int[] manacher(String s) {
char[] chars = s.toCharArray();
int n = s.length();
int[] d1 = new int[n];
for (int i = 0, l = 0, r = -1; i < n; i++) {
int k = (i > r) ? 1 : Math.min(d1[l + r - i], r - i + 1);
while (0 <= i - k && i + k < n && chars[i - k] == chars[i + k]) {
k++;
}
d1[i] = k--;
if (i + k > r) {
l = i - k;
r = i + k;
}
}
return d1;
}
public static int[] kmp(String s) {
int n = s.length();
int[] res = new int[n];
for (int i = 1; i < n; ++i) {
int j = res[i - 1];
while (j > 0 && s.charAt(i) != s.charAt(j)) {
j = res[j - 1];
}
if (s.charAt(i) == s.charAt(j)) {
++j;
}
res[i] = j;
}
return res;
}
}
class Pair {
int i;
int j;
Pair(int i, int j) {
this.i = i;
this.j = j;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Pair pair = (Pair) o;
return i == pair.i && j == pair.j;
}
@Override
public int hashCode() {
return Objects.hash(i, j);
}
}
class ThreePair {
int i;
int j;
int k;
ThreePair(int i, int j, int k) {
this.i = i;
this.j = j;
this.k = k;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ThreePair pair = (ThreePair) o;
return i == pair.i && j == pair.j && k == pair.k;
}
@Override
public int hashCode() {
return Objects.hash(i, j);
}
}
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;
}
}
class Node {
int val;
public Node(int val) {
this.val = val;
}
}
class ST {
int n;
Node[] st;
ST(int n) {
this.n = n;
st = new Node[4 * Integer.highestOneBit(n)];
}
void build(Node[] nodes) {
build(0, 0, n - 1, nodes);
}
private void build(int id, int l, int r, Node[] nodes) {
if (l == r) {
st[id] = nodes[l];
return;
}
int mid = (l + r) >> 1;
build((id << 1) + 1, l, mid, nodes);
build((id << 1) + 2, mid + 1, r, nodes);
st[id] = comb(st[(id << 1) + 1], st[(id << 1) + 2]);
}
void update(int i, Node node) {
update(0, 0, n - 1, i, node);
}
private void update(int id, int l, int r, int i, Node node) {
if (i < l || r < i) {
return;
}
if (l == r) {
st[id] = node;
return;
}
int mid = (l + r) >> 1;
update((id << 1) + 1, l, mid, i, node);
update((id << 1) + 2, mid + 1, r, i, node);
st[id] = comb(st[(id << 1) + 1], st[(id << 1) + 2]);
}
Node get(int x, int y) {
return get(0, 0, n - 1, x, y);
}
private Node get(int id, int l, int r, int x, int y) {
if (x > r || y < l) {
return new Node(0);
}
if (x <= l && r <= y) {
return st[id];
}
int mid = (l + r) >> 1;
return comb(get((id << 1) + 1, l, mid, x, y), get((id << 1) + 2, mid + 1, r, x, y));
}
Node comb(Node a, Node b) {
if (a == null) {
return b;
}
if (b == null) {
return a;
}
return new Node(GCD(a.val, b.val));
}
static int GCD(int a, int b) {
if (b == 0) {
return a;
} else {
return GCD(b, a % b);
}
}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | f6a75bfb17a38fe59fbb4cda88332a69 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.util.*;
public class Main {
public static final int MAXN = 1000;
public static final int COMPONENT_SIZE = (int) (Math.sqrt(MAXN * MAXN) + 10);
public static int fastResult[] = new int[COMPONENT_SIZE];
public static int slowResult[] = new int[MAXN * MAXN];
public static boolean[][] a = new boolean[1000 + 10][1000 + 10];
public static void update(int index, int delta) {
int componentIndex = index / COMPONENT_SIZE;
fastResult[componentIndex] += delta;
slowResult[index] += delta;
}
public static int getSum(int index) {
int componentIndex = index / COMPONENT_SIZE;
int result = 0;
for (int i = 0; i < componentIndex; i++) {
result += fastResult[i];
}
for (int i = componentIndex * COMPONENT_SIZE; i < index; i++) {
result += slowResult[i];
}
return result;
}
public static int getIndex(int x, int y, int n, int m) {
//System.out.println(x + " " + y + " = " + ((y - 1) * n + x - 1));
return (y - 1) * n + x - 1;
}
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
String[] params = scanner.nextLine().split(" ");
int n = Integer.parseInt(params[0]);
int m = Integer.parseInt(params[1]);
int q = Integer.parseInt(params[2]);
for (int i = 1; i <= n; i++) {
String screenLine = scanner.nextLine();
for (int j = 1; j <= m; j++) {
if (screenLine.charAt(j - 1) == '*') {
a[i][j] = true;
update(getIndex(i, j, n, m), 1);
}
}
}
for (; q > 0; q--) {
String line[] = scanner.nextLine().split(" ");
int x = Integer.parseInt(line[0]);
int y = Integer.parseInt(line[1]);
int delta = a[x][y] ? -1 : 1;
update(getIndex(x, y, n, m), delta);
a[x][y] ^= true;
int totalCount = getSum(n * m);
System.out.println(totalCount - getSum(totalCount));
}
}
}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 856695785b6db29a642461c6ab1db3ab | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.util.*;
public class Main {
public static boolean[][] a = new boolean[1000 + 10][1000 + 10];
public static int[][] t = new int[1000 + 10][1000 + 10];
public static int sum(int x, int y) {
int result = 0;
for (int i = x; i >= 0; i = (i & (i + 1)) - 1)
for (int j = y; j >= 0; j = (j & (j + 1)) - 1)
result += t[i][j];
return result;
}
public static void upd(int x, int y, int delta, int n, int m) {
for (int i = x; i < n; i = (i | (i + 1)))
for (int j = y; j < m; j = (j | (j + 1)))
t[i][j] += delta;
}
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
String[] params = scanner.nextLine().split(" ");
int n = Integer.parseInt(params[0]);
int m = Integer.parseInt(params[1]);
int q = Integer.parseInt(params[2]);
int initCount = 0;
for (int i = 1; i <= n; i++) {
String screenLine = scanner.nextLine();
for (int j = 1; j <= m; j++) {
if (screenLine.charAt(j - 1) == '*') {
a[i][j] = true;
initCount++;
upd(i, j, 1, n + 1, m + 1);
}
}
}
for (; q > 0; q--) {
String line[] = scanner.nextLine().split(" ");
int x = Integer.parseInt(line[0]);
int y = Integer.parseInt(line[1]);
int delta = a[x][y] ? -1 : 1;
upd(x, y, delta, n + 1, m + 1);
initCount += delta;
a[x][y] ^= true;
int cFullY = initCount / n;
int cCount = sum(n, cFullY);
int ans = cFullY * n - cCount;
int ost = initCount % n;
ans += ost - sum(ost, cFullY + 1) + sum(ost, cFullY);
System.out.println(ans);
}
}
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | c0bf813023e6ac75ad63a7ecfe7efc5f | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.util.*;
import java.io.*;
import java.lang.reflect.Array;
public class tr0 {
static PrintWriter out;
static StringBuilder sb;
static long mod = (long) 1e9 + 7;
static long inf = (long) 1e16;
static ArrayList<Integer>[] ad, ad1;
static int[][] remove, add;
static long[] inv, f, ncr[];
static HashMap<Integer, Integer> hm;
static int[] pre, suf, Smax[], Smin[];
static int idmax, idmin;
static ArrayList<Integer> av;
static HashMap<Integer, Integer> mm;
static boolean[] msks;
static int[] lazy[], lazyCount;
static int[] c, w;
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
out = new PrintWriter(System.out);
int n = sc.nextInt();
int m = sc.nextInt();
char[][] g = new char[n][m];
int q = sc.nextInt();
int c = 0;
TreeSet<Integer> ts=new TreeSet<>();
FenwickTree ft = new FenwickTree(n * m + 2);
for (int i = 0; i < n; i++) {
g[i] = sc.nextLine().toCharArray();
for (int j = 0; j < m; j++)
if (g[i][j] == '*') {
c++;
int id = i + j * n + 1;
ts.add(id);
ft.point_update(id, 1);
}
}
// System.out.println(ts);
while (q-- > 0) {
int x = sc.nextInt() - 1;
int y = sc.nextInt() - 1;
int id = x + y * n + 1;
// System.out.println(id);
if (g[x][y] == '*') {
g[x][y] = '.';
c--;
ft.point_update(id, -1);
} else {
c++;
g[x][y] = '*';
ft.point_update(id, 1);
}
int get = ft.rsq(c);
// out.println(get+" "+c);
out.println(c - get);
}
out.flush();
}
static public class FenwickTree { // one-based DS
int n;
int[] ft;
FenwickTree(int size) {
n = size;
ft = new int[n + 1];
}
int rsq(int b) // O(log n)
{
int sum = 0;
while (b > 0) {
sum += ft[b];
b -= b & -b;
} // min?
return sum;
}
int rsq(int a, int b) {
return rsq(b) - rsq(a - 1);
}
void point_update(int k, int val) // O(log n), update = increment
{
while (k <= n) {
ft[k] += val;
k += k & -k;
} // min?
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public int[] nextArrInt(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nextArrLong(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public int[] nextArrIntSorted(int n) throws IOException {
int[] a = new int[n];
Integer[] a1 = new Integer[n];
for (int i = 0; i < n; i++)
a1[i] = nextInt();
Arrays.sort(a1);
for (int i = 0; i < n; i++)
a[i] = a1[i].intValue();
return a;
}
public long[] nextArrLongSorted(int n) throws IOException {
long[] a = new long[n];
Long[] a1 = new Long[n];
for (int i = 0; i < n; i++)
a1[i] = nextLong();
Arrays.sort(a1);
for (int i = 0; i < n; i++)
a[i] = a1[i].longValue();
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | d115e3b00a152817abde49a6e99ace0b | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.function.DoubleToLongFunction;
public class Codeforces786{
static long mod = 1000000007L;
static MyScanner sc = new MyScanner();
static void solve() {
int x = sc.nextInt();
int y = sc.nextInt();
if(y%x!=0){
out.println(0+" "+0);
}else{
out.println(1+" "+(y/x));
}
}
static void solve2(){
String str = "abcdefghijklmnopqrstuvwxyz";
HashMap<String,Integer> map = new HashMap<>();
int ind = 1;
for(int i = 0;i<26;i++){
for(int j = 0;j<26;j++){
if(i==j) continue;
map.put((str.charAt(i)+""+str.charAt(j)),ind++);
}
}
int n = sc.nextInt();
for(int i = 0;i<n;i++){
String st = sc.nextLine();
out.println(map.get(st));
}
}
static void solve3(){
String s = sc.nextLine();
String t = sc.nextLine();
boolean flag = true;
for(int i = 0;i<t.length();i++){
if(t.charAt(i)!='a') flag = false;
}
if(t.contains("a") && t.length()>1){
out.println(-1);
return;
}
if(t.contains("a") && t.length()==1){
out.println(1);
return;
}
long ans = 1;
for(int i = 1;i<=s.length();i++){
ans *=2;
}
// ans = pow(2,s.length());
out.println(ans);
// out.println(s.length()+1);
}
static void solve4(){
int n= sc.nextInt();
int arr[] = sc.readIntArray(n);
if(n%2==0){
for(int i = 0;i<n;i+=2){
int min = Math.min(arr[i],arr[i+1]);
int max = Math.max(arr[i],arr[i+1]);
arr[i] = min;
arr[i+1] = max;
}
}else{
for(int i = 1;i<n;i+=2){
int min = Math.min(arr[i],arr[i+1]);
int max = Math.max(arr[i],arr[i+1]);
arr[i] = min;
arr[i+1] = max;
}
}
int brr[] = Arrays.copyOf(arr,n);
sort(brr);
for(int i= 0;i<n;i++){
if(arr[i]!=brr[i]){
out.println("NO");
return;
}
}
out.println("YES");
}
static void solve5(){
int n = sc.nextInt();
int arr[]= sc.readIntArray(n);
int brr[] = Arrays.copyOf(arr,n);
sort(brr);
long ans = (brr[0]+1)/2;
ans += (brr[1]+1)/2;
for(int i = 0;i<n-2;i++){
long temp = Math.min(arr[i],arr[i+2]);
temp += ((Math.max(arr[i],arr[i+2])) - temp+1)/2;
ans = Math.min(ans,temp);
}
for(int i = 0;i<n-1;i++){
long temp = (arr[i]+arr[i+1]+2)/3;
temp = Math.max(temp,Math.max((arr[i]+1)/2,(arr[i+1]+1)/2));
ans = Math.min(temp,ans);
}
out.println(ans);
}
static void solve6(){
int n = sc.nextInt();
int m = sc.nextInt();
int q = sc.nextInt();
int arr[][] = new int[n][m];
int total = 0;
for(int i = 0;i<n;i++){
String str = sc.nextLine();
for(int j = 0;j<m;j++){
arr[i][j] = (str.charAt(j)=='*')?1:0;
total+= arr[i][j];
}
}
int brr[][] = new int[n][m];
for(int i = 0;i<n;i++){
for(int j = 0;j<m;j++){
if(i==0){
brr[i][j] = arr[i][j];
}else
brr[i][j]= brr[i-1][j]+arr[i][j];
}
}
for(int i = 0;i<q;i++){
int a = sc.nextInt()-1;
int b = sc.nextInt()-1;
if(arr[a][b]==1){
arr[a][b] = 0;
total--;
for(int j = a;j<n;j++){
brr[j][b]--;
}
}else{
arr[a][b] = 1;
total++;
for(int j = a;j<n;j++){
brr[j][b]++;
}
}
int div = total/n;
int count = 0;
for(int j = 0;j<div;j++){
count+= brr[n-1][j];
}
if(total%n!=0)
count+= brr[(total%n)-1][total/n];
out.println(total-count);
}
}
static void swap(char arr[][],int i,int j){
for(int k = j;k>0;k--){
if(arr[i][k]=='.'&& arr[i][k-1]=='*'){
char temp = arr[i][k];
arr[i][k] = arr[i][k-1];
arr[i][k-1] = temp;
}
}
}
static int search(int pre,int suf[],int i,int j){
while(i<=j){
int mid = (i+j)/2;
if(suf[mid]==pre) return mid;
else if(suf[mid]<pre) j = mid-1;
else i = mid+1;
}
return Integer.MIN_VALUE;
}
static long pow(long a, long b) {
if (b == 0) return 1;
long res = pow(a, b / 2);
res = (res * res) % 1_000_000_007;
if (b % 2 == 1) {
res = (res * a) % 1_000_000_007;
}
return res;
}
static int lis(int arr[],int n){
int lis[] = new int[n];
lis[0] = 1;
for(int i = 1;i<n;i++){
lis[i] = 1;
for(int j = 0;j<i;j++){
if(arr[i]>arr[j]){
lis[i] = Math.max(lis[i],lis[j]+1);
}
}
}
int max = Integer.MIN_VALUE;
for(int i = 0;i<n;i++){
max = Math.max(lis[i],max);
}
return max;
}
static boolean isPali(String str){
int i = 0;
int j = str.length()-1;
while(i<j){
if(str.charAt(i)!=str.charAt(j)){
return false;
}
i++;
j--;
}
return true;
}
static long gcd(long a,long b){
if(b==0) return a;
return gcd(b,a%b);
}
static String reverse(String str){
char arr[] = str.toCharArray();
int i = 0;
int j = arr.length-1;
while(i<j){
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
String st = new String(arr);
return st;
}
static boolean isprime(int n){
if(n==1) return false;
if(n==3 || n==2) return true;
if(n%2==0 || n%3==0) return false;
for(int i = 5;i*i<=n;i+= 6){
if(n%i== 0 || n%(i+2)==0){
return false;
}
}
return true;
}
public static void main(String[] args) {
out = new PrintWriter(new BufferedOutputStream(System.out));
// int t = sc.nextInt();
int t= 1;
while(t-- >0){
// solve();
// solve2();
// solve3();
// solve4();
solve6();
}
// Stop writing your solution here. -------------------------------------
out.close();
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int[] readIntArray(int n){
int arr[] = new int[n];
for(int i = 0;i<n;i++){
arr[i] = Integer.parseInt(next());
}
return arr;
}
int[] reverse(int arr[]){
int n= arr.length;
int i = 0;
int j = n-1;
while(i<j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
j--;i++;
}
return arr;
}
long[] readLongArray(int n){
long arr[] = new long[n];
for(int i = 0;i<n;i++){
arr[i] = Long.parseLong(next());
}
return arr;
}
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;
}
}
private static void sort(int[] arr) {
List<Integer> list = new ArrayList<>();
for (int i=0; i<arr.length; i++){
list.add(arr[i]);
}
Collections.sort(list); // collections.sort uses nlogn in backend
for (int i = 0; i < arr.length; i++){
arr[i] = list.get(i);
}
}
private static void sort(long[] arr) {
List<Long> list = new ArrayList<>();
for (int i=0; i<arr.length; i++){
list.add(arr[i]);
}
Collections.sort(list); // collections.sort uses nlogn in backend
for (int i = 0; i < arr.length; i++){
arr[i] = list.get(i);
}
}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 397f150c1954d11d1125dee92ff0c67d | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | //package codeforce.div3.r786;
//
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.PrintWriter;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import static java.lang.System.out;
import static java.util.stream.Collectors.joining;
/**
* @author pribic (Priyank Doshi)
* @see <a href="https://codeforces.com/contest/1674/problem/F" target="_top">https://codeforces.com/contest/1674/problem/F</a>
* @since 03/05/22 10:17 AM
*/
public class F {
static FastScanner sc = new FastScanner(System.in);
public static void main(String[] args) {
try (PrintWriter out = new PrintWriter(System.out)) {
int T = 1;//sc.nextInt();
for (int tt = 1; tt <= T; tt++) {
int n = sc.nextInt();
int m = sc.nextInt();
int q = sc.nextInt();
char[][] grid = new char[n][m];
for (int i = 0; i < n; i++) {
grid[i] = sc.next().toCharArray();
}
int total = 0;
int[] colCount = new int[m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
total += getCnt(grid, i, j);
colCount[j] += getCnt(grid, i, j);
}
}
while (q-- > 0) {
int x = sc.nextInt() - 1;
int y = sc.nextInt() - 1;
if (grid[x][y] == '.') {
grid[x][y] = '*';
total++;
colCount[y]++;
} else {
grid[x][y] = '.';
total--;
colCount[y]--;
}
int fullCol = total / n;
int halfCol = total % n;
int starsCount = 0;
for (int i = 0; i < fullCol; i++) {
starsCount += colCount[i];
}
for (int i = 0; i < halfCol; i++) {
starsCount += getCnt(grid, i, fullCol);
}
System.out.println(total - starsCount);
}
}
}
}
private static int getCnt(char[][] grid, int x, int y) {
return grid[x][y] == '*' ? 1 : 0;
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f), 32768);
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | e38d705d5630e931cd219f09f602418d | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | //package codeforce.div3.r786;
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.PrintWriter;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import static java.lang.System.out;
import static java.util.stream.Collectors.joining;
/**
* @author pribic (Priyank Doshi)
* @see <a href="https://codeforces.com/contest/1674/problem/F" target="_top">https://codeforces.com/contest/1674/problem/F</a>
* @since 03/05/22 10:17 AM
*/
public class F {
static FastScanner sc = new FastScanner(System.in);
public static void main(String[] args) {
try (PrintWriter out = new PrintWriter(System.out)) {
int T = 1;//sc.nextInt();
for (int tt = 1; tt <= T; tt++) {
int n = sc.nextInt();
int m = sc.nextInt();
int q = sc.nextInt();
char[][] grid = new char[n][m];
for (int i = 0; i < n; i++) {
grid[i] = sc.next().toCharArray();
}
int total = 0;
int[] colCount = new int[m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
total += getCnt(grid, i, j);
colCount[j] += getCnt(grid, i, j);
}
}
while (q-- > 0) {
int x = sc.nextInt() - 1;
int y = sc.nextInt() - 1;
if (grid[x][y] == '.') {
grid[x][y] = '*';
total++;
colCount[y]++;
} else {
grid[x][y] = '.';
total--;
colCount[y]--;
}
int fullCol = total / n;
int halfCol = total % n;
int starsCount = 0;
for (int i = 0; i < fullCol; i++) {
starsCount += colCount[i];
}
for (int i = 0; i < halfCol; i++) {
starsCount += getCnt(grid, i, fullCol);
}
System.out.println(total - starsCount);
}
}
}
}
private static int getCnt(char[][] grid, int x, int y) {
return grid[x][y] == '*' ? 1 : 0;
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f), 32768);
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 4b304685512a8dd1e144047293a23bee | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static Scanner sc = new Scanner(System.in);
public static PrintWriter pw = new PrintWriter(System.out);
public static void main(String[] args) {
solve();
pw.flush();
}
static void solve() {
int H = sc.nextInt();
int W = sc.nextInt();
int Q = sc.nextInt();
int cnt = 0;
int ans = 0;
char[][] s = new char[H][W];
boolean[][] todo = new boolean[H][W];
for( int i = 0; i < H; i++ ) {
s[i] = sc.next().toCharArray();
for( int j = 0; j < W; j++ ) {
if( s[i][j] == '*' ) cnt++;
}
}
for( int j = 0; j < W; j++ ) {
for( int i = 0; i < H; i++ ) {
if( j*H+(i+1) <= cnt ) {
todo[i][j] = true;
if( s[i][j] == '.' ) ans++;
}
}
}
for( int q = 0; q < Q; q++ ) {
int x = sc.nextInt()-1;
int y = sc.nextInt()-1;
if( s[x][y] == '*' ) {
int r = (cnt-1)%H;
int c = (cnt-1)/H;
cnt--;
ans--;
todo[r][c] = false;
if( todo[x][y] ) ans++;
if( s[r][c] == '*' ) ans++;
s[x][y] = '.';
}else {
int r = cnt%H;
int c = cnt/H;
cnt++;
ans++;
todo[r][c] = true;
if( todo[x][y] ) ans--;
if( s[r][c] == '*' ) ans--;
s[x][y] = '*';
}
pw.println(ans);
}
}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | dbbcfe04ee46c4a8534658011dfe75a4 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.util.Scanner;
public class F {
public static void main(String[] args) {
new F().solve();
}
public void solve() {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
int q = scanner.nextInt();
boolean[][] flag = new boolean[n][m];
char[] ch = null;
int totalIcons = 0;
scanner.nextLine();
for (int i = 0; i < n; i++) {
ch = scanner.nextLine().toCharArray();
for (int j = 0; j < m; j++) {
if (ch[j] == '*') {
flag[i][j] = true;
totalIcons++;
}
}
}
int position = -1;
int preIcons = 0;
if (position + 1 < totalIcons) {
loop: for (int j = 0; j < m; j++) {
for (int i = 0; i < n; i++) {
position++;
if (flag[i][j])
preIcons++;
if (position + 1 == totalIcons)
break loop;
}
}
}
while (q-- > 0) {
int x = scanner.nextInt() - 1;
int y = scanner.nextInt() - 1;
int temp = y * n + x;
if (flag[x][y]) {
flag[x][y] = false;
totalIcons--;
if (temp <= position)
preIcons--;
if (flag[position % n][position / n])
preIcons--;
position--;
} else {
flag[x][y] = true;
totalIcons++;
if (temp <= position)
preIcons++;
position++;
if (flag[position % n][position / n])
preIcons++;
}
System.out.println(totalIcons - preIcons);
}
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 0c37304187a61c58c8186388b37517d6 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.*;
public class CF1{
public static void main(String[] args) {
FastScanner sc=new FastScanner();
// int T=sc.nextInt();
int T=1;
for (int tt=1; tt<=T; tt++){
int n= sc.nextInt();
int m = sc.nextInt();
int q = sc.nextInt();
char arr[][]= new char [n][m];
for (int i=0; i<n; i++){
arr[i]=sc.next().toCharArray();
}
int start=0;
int count =0;
for (int i=0; i<n; i++){
for (int j=0; j<m; j++){
if (arr[i][j]=='*') count++;
}
}
int x=1;
for (int j=0; j<m; j++){
for (int i=0; i<n; i++){
if (arr[i][j]=='*'){
if (x>count) start++;
}
x++;
}
}
// System.out.println(start);
for (int i=0; i<q; i++){
int t1= sc.nextInt();
int t2=sc.nextInt();
t1--;
t2--;
if (arr[t1][t2]=='*'){
arr[t1][t2]='.';
int yy =count/n;
if (count%n==0) yy--;
int xx= count%n-1;
if (xx==-1) xx=n-1;
if(t1==xx && t2==yy){
start=start;
}
else if (arr[xx][yy]!='*') {
if (t2>yy || (t2==yy && t1>xx)) start--;
}
else {
if (t2>yy || (t2==yy && t1>xx)) start=start;
else start++;
}
count--;
}
else {
arr[t1][t2]='*';
count++;
if (count==n*m){
start=0;
}
else {
int yy =count/n;
if (count%n==0) yy--;
int xx= count%n-1;
if (xx==-1) xx=n-1;
if(t1==xx && t2==yy){
start=start;
}
else if (arr[xx][yy]=='*') {
if (t2<yy || (t2==yy && t1<xx)) start--;
}
else {
if (t2<yy || (t2==yy && t1<xx)) start=start;
else start++;
}
}
}
System.out.println(start);
}
}
}
static int createPalindrome(int input, int b, int isOdd) {
int n = input;
int palin = input;
if (isOdd == 1)
n /= b;
while (n > 0) {
palin = palin * b + (n % b);
n /= b;
}
return palin;
}
static ArrayList<Integer> arr;
static void generatePalindromes(int n) {
int number;
for (int j = 0; j < 2; j++) {
int i = 1;
while ((number = createPalindrome(i, 10, j % 2)) < n) {
arr.add(number);
i++;
}
}
}
static class SegmentTree{
int nodes[];
int arr[];
int lazy[];
public SegmentTree(int n, int arr[]){
nodes = new int [4*n+1];
lazy= new int [4*n+1];
this.arr=arr;
build(1,1,n);
}
private void build (int v, int l , int r){
if (l==r) {
nodes[v]=arr[l-1];}
else {
int m=(l+r)/2;
build(2*v,l,m);
build(2*v+1,m+1,r);
nodes[v]=Math.min(nodes[2*v], nodes[2*v+1]);
}
}
private void push(int v) {
nodes[v*2] += lazy[v];
lazy[v*2] += lazy[v];
nodes[v*2+1] += lazy[v];
lazy[v*2+1] += lazy[v];
lazy[v] = 0;
}
private void update(int v, int l, int r, int x, int y, int add) {
if (l>y || r<x) return;
if (l>=x && y>=r) {
nodes[v]+=add;
lazy[v]+=add;
}
else {
push(v);
int mid =(l+r)/2;
update(2*v,l,mid,x,y,add);
update(2*v+1,mid+1,r,x,y,add);
nodes[v]=Math.min(nodes[v*2], nodes[v*2+1]);
}
}
private int query(int v, int l, int r, int x, int y){
if (l>y || r<x) return Integer.MAX_VALUE;
if (l>=x && r<=y) return nodes[v];
else {
int m = (l+r)/2;
push(v);
return Math.min(query(2*v+1,m+1,r,x,y),query(2*v,l,m,x,y));
}
}
}
static class LPair{
long x,y;
LPair(long x , long y){
this.x=x;
this.y=y;
}
}
static long prime(long n){
for (long i=3; i*i<=n; i+=2){
if (n%i==0) return i;
}
return -1;
}
static long factorial (int x){
if (x==0) return 1;
long ans =x;
for (int i=x-1; i>=1; i--){
ans*=i;
ans%=mod;
}
return ans;
}
static long mod =1000000007L;
static long power2 (long a, long b){
long res=1;
while (b>0){
if ((b&1)== 1){
res= (res * a % mod)%mod;
}
a=(a%mod * a%mod)%mod;
b=b>>1;
}
return res;
}
static boolean []sieveOfEratosthenes(int n){
boolean prime[] = new boolean[n+1];
for(int i=0;i<=n;i++)
prime[i] = true;
for(int p = 2; p*p <=n; p++)
{
if(prime[p] == true)
{
for(int i = p*p; i <= n; i += p)
prime[i] = false;
}
}
return prime;
}
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 sortLong(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 long gcd (long n, long m){
if (m==0) return n;
else return gcd(m, n%m);
}
static class Pair implements Comparable<Pair>{
int x,y;
private static final int hashMultiplier = BigInteger.valueOf(new Random().nextInt(1000) + 100).nextProbablePrime().intValue();
public Pair(int x, int y){
this.x = x;
this.y = y;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pii = (Pair) o;
if (x != pii.x) return false;
return y == pii.y;
}
public int hashCode() {
return hashMultiplier * x + y;
}
public int compareTo(Pair o){
if (this.x==o.x) return Integer.compare(this.y,o.y);
else return Integer.compare(this.x,o.x);
}
// this.x-o.x is ascending
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 9518087448ce77b536f35d5c70182546 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class Main {
static int t;
static int n, m;
static int[] a;
static String s;
static FastReader fr = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
static int[] sum;
public static long mod = 998244353L;
static boolean flag;
public static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static long Pow(long a, long n, long p) {
long x = a;
long res = 1;
while (n > 0) {
if ((n & 1) != 0) {
res = ((long) res * (long) x) % p;
}
n >>= 1;
x = ((long) x * (long) x) % p;
}
return res;
}
public static int[] p;
public static void initUnion(int size) {
p = new int[size];
for (int i = 0; i < size; i++) {
p[i] = i;
}
}
public static int find(int x) { //查找x元素所在的集合,回溯时压缩路径
if (x != p[x]) {
p[x] = find(p[x]); //回溯时的压缩路径
} //从x结点搜索到祖先结点所经过的结点都指向该祖先结点
return p[x];
}
static class Edge {
int u, v, w, next;
boolean cut;
int used;
int num;
}
static class SegNode {
int left;
int right;
int data;
long lazy;
}
static int MAX_N;
static SegNode[] stu;
static void initSegNode(int n) {
MAX_N = n;
stu = new SegNode[MAX_N * 4];
}
static void pushudown(int rt) {
if (stu[rt] == null) return;
if (rt * 2 >= stu.length || (rt * 2 + 1) >= stu.length) return;
if (stu[rt * 2] == null || stu[rt * 2 + 1] == null) return;
if (stu[rt].lazy > 0) {
stu[rt * 2].lazy += stu[rt].lazy;
stu[rt * 2 +1].lazy += stu[rt].lazy;
stu[rt * 2].data += (stu[rt * 2].right - stu[rt * 2].left + 1)*stu[rt].lazy;
stu[rt * 2 + 1].data += (stu[rt * 2 + 1].right - stu[rt * 2 + 1].left + 1)*stu[rt].lazy;
stu[rt].lazy = 0;
}
}
static void pushup(int ii) {
if (ii * 2 >= stu.length || (ii * 2 + 1) >= stu.length) return;
stu[ii].data = stu[ii * 2].data + stu[ii * 2 + 1].data;
}
static void CreateTree(int ii, int a, int b) {
if (stu[ii] == null) stu[ii] = new SegNode();
stu[ii].left = a;
stu[ii].right = b;
stu[ii].data = 0;
stu[ii].lazy = 0;
if (a == b) {
stu[ii].data = Main.a[a];
return;
} else {
int mid = (a + b) >> 1;
CreateTree(ii * 2, a, mid);
CreateTree(ii * 2 + 1, mid + 1, b);
}
pushup(ii);
}
static void updata(int ii, int a, int b, int at) {
if (ii >= stu.length || stu[ii] == null) return;
try {
if (stu[ii].left == a && stu[ii].right == b) {
stu[ii].lazy += at;
stu[ii].data += (b - a + 1) * at;
return;
}
pushudown(ii);
int mid = (stu[ii].left + stu[ii].right) >> 1;
if (b <= mid) {
updata(ii * 2, a, b, at);
} else if (a > mid) {
updata(ii * 2 + 1, a, b, at);
} else {
updata(ii * 2, a, mid, at);
updata(ii * 2 + 1, mid + 1, b, at);
}
pushup(ii);
} catch (Exception e) {
}
}
static int find1(int ii, int a, int b) {
if (ii >= stu.length || stu[ii] == null) return 0;
if (stu[ii].left == a && stu[ii].right == b) {
return stu[ii].data;
}
pushudown(ii);
int mid = (stu[ii].left + stu[ii].right) >> 1;
if (b <= mid) {
return find1(ii * 2, a, b);
} else if (a > mid) {
return find1(ii * 2 + 1, a, b);
} else {
return find1(ii * 2, a, mid) + find1(ii * 2 + 1, mid + 1, b);
}
}
public static void main(String[] args) {
// int t = fr.nextInt();
// out:
// while ((t --) > 0) {
//
// }
// return;
int n = fr.nextInt();
int m = fr.nextInt();
int q = fr.nextInt();
a = new int[n * m + 1];
char[][] cs = new char[n][m];
int sum = 0;
for (int i = 0; i < n; i++) {
String s = fr.nextString();
cs[i] = s.toCharArray();
for (int j = 0; j < m; j++) {
if (cs[i][j] == '*') {
a[j * n + i + 1] = 1;
sum++;
}
}
}
initSegNode(n * m + 1);
CreateTree(1, 1, n * m);
for (int i = 0; i < q; i++) {
int x = fr.nextInt() - 1;
int y = fr.nextInt() - 1;
int idx = y * n + x + 1;
if (cs[x][y] == '*') {
cs[x][y] = '.';
sum --;
updata(1, idx, idx, -1);
} else {
cs[x][y] = '*';
sum ++;
updata(1, idx, idx, 1);
}
int kt = find1(1, 1, sum);
System.out.println(sum - kt);
}
}
static class FastReader {
private BufferedReader bfr;
private StringTokenizer st;
public FastReader() {
bfr = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
if (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(bfr.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());
}
char nextChar() {
return next().toCharArray()[0];
}
String nextString() {
return next();
}
int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
double[] nextDoubleArray(int n) {
double[] arr = new double[n];
for (int i = 0; i < arr.length; i++)
arr[i] = nextDouble();
return arr;
}
long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = nextLong();
return arr;
}
int[][] nextIntGrid(int nL, int m) {
int[][] grid = new int[n][m];
for (int i = 0; i < n; i++) {
char[] line = fr.next().toCharArray();
for (int j = 0; j < m; j++)
grid[i][j] = line[j] - 48;
}
return grid;
}
}
public static void merge(int arr[], int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int[n1];
int R[] = new int[n2];
for (int i = 0; i < n1; ++i)
L[i] = arr[l + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[m + 1 + j];
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
public static void sort(int arr[], int l, int r) {
if (l < r) {
int m =l+ (r-l)/2;
sort(arr, l, m);
sort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | bad0a0e69085f0b25cfd097fde785f54 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
//--------------------------INPUT READER---------------------------------//
static class fs {
public BufferedReader br;
StringTokenizer st = new StringTokenizer("");
public fs() { this(System.in); }
public fs(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
String next() {
while (!st.hasMoreTokens()) {
try { st = new StringTokenizer(br.readLine()); }
catch (IOException e) { e.printStackTrace(); }
}
return st.nextToken();
}
int ni() { return Integer.parseInt(next()); }
long nl() { return Long.parseLong(next()); }
double nd() { return Double.parseDouble(next()); }
String ns() { return next(); }
int[] na(long nn) {
int n = (int) nn;
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
long[] nal(long nn) {
int n = (int) nn;
long[] l = new long[n];
for(int i = 0; i < n; i++) l[i] = nl();
return l;
}
}
//-----------------------------------------------------------------------//
//---------------------------PRINTER-------------------------------------//
static class Printer {
static PrintWriter w;
public Printer() {this(System.out);}
public Printer(OutputStream os) {
w = new PrintWriter(os);
}
public void p(int i) {w.println(i);}
public void p(long l) {w.println(l);}
public void p(double d) {w.println(d);}
public void p(String s) { w.println(s);}
public void pr(int i) {w.print(i);}
public void pr(long l) {w.print(l);}
public void pr(double d) {w.print(d);}
public void pr(String s) { w.print(s);}
public void pl() {w.println();}
public void close() {w.close();}
}
//-----------------------------------------------------------------------//
//--------------------------VARIABLES------------------------------------//
static fs sc = new fs();
static OutputStream outputStream = System.out;
static Printer w = new Printer(outputStream);
static long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE;
static int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE;
static long mod = 1000000007;
//-----------------------------------------------------------------------//
//--------------------------ADMIN_MODE-----------------------------------//
private static void ADMIN_MODE() throws IOException {
if (System.getProperty("ONLINE_JUDGE") == null) {
w = new Printer(new FileOutputStream("output.txt"));
sc = new fs(new FileInputStream("input.txt"));
}
}
//-----------------------------------------------------------------------//
//----------------------------START--------------------------------------//
public static void main(String[] args)
throws IOException {
ADMIN_MODE();
//int t = sc.ni();while(t-->0)
solve();
w.close();
}
static void solve() throws IOException {
int r = sc.ni();
int c = sc.ni();
int q = sc.ni();
long[] arr = new long[(r*c)+10];
int totElems = 0;
for(int i = 0; i < r; i++) {
char[] strr = sc.ns().toCharArray();
for(int j = 0; j < c; j++) {
if(strr[j] == '*') {
totElems++;
int pos = (j*r)+i;
arr[pos]=1;
}
}
}
st st = new st(arr);
while(q-- > 0) {
int x = sc.ni()-1;
int y = sc.ni()-1;
int pos = (y*r)+x;
if(st.query(pos, pos+1) == 1) {
totElems--;
st.modify(pos, -1);
} else {
totElems++;
st.modify(pos, 1);
}
if(totElems == 0) {
w.p(0);
continue;
}
long already = st.query(0, totElems);
long rem = totElems-already;
w.p(rem);
}
}
static class st {
private int N;
private long UNIQUE = 8123572096793136074L;
private long[] tree;
public st(int size) {
tree = new long[2 * (N = size)];
Arrays.fill(tree, UNIQUE);
}
public st(long[] values) {
this(values.length);
for (int i = 0; i < N; i++) modify(i, values[i]);
}
private long function(long a, long b) {
if (a == UNIQUE) return b;
else if (b == UNIQUE) return a;
return a+b;
}
public void modify(int i, long value) {
tree[i + N] = function(tree[i + N], value);
for (i += N; i > 1; i >>= 1) {
tree[i >> 1] = function(tree[i], tree[i ^ 1]);
}
}
//[l, r)
public long query(int l, int r) {
long res = UNIQUE;
for (l += N, r += N; l < r; l >>= 1, r >>= 1) {
if ((l & 1) != 0) res = function(res, tree[l++]);
if ((r & 1) != 0) res = function(res, tree[--r]);
}
return res;
}
}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 4b106d6caecc2f22d73e6bf4e6c13b94 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.util.*;
// import java.lang.invoke.ConstantBootstraps;
// import java.math.BigInteger;
// import java.beans.IndexedPropertyChangeEvent;
import java.io.*;
@SuppressWarnings("unchecked")
public class Main implements Runnable {
static FastReader in;
static PrintWriter out;
static int bit(long n) {
return (n == 0) ? 0 : (1 + bit(n & (n - 1)));
}
static void p(Object o) {
out.print(o);
}
static void pn(Object o) {
out.println(o);
}
static void pni(Object o) {
out.println(o);
out.flush();
}
static String n() throws Exception {
return in.next();
}
static String nln() throws Exception {
return in.nextLine();
}
static int ni() throws Exception {
return Integer.parseInt(in.next());
}
static long nl() throws Exception {
return Long.parseLong(in.next());
}
static double nd() throws Exception {
return Double.parseDouble(in.next());
}
static class FastReader {
static BufferedReader br;
static StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception {
br = new BufferedReader(new FileReader(s));
}
String next() throws Exception {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new Exception(e.toString());
}
}
return st.nextToken();
}
String nextLine() throws Exception {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
throw new Exception(e.toString());
}
return str;
}
}
static long power(long a, long b) {
if (a == 0L)
return 0L;
if (b == 0)
return 1;
long val = power(a, b / 2);
val = val * val;
if ((b % 2) != 0)
val = val * a;
return val;
}
static long power(long a, long b, long mod) {
if (a == 0L)
return 0L;
if (b == 0)
return 1;
long val = power(a, b / 2L, mod) % mod;
val = (val * val) % mod;
if ((b % 2) != 0)
val = (val * a) % mod;
return val;
}
static ArrayList<Long> prime_factors(long n) {
ArrayList<Long> ans = new ArrayList<Long>();
while (n % 2 == 0) {
ans.add(2L);
n /= 2L;
}
for (long i = 3; i * i <= n; i++) {
while (n % i == 0) {
ans.add(i);
n /= i;
}
}
if (n > 2) {
ans.add(n);
}
return ans;
}
static void sort(ArrayList<Long> a) {
Collections.sort(a);
}
static void reverse_sort(ArrayList<Long> a) {
Collections.sort(a, Collections.reverseOrder());
}
static void swap(long[] a, int i, int j) {
long temp = a[i];
a[i] = a[j];
a[j] = temp;
}
static void swap(List<Long> a, int i, int j) {
long temp = a.get(i);
a.set(j, a.get(i));
a.set(j, temp);
}
static void sieve(boolean[] prime) {
int n = prime.length - 1;
Arrays.fill(prime, true);
for (int i = 2; i * i <= n; i++) {
if (prime[i]) {
for (int j = 2 * i; j <= n; j += i) {
prime[j] = false;
}
}
}
}
static long gcd(long a, long b) {
if (a < b) {
long temp = a;
a = b;
b = temp;
}
if (b == 0)
return a;
return gcd(b, a % b);
}
static HashMap<Long, Long> map_prime_factors(long n) {
HashMap<Long, Long> map = new HashMap<>();
while (n % 2 == 0) {
map.put(2L, map.getOrDefault(2L, 0L) + 1L);
n /= 2L;
}
for (long i = 3; i * i <= n; i++) {
while (n % i == 0) {
map.put(i, map.getOrDefault(i, 0L) + 1L);
n /= i;
}
}
if (n > 2) {
map.put(n, map.getOrDefault(n, 0L) + 1L);
}
return map;
}
static List<Long> divisor(long n) {
List<Long> ans = new ArrayList<>();
ans.add(1L);
long count = 0;
for (long i = 2L; i * i <= n; i++) {
if (n % i == 0) {
if (i == n / i)
ans.add(i);
else {
ans.add(i);
ans.add(n / i);
}
}
}
return ans;
}
static void sum_of_divisors(int n) {
int[] dp = new int[n + 1];
for (int i = 1; i <= n; i++) {
dp[i] += i;
for (int j = i + i; j <= n; j += i) {
dp[j] += i;
}
}
}
static void prime_factorization_using_sieve(int n) {
int[] dp = new int[n + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
for (int i = 2; i <= n; i++) {
dp[i] = Math.min(dp[i], i);// dp[i] stores smallest prime number which divides number i
for (int j = 2 * i; j <= n; j++) {// can calculate prime factorization in O(logn) time by dividing
// val/=dp[val]; till 1 is obtained
dp[j] = Math.min(dp[j], i);
}
}
}
/*
* ----------------------------------------------------Sorting------------------
* ------------------------------------------------
*/
public static void sort(long[] arr, int l, int r) {
if (l >= r)
return;
int mid = (l + r) / 2;
sort(arr, l, mid);
sort(arr, mid + 1, r);
merge(arr, l, mid, r);
}
public static void sort(int[] arr, int l, int r) {
if (l >= r)
return;
int mid = (l + r) / 2;
sort(arr, l, mid);
sort(arr, mid + 1, r);
merge(arr, l, mid, r);
}
static void merge(int[] arr, int l, int mid, int r) {
int[] left = new int[mid - l + 1];
int[] right = new int[r - mid];
for (int i = l; i <= mid; i++) {
left[i - l] = arr[i];
}
for (int i = mid + 1; i <= r; i++) {
right[i - (mid + 1)] = arr[i];
}
int left_start = 0;
int right_start = 0;
int left_length = mid - l + 1;
int right_length = r - mid;
int temp = l;
while (left_start < left_length && right_start < right_length) {
if (left[left_start] < right[right_start]) {
arr[temp] = left[left_start++];
} else {
arr[temp] = right[right_start++];
}
temp++;
}
while (left_start < left_length) {
arr[temp++] = left[left_start++];
}
while (right_start < right_length) {
arr[temp++] = right[right_start++];
}
}
static void merge(long[] arr, int l, int mid, int r) {
long[] left = new long[mid - l + 1];
long[] right = new long[r - mid];
for (int i = l; i <= mid; i++) {
left[i - l] = arr[i];
}
for (int i = mid + 1; i <= r; i++) {
right[i - (mid + 1)] = arr[i];
}
int left_start = 0;
int right_start = 0;
int left_length = mid - l + 1;
int right_length = r - mid;
int temp = l;
while (left_start < left_length && right_start < right_length) {
if (left[left_start] < right[right_start]) {
arr[temp] = left[left_start++];
} else {
arr[temp] = right[right_start++];
}
temp++;
}
while (left_start < left_length) {
arr[temp++] = left[left_start++];
}
while (right_start < right_length) {
arr[temp++] = right[right_start++];
}
}
// static int[] smallest_prime_factor;
// static int count = 1;
// static int[] p = new int[100002];
// static long[] flat_tree = new long[300002];
// static int[] in_time = new int[1000002];
// static int[] out_time = new int[1000002];
// static long[] subtree_gcd = new long[100002];
// static int w = 0;
// static boolean poss = true;
/*
* (a^b^c)%mod
* Using fermats Little theorem
* x^(mod-1)=1(mod)
* so b^c can be written as b^c=x*(mod-1)+y
* then (a^(x*(mod-1)+y))%mod=(a^(x*(mod-1))*a^(y))mod
* the term (a^(x*(mod-1)))%mod=a^(mod-1)*a^(mod-1)
*
*/
// ---------------------------------------------------Segment_Tree----------------------------------------------------------------//
// static class comparator implements Comparator<node> {
// public int compare(node a, node b) {
// return a.a - b.a > 0 ? 1 : -1;
// }
// }
static class Segment_Tree {
private long[] segment_tree;
public Segment_Tree(int n) {
this.segment_tree = new long[4 * n + 1];
}
void build(int index, int left, int right, int[] a) {
if (left == right) {
segment_tree[index] = a[left];
return;
}
int mid = (left + right) / 2;
build(2 * index + 1, left, mid, a);
build(2 * index + 2, mid + 1, right, a);
segment_tree[index] = segment_tree[2 * index + 1] + segment_tree[2 * index + 2];
}
long query(int index, int left, int right, int l, int r) {
if (left > right)
return 0;
if (left >= l && r >= right) {
return segment_tree[index];
}
if (l > right || left > r)
return 0;
int mid = (left + right) / 2;
return query(2 * index + 1, left, mid, l, r) + query(2 * index + 2, mid + 1, right, l, r);
}
void update(int index, int left, int right, int node, int val) {
if (left == right) {
segment_tree[index] = val;
return;
}
int mid = (left + right) / 2;
if (node <= mid)
update(2 * index + 1, left, mid, node, val);
else
update(2 * index + 2, mid + 1, right, node, val);
segment_tree[index] = segment_tree[2 * index + 1] + segment_tree[2 * index + 2];
}
}
static class min_Segment_Tree {
private long[] segment_tree;
public min_Segment_Tree(int n) {
this.segment_tree = new long[4 * n + 1];
}
void build(int index, int left, int right, int[] a) {
if (left == right) {
segment_tree[index] = a[left];
return;
}
int mid = (left + right) / 2;
build(2 * index + 1, left, mid, a);
build(2 * index + 2, mid + 1, right, a);
segment_tree[index] = Math.min(segment_tree[2 * index + 1], segment_tree[2 * index + 2]);
}
long query(int index, int left, int right, int l, int r) {
if (left > right)
return Integer.MAX_VALUE;
if (left >= l && r >= right) {
return segment_tree[index];
}
if (l > right || left > r)
return Integer.MAX_VALUE;
int mid = (left + right) / 2;
return Math.min(query(2 * index + 1, left, mid, l, r), query(2 * index + 2, mid + 1, right, l, r));
}
void update(int index, int left, int right, int node, int val) {
if (left == right) {
segment_tree[index] = val;
return;
}
int mid = (left + right) / 2;
if (node <= mid)
update(2 * index + 1, left, mid, node, val);
else
update(2 * index + 2, mid + 1, right, node, val);
segment_tree[index] = Math.min(segment_tree[2 * index + 1], segment_tree[2 * index + 2]);
}
}
static class max_Segment_Tree {
public long[] segment_tree;
public max_Segment_Tree(int n) {
this.segment_tree = new long[4 * n + 1];
}
void build(int index, int left, int right, long[] a) {
// pn(index+" "+left+" "+right);
if (left == right) {
segment_tree[index] = a[left];
return;
}
int mid = (left + right) / 2;
build(2 * index + 1, left, mid, a);
build(2 * index + 2, mid + 1, right, a);
segment_tree[index] = Math.max(segment_tree[2 * index + 1], segment_tree[2 * index + 2]);
}
long query(int index, int left, int right, int l, int r) {
if (left >= l && r >= right) {
return segment_tree[index];
}
if (l > right || left > r)
return Long.MIN_VALUE;
int mid = (left + right) / 2;
long ans1=query(2 * index + 1, left, mid, l, r);
long ans2=query(2 * index + 2, mid + 1, right, l, r);
long max=Math.max(ans1,ans2);
// pn(index+" "+left+" "+right+" "+max+" "+l+" "+r+" "+ans1+" "+ans2);
return max;
}
void update(int index, int left, int right, int node, int val) {
if (left == right) {
segment_tree[index] += val;
return;
}
int mid = (left + right) / 2;
if (node <= mid)
update(2 * index + 1, left, mid, node, val);
else
update(2 * index + 2, mid + 1, right, node, val);
segment_tree[index] = Math.max(segment_tree[2 * index + 1], segment_tree[2 * index + 2]);
}
}
// // ------------------------------------------------------ DSU
// // --------------------------------------------------------------------//
static class dsu {
private int[] parent;
private int[] rank;
private int[] size;
public dsu(int n) {
this.parent = new int[n + 1];
this.rank = new int[n + 1];
this.size = new int[n + 1];
for (int i = 0; i <= n; i++) {
parent[i] = i;
rank[i] = 1;
size[i] = 1;
}
}
int findParent(int a) {
if (parent[a] == a)
return a;
else
return parent[a] = findParent(parent[a]);
}
void join(int a, int b) {
int parent_a = findParent(a);
int parent_b = findParent(b);
if (parent_a == parent_b)
return;
if (rank[parent_a] > rank[parent_b]) {
parent[parent_b] = parent_a;
size[parent_a] += size[parent_b];
} else if (rank[parent_a] < rank[parent_b]) {
parent[parent_a] = parent_b;
size[parent_b] += size[parent_a];
} else {
parent[parent_a] = parent_b;
size[parent_b] += size[parent_a];
rank[parent_b]++;
}
}
}
// ------------------------------------------------Comparable---------------------------------------------------------------------//
public static class rectangle {
int x1, x3, y1, y3;// lower left and upper rigth coordinates
int x2, y2, x4, y4;// remaining coordinates
/*
* (x4,y4) (x3,y3)
* ____________
* | |
* |____________|
*
* (x1,y1) (x2,y2)
*/
public rectangle(int x1, int y1, int x3, int y3) {
this.x1 = x1;
this.y1 = y1;
this.x3 = x3;
this.y3 = y3;
this.x2 = x3;
this.y2 = y1;
this.x4 = x1;
this.y4 = y3;
}
public long area() {
if (x3 < x1 || y3 < y1)
return 0;
return (long) Math.abs(x1 - x3) * (long) Math.abs(y1 - y3);
}
}
static long intersection(rectangle a, rectangle b) {
if (a.x3 < a.x1 || a.y3 < a.y1 || b.x3 < b.x1 || b.y3 < b.y1)
return 0;
long l1 = ((long) Math.min(a.x3, b.x3) - (long) Math.max(a.x1, b.x1));
long l2 = ((long) Math.min(a.y3, b.y3) - (long) Math.max(a.y1, b.y1));
if (l1 < 0 || l2 < 0)
return 0;
long area = ((long) Math.min(a.x3, b.x3) - (long) Math.max(a.x1, b.x1))
* ((long) Math.min(a.y3, b.y3) - (long) Math.max(a.y1, b.y1));
if (area < 0)
return 0;
return area;
}
// --------------------------------------------------------------Multiset---------------------------------------------------------------//
public static class multiset {
public TreeMap<Integer, Integer> map;
public int size = 0;
public multiset() {
map = new TreeMap<>();
}
public multiset(int[] a) {
map = new TreeMap<>();
size = a.length;
for (int i = 0; i < a.length; i++) {
map.put(a[i], map.getOrDefault(a[i], 0) + 1);
}
}
void add(int a) {
size++;
map.put(a, map.getOrDefault(a, 0) + 1);
}
void remove(int a) {
size--;
int val = map.get(a);
map.put(a, val - 1);
if (val == 1)
map.remove(a);
}
void removeAll(int a) {
if (map.containsKey(a)) {
size -= map.get(a);
map.remove(a);
}
}
int ceiling(int a) {
if (map.ceilingKey(a) != null) {
int find = map.ceilingKey(a);
return find;
} else
return Integer.MIN_VALUE;
}
int floor(int a) {
if (map.floorKey(a) != null) {
int find = map.floorKey(a);
return find;
} else
return Integer.MAX_VALUE;
}
int lower(int a) {
if (map.lowerKey(a) != null) {
int find = map.lowerKey(a);
return find;
} else
return Integer.MAX_VALUE;
}
int higher(int a) {
if (map.higherKey(a) != null) {
int find = map.higherKey(a);
return find;
} else
return Integer.MIN_VALUE;
}
int first() {
return map.firstKey();
}
int last() {
return map.lastKey();
}
boolean contains(int a) {
if (map.containsKey(a))
return true;
return false;
}
int size() {
return size;
}
void clear() {
map.clear();
}
int poll() {
if (map.size() == 0) {
return Integer.MAX_VALUE;
}
size--;
int first = map.firstKey();
if (map.get(first) == 1) {
map.pollFirstEntry();
} else
map.put(first, map.get(first) - 1);
return first;
}
int polllast() {
if (map.size() == 0) {
return Integer.MAX_VALUE;
}
size--;
int last = map.lastKey();
if (map.get(last) == 1) {
map.pollLastEntry();
} else
map.put(last, map.get(last) - 1);
return last;
}
}
static class pair implements Comparable<pair> {
int a;
int b;
int dir;
public pair(int a, int b, int dir) {
this.a = a;
this.b = b;
this.dir = dir;
}
public int compareTo(pair p) {
// if (this.b == Integer.MIN_VALUE || p.b == Integer.MIN_VALUE)
// return (int) (this.index - p.index);
return (int) (this.a - p.a);
}
}
static class pair2 implements Comparable<pair2> {
long a;
int index;
public pair2(long a, int index) {
this.a = a;
this.index = index;
}
public int compareTo(pair2 p) {
return (int) (this.a - p.a);
}
}
static class node implements Comparable<node> {
int l;
int r;
public node(int l, int r) {
this.l = l;
this.r = r;
}
public int compareTo(node a) {
if (this.l == a.l) {
return this.r - a.r;
}
return (int) (this.l - a.l);
}
}
static long ans = 0;
static int leaf = 0;
static boolean poss = true;
static long mod = 1000000007L;
static int[] dx = { -1, 0, 0, 1, -1, -1, 1, 1 };
static int[] dy = { 0, -1, 1, 0, -1, 1, -1, 1 };
static Set<Integer> path_nodes;
int count = 0;
public static void main(String[] args) throws Exception {
// new Thread(null,new Main(), "1", 1 << 26).start();
long start = System.nanoTime();
in = new FastReader();
out = new PrintWriter(System.out, false);
int tc = 1;
while (tc-- > 0) {
int n=ni();
int m=ni();
int q=ni();
int[] a=new int[n*m];
int count=0;
int val=0;
Map<String,Integer> map=new HashMap<>();
for(int j=0;j<m;j++){
for(int i=0;i<n;i++){
map.put(String.valueOf(i)+"#"+String.valueOf(j), val);
val++;
}
}
char[][] c=new char[n][m];
for(int i=0;i<n;i++){
String s=n();
for(int j=0;j<m;j++){
if(s.charAt(j)=='*'){
a[map.get(String.valueOf(i)+"#"+String.valueOf(j))]=1;
c[i][j]='*';
count++;
}else c[i][j]='.';
}
}
Segment_Tree sg=new Segment_Tree(n*m);
sg.build(0, 0, n*m-1, a);
for(int i=0;i<q;i++){
int x=ni()-1;
int y=ni()-1;
sg.update(0, 0, n*m-1, map.get(String.valueOf(x)+"#"+String.valueOf(y)), (c[x][y]=='*')?0:1);
// for(int j=0;j<sg.segment_tree.length;j++){
// p(sg.segment_tree[j]+" ");
// }
// pn("");
if(c[x][y]=='*'){
c[x][y]='.';
count--;
}
else{
c[x][y]='*';
count++;
}
// pn(i+" "+count+" "+sg.query(0, 0, n*m-1, 0, count-1)+" "+c[x][y]+" "+map.get(String.valueOf(x)+"#"+String.valueOf(y)));
pn(count-sg.query(0, 0, n*m-1, 0, count-1));
}
}
long end = System.nanoTime();
// pn((end-start)*1.0/1000000000);
out.flush();
out.close();
}
public void run() {
try {
in = new FastReader();
out = new PrintWriter(System.out);
int tc = ni();
while (tc-- > 0) {
}
out.flush();
} catch (Exception e) {
}
}
static boolean dfs(int i, int p, int x,int y,Set<Integer> k_nodes, boolean[] visited, List<TreeSet<Integer>> arr, int[] dp) {
visited[i] = true;
boolean found=false;
if(k_nodes.contains(i)){
found=true;
}
List<Integer> remove=new ArrayList<>();
for (int nei:arr.get(i)) {
if (visited[nei] || nei == p)continue;
boolean yes=dfs(nei, i, x, y,k_nodes, visited, arr, dp);
if(!yes)remove.add(nei);
// pn(i+" "+nei+" "+yes);
found =found || yes;
}
for(int nei:remove){
arr.get(i).remove(nei);
}
return found;
}
static boolean inside(int i, int j, int n, int m) {
if (i >= 0 && j >= 0 && i < n && j < m)
return true;
return false;
}
static long ncm(long[] fact, long[] fact_inv, int n, int m) {
if (n < m)
return 0L;
long a = fact[n];
long b = fact_inv[n - m];
long c = fact_inv[m];
a = (a * b) % mod;
return (a * c) % mod;
}
static int binary_search(int[] a, int val) {
int l = 0;
int r = a.length - 1;
int ans = 0;
while (l <= r) {
int mid = l + (r - l) / 2;
if (a[mid] <= val) {
ans = mid;
l = mid + 1;
} else
r = mid - 1;
}
return ans;
}
static int[] longest_common_prefix(String s) {
int m = s.length();
int[] lcs = new int[m];
int len = 0;
int i = 1;
lcs[0] = 0;
while (i < m) {
if (s.charAt(i) == s.charAt(len)) {
lcs[i++] = ++len;
} else {
if (len == 0) {
lcs[i] = 0;
i++;
} else
len = lcs[len - 1];
}
}
return lcs;
}
static void swap(char[] a, char[] b, int i, int j) {
char temp = a[i];
a[i] = b[j];
b[j] = temp;
}
static void factorial(long[] fact, long[] fact_inv, int n, long mod) {
fact[0] = 1;
for (int i = 1; i < n; i++) {
fact[i] = (i * fact[i - 1]) % mod;
}
for (int i = 0; i < n; i++) {
fact_inv[i] = power(fact[i], mod - 2, mod);// (1/x)%m can be calculated by fermat's little theoram which is
// (x**(m-2))%m when m is prime
}
// (a^(b^c))%m is equal to, let res=(b^c)%(m-1) then (a^res)%m
// https://www.geeksforgeeks.org/find-power-power-mod-prime/?ref=rp
}
static void find(int i, int n, int[] row, int[] col, int[] d1, int[] d2) {
if (i >= n) {
ans++;
return;
}
for (int j = 0; j < n; j++) {
if (col[j] == 0 && d1[i - j + n - 1] == 0 && d2[i + j] == 0) {
col[j] = 1;
d1[i - j + n - 1] = 1;
d2[i + j] = 1;
find(i + 1, n, row, col, d1, d2);
col[j] = 0;
d1[i - j + n - 1] = 0;
d2[i + j] = 0;
}
}
}
static int answer(int l, int r, int[][] dp) {
if (l > r)
return 0;
if (l == r) {
dp[l][r] = 1;
return 1;
}
if (dp[l][r] != -1)
return dp[l][r];
int val = Integer.MIN_VALUE;
int mid = l + (r - l) / 2;
val = 1 + Math.max(answer(l, mid - 1, dp), answer(mid + 1, r, dp));
return dp[l][r] = val;
}
static void print(int[] a) {
for (int i = 0; i < a.length; i++)
p(a[i] + " ");
pn("");
}
static long count(long n) {
long count = 0;
while (n != 0) {
count += n % 10;
n /= 10;
}
return count;
}
static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
static int LcsOfPrefix(String a, String b) {
int i = 0;
int j = 0;
int count = 0;
while (i < a.length() && j < b.length()) {
if (a.charAt(i) == b.charAt(j)) {
j++;
count++;
}
i++;
}
return a.length() + b.length() - 2 * count;
}
static void reverse(int[] a, int n) {
for (int i = 0; i < n / 2; i++) {
int temp = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = temp;
}
}
static char get_char(int a) {
return (char) (a + 'a');
}
static int find1(int[] a, int val) {
int ans = -1;
int l = 0;
int r = a.length - 1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (a[mid] <= val) {
l = mid + 1;
ans = mid;
} else
r = mid - 1;
}
return ans;
}
static int find2(int[] a, int val) {
int l = 0;
int r = a.length - 1;
int ans = -1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (a[mid] <= val) {
ans = mid;
l = mid + 1;
} else
r = mid - 1;
}
return ans;
}
// static void dfs(List<List<Integer>> arr, int node, int parent, long[] val) {
// p[node] = parent;
// in_time[node] = count;
// flat_tree[count] = val[node];
// subtree_gcd[node] = val[node];
// count++;
// for (int adj : arr.get(node)) {
// if (adj == parent)
// continue;
// dfs(arr, adj, node, val);
// subtree_gcd[node] = gcd(subtree_gcd[adj], subtree_gcd[node]);
// }
// out_time[node] = count;
// flat_tree[count] = val[node];
// count++;
// }
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 7813632b2c461362eb00b55b4568f1e2 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.io.*;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class DesktopRearrangement {
static int mod = 1000000007;
public static void main(String[] args) throws IOException {
FastReader reader = new FastReader();
FastWriter writer = new FastWriter();
int[] nmq = reader.readIntArray(3);
int n = nmq[0], m = nmq[1], q = nmq[2];
char[][] desktop = new char[n][m];
for(int i = 0; i<n; i++){
desktop[i] = reader.readString().toCharArray();
}
//Count the number (u) of * .
// For u, count the number already inside the required space
// The required space is (n/u + n%u) say this is (k)
// without any query, we must move (u-k) = j
//
// when we get a query q, if q adds an icon, the space increases
// by a little, check if its in the space, if not, then we must move it
// into the space. j = (j + 1) if so, then we dont need to move it, j = j
// then check if the spaces increses to include an existing *
// if so then we move one less j = j-1, else we move j.
// print j.
// if q removes an icon, the space decreases, check if the
// the removed icon was in the old space, if so, then we
// still have to move j. if not, then we move j-1.
//
//
int used = 0;
for(int i = 0; i<n; i++){
for(int j = 0; j<m; j++){
if(desktop[i][j] == '*') used++;
}
}
int nc = used/n, in = 0;
int nr = used%n;
for(int i = 0; i<n; i++){
for(int j = 0; j<m; j++){
if(desktop[i][j] == '*') {
if(j < nc || j == nc && i < nr)
in++;
}
}
}
int move = used-in;
int[] ans = new int[q];
for(int i = 0; i<q; i++){
int[] qu = reader.readIntArray(2);
int r = qu[0]-1, c = qu[1]-1;
//System.out.println(desktop[r][c] + " " + nr + " " + nc + " " + r + " " + c );
if(desktop[r][c] != '*'){
if(c > nc ||(c == nc && r > nr)){
move++;
}
if(nc < m && desktop[nr][nc] == '*'){
move--;
}
desktop[r][c] = '*';
used++;
nc = used/n;
nr = used%n;
} else {
desktop[r][c] = '.';
used--;
if(c > nc ||(c == nc && r >= nr)){
move--;
}
nc = used/n;
nr = used%n;
if(nc < m && desktop[nr][nc] == '*'){
move++;
}
}
ans[i] = move;
}
for(int i = 0; i<q; i++){
writer.writeSingleInteger(ans[i]);
}
}
public static void mergeSort(int[] a, int n) {
if (n < 2) {
return;
}
int mid = n / 2;
int[] l = new int[mid];
int[] r = new int[n - mid];
for (int i = 0; i < mid; i++) {
l[i] = a[i];
}
for (int i = mid; i < n; i++) {
r[i - mid] = a[i];
}
mergeSort(l, mid);
mergeSort(r, n - mid);
merge(a, l, r, mid, n - mid);
}
public static void merge(int[] a, int[] l, int[] r, int left, int right) {
int i = 0, j = 0, k = 0;
while (i < left && j < right) {
if (l[i] <= r[j]) {
a[k++] = l[i++];
}
else {
a[k++] = r[j++];
}
}
while (i < left) {
a[k++] = l[i++];
}
while (j < right) {
a[k++] = r[j++];
}
}
public static class FastReader {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer;
public int readSingleInt() throws IOException {
return Integer.parseInt(reader.readLine());
}
public int[] readIntArray(int numInts) throws IOException {
int[] nums = new int[numInts];
tokenizer = new StringTokenizer(reader.readLine());
for(int i = 0; i<numInts; i++){
nums[i] = Integer.parseInt(tokenizer.nextToken());
}
return nums;
}
public long[] readLongArray(int numInts) throws IOException {
long[] nums = new long[numInts];
tokenizer = new StringTokenizer(reader.readLine());
for(int i = 0; i<numInts; i++){
nums[i] = Long.parseLong(tokenizer.nextToken());
}
return nums;
}
public String readString() throws IOException {
return reader.readLine();
}
}
public static class FastWriter {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
public void writeSingleInteger(int i) throws IOException {
writer.write(Integer.toString(i));
writer.newLine();
writer.flush();
}
public void writeSingleLong(long i) throws IOException {
writer.write(Long.toString(i));
writer.newLine();
writer.flush();
}
public void writeIntArrayWithSpaces(int[] nums) throws IOException {
for(int i = 0; i<nums.length; i++){
writer.write(nums[i] + " ");
}
writer.newLine();
writer.flush();
}
public void writeLongArrayWithSpaces(long[] nums) throws IOException {
for(int i = 0; i<nums.length; i++){
writer.write(nums[i] + " ");
}
writer.newLine();
writer.flush();
}
public void writeIntArrayListWithSpaces(ArrayList<Integer> nums) throws IOException {
for(int i = 0; i<nums.size(); i++){
writer.write(nums.get(i) + " ");
}
writer.newLine();
writer.flush();
}
public void writeIntArrayWithoutSpaces(int[] nums) throws IOException {
for(int i = 0; i<nums.length; i++){
writer.write(Integer.toString(nums[i]));
}
writer.newLine();
writer.flush();
}
public void writeString(String s) throws IOException {
writer.write(s);
writer.newLine();
writer.flush();
}
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 20f8a26611addbc9c108757e65e04c86 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | //package kg.my_algorithms.Codeforces;
/*
1) If you can't Calculate, then Stimulate
2) Don't show it unless you find it
*/
import java.util.*;
import java.io.*;
public class Solution {
public static void main(String[] args) throws IOException {
FastReader fr = new FastReader();
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
StringBuilder sb = new StringBuilder();
int rows = fr.nextInt();
int cols = fr.nextInt();
int queries = fr.nextInt();
char[][] grid = new char[rows][cols];
for(int row=0;row<rows;row++){
grid[row] = fr.next().toCharArray();
}
int icons = 0;
int[] arr = new int[rows*cols];
int index=0;
for(int col=0;col<cols;col++){
for(int row=0;row<rows;row++){
if(grid[row][col] == '*'){
icons++;
arr[index] = 1;
}
index++;
}
}
// System.out.println(Arrays.toString(arr));
SegmentTree segmentTree = new SegmentTree(arr);
for(int query=1;query<=queries;query++){
int row = fr.nextInt()-1;
int col = fr.nextInt()-1;
int updateIndex = col*rows+row;
if(arr[updateIndex]==1) icons--;
else icons++;
arr[updateIndex] = arr[updateIndex]^1;
segmentTree.flipIndex(updateIndex);
int numberOfIconsArranged = segmentTree.getInclusiveSumInRange(0,icons-1);
sb.append(icons-numberOfIconsArranged).append("\n");
}
output.write(sb.toString());
output.flush();
}
}
class SegmentTree{
int[] segmentArray;
int length;
public SegmentTree(int[] arr){
this.length = arr.length;
int height = (int) Math.ceil(Math.log(length)/Math.log(2));
int sizeOfSegmentTree = 2*(1<<height)-1;
this.segmentArray = new int[sizeOfSegmentTree];
segmentTreeConstructor(0,length-1,0,arr);
}
private int segmentTreeConstructor(int segmentStart, int segmentEnd, int segmentIndex, int[] arr){
if(segmentStart==segmentEnd) return segmentArray[segmentIndex] = arr[segmentStart];
int mid = (segmentStart+segmentEnd)/2;
return segmentArray[segmentIndex] = segmentTreeConstructor(segmentStart,mid,2*segmentIndex+1,arr)+
segmentTreeConstructor(mid+1,segmentEnd,2*segmentIndex+2,arr);
}
public int getInclusiveSumInRange(int left, int right){
return getSum(0,length-1,0,left,right);
}
private int getSum(int segmentStart, int segmentEnd, int segmentIndex, int queryStart, int queryEnd){
if(segmentEnd<queryStart || queryEnd<segmentStart) return 0;
if(queryStart<=segmentStart && segmentEnd<=queryEnd) return segmentArray[segmentIndex];
int mid = (segmentStart+segmentEnd)/2;
return getSum(segmentStart,mid,2*segmentIndex+1,queryStart,queryEnd)+
getSum(mid+1,segmentEnd,2*segmentIndex+2,queryStart,queryEnd);
}
public void flipIndex(int index){
update(0,length-1,0,index);
}
private int update(int segmentStart, int segmentEnd, int segmentIndex, int index){
if(index<segmentStart || index>segmentEnd) return segmentArray[segmentIndex];
if(index==segmentStart && index==segmentEnd) return segmentArray[segmentIndex] = segmentArray[segmentIndex]^1;
int mid = (segmentEnd+segmentStart)/2;
return segmentArray[segmentIndex] = update(segmentStart,mid,2*segmentIndex+1,index)+
update(mid+1,segmentEnd,2*segmentIndex+2,index);
}
}
//Fast Input
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 {
if(st.hasMoreTokens()){
str = st.nextToken("\n");
}
else{
str = br.readLine();
}
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 55ebbe17cf6d0ae9246edcd2065cf165 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | //https://codeforces.com/contest/1674/problem/F
//Evan Billingsley 6/21/22
import java.io.*;
import java.util.*;
import java.util.StringTokenizer;
public class Desktop implements Runnable {
public static void main(String [] args) {
new Thread(null, new Desktop(), "whatever", 1<<26).start();
}
public void run() {
FastScanner scanner = new FastScanner(System.in);
StringBuilder answers = new StringBuilder();
int n = scanner.nextInt();
int m = scanner.nextInt();
int q = scanner.nextInt();
int[][] map = new int[n][m];
int totalIcons = 0;
for (int r = 0; r < n; r++) {
char[] row = scanner.next().toCharArray();
for (int c = 0; c < m; c++) {
map[r][c] = row[c];
if (row[c] == '*') {
totalIcons++;
}
}
}
int usableColumns = (totalIcons / m) + (totalIcons % m == 0 ? 0 : 1);
int r = 0;
int c = 0;
int inPlace = 0;
while ((c * n) + r + 1 <= totalIcons) {
if (map[r][c] == '*') {
inPlace++;
}
if (r < n - 1) {
r++;
}
else {
r = 0;
c++;
}
}
for (int i = 0; i < q; i++) {
r = scanner.nextInt() - 1;
c = scanner.nextInt() - 1;
if (map[r][c] == '*') {
if ((c * n) + r + 1 < totalIcons) {
inPlace--;
}
//System.err.println("LastSub: " + getLastX(n, totalIcons) + " " + ((totalIcons - 1) / n));
if (map[getLastX(n, totalIcons)][(totalIcons - 1) / n] == '*') {
inPlace--;
}
map[r][c] = '.';
totalIcons--;
}
else {
map[r][c] = '*';
totalIcons++;
if ((c * n) + r + 1 < totalIcons) {
inPlace++;
}
//System.err.println("LastAdd: " + getLastX(n, totalIcons) + " " + ((totalIcons - 1) / n));
if (map[getLastX(n, totalIcons)][(totalIcons - 1) / n] == '*') {
inPlace++;
}
}
// System.err.println("~~~~~~~~~~~~~~~~~~~");
// System.err.println("Total: " + totalIcons);
// System.err.println("InPlace: " + inPlace);
// for (int k = 0; k < n; k++) {
// for (int j = 0; j < m; j++) {
// System.err.print(Character.toString(map[k][j]));
// }
// System.err.println();
// }
answers.append(totalIcons - inPlace + "\n");
}
System.out.println(answers);
}
public int getLastX(int n, int totalIcons) {
if ((totalIcons % n) - 1 >= 0) {
return (totalIcons % n) - 1;
}
else {
return n - 1;
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(Reader in) {
br = new BufferedReader(in);
}
public FastScanner(InputStream in) {
this(new InputStreamReader(in));
}
public String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() { return Double.parseDouble(next());}
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | e80d0d0efbe23e61ae3c7d1e3cc63a94 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.util.*;
import java.io.*;
public class codeforces1674F {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int numQueries = Integer.parseInt(st.nextToken());
char [][] desk = new char[n][m];
int numberItems = 0;
int [] columns = new int[m];
for (int i = 0; i<n;i++)
{
String str = br.readLine();
for (int b = 0; b<m;b++)
{
desk[i][b] = str.charAt(b);
if (desk[i][b]=='*')
{
columns[b]++;
numberItems++;
}
}
}
int currOpsNeeded = numberItems;
//System.out.println(currOpsNeeded);
for (int rep = 0; rep<numQueries;rep++)
{
st = new StringTokenizer(br.readLine());
int x = Integer.parseInt(st.nextToken());
x--;
int y = Integer.parseInt(st.nextToken());
y--;
int currNotMove = 0;
//System.out.println(desk[x][y]);
if (desk[x][y]=='*')
{
desk[x][y] = '.';
numberItems--;
columns[y]--;
if (numberItems>0)
{
for (int i = 0; i<(numberItems)/n;i++)
{
currNotMove+=columns[i];
}
if (numberItems!=n*m)
{
for (int i = 0; i<numberItems%n;i++)
{
if (desk[i][(numberItems)/n]=='*')
{
currNotMove++;
}
}
}
}
}
else
{
desk[x][y] = '*';
numberItems++;
columns[y]++;
for (int i = 0; i<(numberItems)/n;i++)
{
currNotMove+=columns[i];
}
for (int i = 0; i<numberItems%n;i++)
{
if (desk[i][(numberItems)/n]=='*')
{
currNotMove++;
}
}
}
//System.out.println(numberItems+" "+currNotMove);
currOpsNeeded = numberItems-currNotMove;
System.out.println(currOpsNeeded);
}
}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 797531cb9ff8286f51e59f46fbf96b18 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.util.*;
public class DesktopRearrangment {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int q = in.nextInt();
String[] a = new String[n];
for (int i=0; i<n; i++){
a[i] = in.next();
}
char[] s = new char[n*m];
int sum = 0; // count of '*' in desktop
for(int j=0; j<m; j++){
for(int i=0; i<n; i++){
s[i+j*n] = a[i].charAt(j);
if (s[i+j*n] == '*'){
sum++;
}
}
}
int res = 0; // count of '.' in prefix of s of length sum
for(int i=0; i<sum; i++){
if (s[i] == '.'){
res++;
}
}
// now handling the q queries
int pos = sum;
for(int i=0; i<q; i++){
int x = in.nextInt();
int y = in.nextInt();
x--; y--;
int p = y*n + x;
if (p<pos){
if (s[p]=='.'){
res--;
} else{
res++;
}
}
if (s[p]=='.'){
s[p] = '*';
} else{
s[p] = '.';
}
if (s[p]=='*'){
if (s[pos]=='.') {
res++;
}
pos++;
} else{
if (s[pos-1]=='.'){
res--;
}
pos--;
}
System.out.println(res);
}
in.close();
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | ef0f4f26ed8a23969120788b7aa57d1c | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.*;
public class Codeforces {
static long mod= 10000_0000_7;
static int dp[];
static int fake[];
static int in[];
static List<Integer> adj[];
public static void main(String[] args) throws Exception {
PrintWriter out=new PrintWriter(System.out);
FastScanner fs=new FastScanner();
// DecimalFormat formatter= new DecimalFormat("#0.000000");
// int t=fs.nextInt();
int t=1;
outer:for(int time=1;time<=t;time++) {
int n=fs.nextInt(), m=fs.nextInt(), q=fs.nextInt();
char arr[][]=new char[n][m];
for(int i=0;i<n;i++) arr[i]=fs.next().toCharArray();
ST st[]=new ST[m+1];
for(int i=0;i<=m;i++) st[i]=new ST(0,n);
ST seg=new ST(0,m);
int cnt=0;
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
if(arr[i][j]=='*') {
cnt++;
st[j+1].pointUpdate(i+1, 1);
seg.pointUpdate(j+1, 1);
}
}
}
while(q-->0) {
int r=fs.nextInt(), c=fs.nextInt();
if(arr[r-1][c-1]=='*') {
cnt--;
arr[r-1][c-1]='.';
st[c].pointUpdate(r, -1);
seg.pointUpdate(c,-1);
}
else {
arr[r-1][c-1]='*';
cnt++;
st[c].pointUpdate(r, 1);
seg.pointUpdate(c,1);
}
if(cnt==n*m) {
out.println(0);
continue;
}
int left=1,right=m+1;
while(left<right) {
int mid= (left+right)/2;
int cur= n*mid;
if(cur>cnt) {
right=mid;
}
else left=mid+1;
}
int rem= cnt-(left-1)*n;
long ans = cnt- seg.rangeSum(0, left-1)- st[left].rangeSum(0, rem);
out.println(ans);
}
}
out.close();
}
static class ST {
int leftmost, rightmost;
ST lChild, rChild;
int max, toProp;
long sum;
public ST(int leftmost, int rightmost) { // we can also pass a array here and if leftmost==rightmost
// we will do sum=arr[leftmost] else same in if case;
this.leftmost=leftmost;
this.rightmost=rightmost;
if (leftmost!=rightmost) {
int mid=(leftmost+rightmost)/2;
lChild=new ST(leftmost, mid);
rChild=new ST(mid+1, rightmost);
recalc();
}
}
int max() {
return max+toProp;
}
long sum() {
return sum+toProp;
}
void recalc() {
if (leftmost==rightmost) return;
max=Math.max(lChild.max(), rChild.max());
sum=lChild.sum()+rChild.sum();
}
void prop() {
if (leftmost!=rightmost) {
lChild.toProp+=toProp;
rChild.toProp+=toProp;
toProp=0;
}
recalc();
}
void rangeAdd(int l, int r, int d) {
if (l>rightmost || r<leftmost) return;
if (l<=leftmost && r>=rightmost) {
toProp+=d;
return;
}
prop();
lChild.rangeAdd(l, r, d);
rChild.rangeAdd(l, r, d);
recalc();
}
int max(int l, int r) {
if (l>rightmost || r<leftmost) return Integer.MIN_VALUE;
if (l<=leftmost && r>=rightmost) {
return max();
}
prop();
return Math.max(lChild.max(l, r), rChild.max(l, r));
}
void pointUpdate(int index,int val) {
if(leftmost==rightmost) {
sum+=val;
return;
}
int mid=(leftmost+rightmost)/2;
if(index<=mid) lChild.pointUpdate(index,val);
else rChild.pointUpdate(index,val);
recalc();
}
long rangeSum(int l,int r) {
if(l>rightmost||r<leftmost) return 0;
if(l<=leftmost&&r>=rightmost) return sum;
prop();
return lChild.rangeSum(l, r)+rChild.rangeSum(l, r);
}
}
static long pow(long a,long b) {
if(b<0) return 1;
long res=1;
while(b!=0) {
if((b&1)!=0) {
res*=a;
res%=mod;
}
a*=a;
a%=mod;
b=b>>1;
}
return res;
}
static long gcd(long a,long b) {
if(b==0) return a;
return gcd(b,a%b);
}
static long nck(int n,int k) {
if(k>n) return 0;
long res=1;
res*=fact(n);
res%=mod;
res*=modInv(fact(k));
res%=mod;
res*=modInv(fact(n-k));
res%=mod;
return res;
}
static long fact(long n) {
// return fact[(int)n];
long res=1;
for(int i=2;i<=n;i++) {
res*=i;
res%=mod;
}
return res;
}
static long modInv(long n) {
return pow(n,mod-2);
}
static void sort(int[] a) {
//suffle
int n=a.length;
Random r=new Random();
for (int i=0; i<a.length; i++) {
int oi=r.nextInt(n);
int temp=a[i];
a[i]=a[oi];
a[oi]=temp;
}
//then sort
Arrays.sort(a);
}
static void sort(long[] a) {
//suffle
int n=a.length;
Random r=new Random();
for (int i=0; i<a.length; i++) {
int oi=r.nextInt(n);
long temp=a[i];
a[i]=a[oi];
a[oi]=temp;
}
//then sort
Arrays.sort(a);
}
// Use this to input code since it is faster than a Scanner
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
String nextLine() {
String str="";
try {
str= (br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int nextInt() {
return Integer.parseInt(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
long[] readArrayL(int n) {
long a[]=new long[n];
for(int i=0;i<n;i++) a[i]=nextLong();
return a;
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | cc54d412e349a441d5d8da2127bde875 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 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.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class F {
public static void main(String[]args) throws IOException {
Scanner sc=new Scanner(System.in);
PrintWriter out=new PrintWriter(System.out);
int n=sc.nextInt(),m=sc.nextInt(),q=sc.nextInt();
char[][]mp=new char[n][m];
int cnt=0;
for(int i=0;i<n;i++) {
mp[i]=sc.next().toCharArray();
for(int j=0;j<m;j++) {
if(mp[i][j]=='*') {
cnt++;
}
}
}
int inplace=0;
for(int i=0;i<cnt;i++) {
int x=i%n,y=i/n;
if(mp[x][y]=='*')inplace++;
}
while(q-->0) {
int x=sc.nextInt()-1,y=sc.nextInt()-1;
if(mp[x][y]=='.') {
int idx=y*n+x%n;
int xf=cnt%n,yf=cnt/n;//last pos to include
cnt++;
if(idx<cnt)inplace++;
if(!(xf==x&&yf==y)&&mp[xf][yf]=='*')inplace++;
mp[x][y]='*';
}else {
int idx=y*n+x%n;
cnt--;
int xf=cnt%n,yf=cnt/n;//last pos excluded
if(idx<cnt)inplace--;
if(mp[xf][yf]=='*')inplace--;
mp[x][y]='.';
}
out.println(cnt-inplace);
}
out.close();
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public boolean hasNext() {return st.hasMoreTokens();}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public double nextDouble() throws IOException {return Double.parseDouble(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public boolean ready() throws IOException {return br.ready(); }
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 4b6600c70f6ee05ed3e4d74140e1c0eb | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.io.*;
import java.util.*;
//import org.graalvm.compiler.core.common.Fields.ObjectTransformer;
import java.math.*;
import java.math.BigInteger;
public final class A
{
static PrintWriter out = new PrintWriter(System.out);
static StringBuilder ans=new StringBuilder();
static FastReader in=new FastReader();
// static int g[][];
static ArrayList<Integer> g[];
static long mod=(long)998244353,INF=Long.MAX_VALUE;
static boolean set[];
static int max=0;
static int lca[][];
static int par[],col[],D[];
static long fact[];
static int size[],N;
static long dp[][],sum[][],f[];
static int seg[];
static ArrayList<Integer> A;
public static void main(String args[])throws IOException
{
/*
* star,rope,TPST
* BS,LST,MS,MQ
*/
int N=i(),M=i(),Q=i();
int A[]=new int[N*M];
int it=0;
char X[][]=new char[N][M];
for(int i=0; i<N; i++)X[i]=in.next().toCharArray();
for(int j=0; j<M; j++)
{
for(int i=0; i<N; i++)
{
if(X[i][j]=='*')A[it]=1;
it++;
}
}
// print(A);
int n=N*M;
seg=new int[4*n+5];
build(1,0,n-1,A);
while(Q-->0)
{
int x=i(),y=i();
int s=(y-1)*N+x-1;
// System.out.println(s);
update(1,0,n-1,s);
int tot=ask(1,0,n-1,0,n-1);
tot-=ask(1,0,n-1,0,tot-1);
ans.append(tot+"\n");
}
out.print(ans);
out.close();
}
public static int minSwaps(int[] arr)
{
int n = arr.length;
ArrayList <pair3 > A = new ArrayList < > ();
for (int i = 0; i < n; i++)
A.add(new pair3(arr[i], i));
Collections.sort(A);
Boolean[] vis = new Boolean[n];
Arrays.fill(vis, false);
// Initialize result
int ans = 0;
// Traverse array elements
for (int i = 0; i < n; i++)
{
if (vis[i] || A.get(i).index == i)
continue;
int cycle_size = 0;
int j = i;
while (!vis[j])
{
vis[j] = true;
// move to next node
j = A.get(j).index;
cycle_size++;
}
// Update answer by adding current cycle.
if(cycle_size > 0)
{
ans += (cycle_size - 1);
}
}
// Return result
return ans;
}
public static long mergeSort(int A[],int l,int r)
{
long a=0;
if(l<r)
{
int m=(l+r)/2;
a+=mergeSort(A,l,m);
a+=mergeSort(A,m+1,r);
a+=merge(A,l,m,r);
}
return a;
}
public static long merge(int A[],int l,int m,int r)
{
long a=0;
int i=l,j=m+1,index=0;
long c=0;
int B[]=new int[r-l+1];
while(i<=m && j<=r)
{
if(A[i]<=A[j])
{
c++;
B[index++]=A[i++];
}
else
{
long s=(m-l)+1;
a+=(s-c);
B[index++]=A[j++];
}
}
while(i<=m)B[index++]=A[i++];
while(j<=r)B[index++]=A[j++];
index=0;
for(; l<=r; l++)A[l]=B[index++];
return a;
}
static int f(int A[])
{
int s=0;
for(int i=1; i<4; i++)
{
s+=Math.abs(A[i]-A[i-1]);
}
return s;
}
static boolean f(int A[],int B[],int N)
{
for(int i=0; i<N; i++)
{
if(Math.abs(A[i]-B[i])>1)return false;
}
return true;
}
static void dfS(int n,int p)
{
int child=0;
for(int c:g[n])
{
if(c!=p)
{
child++;
dfS(c,n);
}
}
if(child!=0)A.add(child);
}
static int [] prefix(char s[],int N) {
// int n = (int)s.length();
// vector<int> pi(n);
N=s.length;
int pi[]=new int[N];
for (int i = 1; i < N; i++) {
int j = pi[i-1];
while (j > 0 && s[i] != s[j])
j = pi[j-1];
if (s[i] == s[j])
j++;
pi[i] = j;
}
return pi;
}
static int count(long N)
{
int cnt=0;
long p=1L;
while(p<=N)
{
if((p&N)!=0)cnt++;
p<<=1;
}
return cnt;
}
static long kadane(long A[])
{
long lsum=A[0],gsum=0;
gsum=Math.max(gsum, lsum);
for(int i=1; i<A.length; i++)
{
lsum=Math.max(lsum+A[i],A[i]);
gsum=Math.max(gsum,lsum);
}
return gsum;
}
public static boolean pal(int i)
{
StringBuilder sb=new StringBuilder();
StringBuilder rev=new StringBuilder();
int p=1;
while(p<=i)
{
if((i&p)!=0)
{
sb.append("1");
}
else sb.append("0");
p<<=1;
}
rev=new StringBuilder(sb.toString());
rev.reverse();
if(i==8)System.out.println(sb+" "+rev);
return (sb.toString()).equals(rev.toString());
}
public static void reverse(int i,int j,int A[])
{
while(i<j)
{
int t=A[i];
A[i]=A[j];
A[j]=t;
i++;
j--;
}
}
public static int ask(int a,int b,int c)
{
System.out.println("? "+a+" "+b+" "+c);
return i();
}
static int[] reverse(int A[],int N)
{
int B[]=new int[N];
for(int i=N-1; i>=0; i--)
{
B[N-i-1]=A[i];
}
return B;
}
static boolean isPalin(char X[])
{
int i=0,j=X.length-1;
while(i<=j)
{
if(X[i]!=X[j])return false;
i++;
j--;
}
return true;
}
static int distance(int a,int b)
{
int d=D[a]+D[b];
int l=LCA(a,b);
l=2*D[l];
return d-l;
}
static int LCA(int a,int b)
{
if(D[a]<D[b])
{
int t=a;
a=b;
b=t;
}
int d=D[a]-D[b];
int p=1;
for(int i=0; i>=0 && p<=d; i++)
{
if((p&d)!=0)
{
a=lca[a][i];
}
p<<=1;
}
if(a==b)return a;
for(int i=max-1; i>=0; i--)
{
if(lca[a][i]!=-1 && lca[a][i]!=lca[b][i])
{
a=lca[a][i];
b=lca[b][i];
}
}
return lca[a][0];
}
static void dfs(int n,int p)
{
lca[n][0]=p;
if(p!=-1)D[n]=D[p]+1;
for(int c:g[n])
{
if(c!=p)
{
dfs(c,n);
}
}
}
static int[] prefix_function(char X[])//returns pi(i) array
{
int N=X.length;
int pre[]=new int[N];
for(int i=1; i<N; i++)
{
int j=pre[i-1];
while(j>0 && X[i]!=X[j])
j=pre[j-1];
if(X[i]==X[j])j++;
pre[i]=j;
}
return pre;
}
static TreeNode start;
public static void f(TreeNode root,TreeNode p,int r)
{
if(root==null)return;
if(p!=null)
{
root.par=p;
}
if(root.val==r)start=root;
f(root.left,root,r);
f(root.right,root,r);
}
static int right(int A[],int Limit,int l,int r)
{
while(r-l>1)
{
int m=(l+r)/2;
if(A[m]<Limit)l=m;
else r=m;
}
return l;
}
static int left(int A[],int a,int l,int r)
{
while(r-l>1)
{
int m=(l+r)/2;
if(A[m]<a)l=m;
else r=m;
}
return l;
}
static void build(int v,int tl,int tr,int A[])
{
if(tl==tr)
{
seg[v]=A[tl];
return;
}
int tm=(tl+tr)/2;
build(v*2,tl,tm,A);
build(v*2+1,tm+1,tr,A);
seg[v]=seg[v*2]+seg[v*2+1];
}
static void update(int v,int tl,int tr,int index)
{
if(index==tl && index==tr)
{
seg[v]+=1;
seg[v]%=2;
}
else
{
int tm=(tl+tr)/2;
if(index<=tm)update(v*2,tl,tm,index);
else update(v*2+1,tm+1,tr,index);
seg[v]=seg[v*2]+seg[v*2+1];
}
}
static int ask(int v,int tl,int tr,int l,int r)
{
if(l>r)return 0;
if(tl==l && r==tr)
{
return seg[v];
}
int tm=(tl+tr)/2;
return ask(v*2,tl,tm,l,Math.min(tm, r))+ask(v*2+1,tm+1,tr,Math.max(tm+1, l),r);
}
static boolean f(long A[],long m,int N)
{
long B[]=new long[N];
for(int i=0; i<N; i++)
{
B[i]=A[i];
}
for(int i=N-1; i>=0; i--)
{
if(B[i]<m)return false;
if(i>=2)
{
long extra=Math.min(B[i]-m, A[i]);
long x=extra/3L;
B[i-2]+=2L*x;
B[i-1]+=x;
}
}
return true;
}
static int f(int l,int r,long A[],long x)
{
while(r-l>1)
{
int m=(l+r)/2;
if(A[m]>=x)l=m;
else r=m;
}
return r;
}
static boolean f(long m,long H,long A[],int N)
{
long s=m;
for(int i=0; i<N-1;i++)
{
s+=Math.min(m, A[i+1]-A[i]);
}
return s>=H;
}
static long ask(long l,long r)
{
System.out.println("? "+l+" "+r);
return l();
}
static long f(long N,long M)
{
long s=0;
if(N%3==0)
{
N/=3;
s=N*M;
}
else
{
long b=N%3;
N/=3;
N++;
s=N*M;
N--;
long a=N*M;
if(M%3==0)
{
M/=3;
a+=(b*M);
}
else
{
M/=3;
M++;
a+=(b*M);
}
s=Math.min(s, a);
}
return s;
}
static int ask(StringBuilder sb,int a)
{
System.out.println(sb+""+a);
return i();
}
static void swap(char X[],int i,int j)
{
char x=X[i];
X[i]=X[j];
X[j]=x;
}
static int min(int a,int b,int c)
{
return Math.min(Math.min(a, b), c);
}
static long and(int i,int j)
{
System.out.println("and "+i+" "+j);
return l();
}
static long or(int i,int j)
{
System.out.println("or "+i+" "+j);
return l();
}
static int len=0,number=0;
static void f(char X[],int i,int num,int l)
{
if(i==X.length)
{
if(num==0)return;
//update our num
if(isPrime(num))return;
if(l<len)
{
len=l;
number=num;
}
return;
}
int a=X[i]-'0';
f(X,i+1,num*10+a,l+1);
f(X,i+1,num,l);
}
static boolean is_Sorted(int A[])
{
int N=A.length;
for(int i=1; i<=N; i++)if(A[i-1]!=i)return false;
return true;
}
static boolean f(StringBuilder sb,String Y,String order)
{
StringBuilder res=new StringBuilder(sb.toString());
HashSet<Character> set=new HashSet<>();
for(char ch:order.toCharArray())
{
set.add(ch);
for(int i=0; i<sb.length(); i++)
{
char x=sb.charAt(i);
if(set.contains(x))continue;
res.append(x);
}
}
String str=res.toString();
return str.equals(Y);
}
static boolean all_Zero(int f[])
{
for(int a:f)if(a!=0)return false;
return true;
}
static long form(int a,int l)
{
long x=0;
while(l-->0)
{
x*=10;
x+=a;
}
return x;
}
static int count(String X)
{
HashSet<Integer> set=new HashSet<>();
for(char x:X.toCharArray())set.add(x-'0');
return set.size();
}
static int f(long K)
{
long l=0,r=K;
while(r-l>1)
{
long m=(l+r)/2;
if(m*m<K)l=m;
else r=m;
}
return (int)l;
}
// static void build(int v,int tl,int tr,long A[])
// {
// if(tl==tr)
// {
// seg[v]=A[tl];
// }
// else
// {
// int tm=(tl+tr)/2;
// build(v*2,tl,tm,A);
// build(v*2+1,tm+1,tr,A);
// seg[v]=Math.min(seg[v*2], seg[v*2+1]);
// }
// }
static int [] sub(int A[],int B[])
{
int N=A.length;
int f[]=new int[N];
for(int i=N-1; i>=0; i--)
{
if(B[i]<A[i])
{
B[i]+=26;
B[i-1]-=1;
}
f[i]=B[i]-A[i];
}
for(int i=0; i<N; i++)
{
if(f[i]%2!=0)f[i+1]+=26;
f[i]/=2;
}
return f;
}
static int[] f(int N)
{
char X[]=in.next().toCharArray();
int A[]=new int[N];
for(int i=0; i<N; i++)A[i]=X[i]-'a';
return A;
}
static int max(int a ,int b,int c,int d)
{
a=Math.max(a, b);
c=Math.max(c,d);
return Math.max(a, c);
}
static int min(int a ,int b,int c,int d)
{
a=Math.min(a, b);
c=Math.min(c,d);
return Math.min(a, c);
}
static HashMap<Integer,Integer> Hash(int A[])
{
HashMap<Integer,Integer> mp=new HashMap<>();
for(int a:A)
{
int f=mp.getOrDefault(a,0)+1;
mp.put(a, f);
}
return mp;
}
static long mul(long a, long b)
{
return ( a %mod * 1L * b%mod )%mod;
}
static void swap(int A[],int a,int b)
{
int t=A[a];
A[a]=A[b];
A[b]=t;
}
static int find(int a)
{
if(par[a]<0)return a;
return par[a]=find(par[a]);
}
static void union(int a,int b)
{
a=find(a);
b=find(b);
if(a!=b)
{
if(par[a]>par[b]) //this means size of a is less than that of b
{
int t=b;
b=a;
a=t;
}
par[a]+=par[b];
par[b]=a;
}
}
static boolean isSorted(int A[])
{
for(int i=1; i<A.length; i++)
{
if(A[i]<A[i-1])return false;
}
return true;
}
static boolean isDivisible(StringBuilder X,int i,long num)
{
long r=0;
for(; i<X.length(); i++)
{
r=r*10+(X.charAt(i)-'0');
r=r%num;
}
return r==0;
}
static int lower_Bound(int A[],int low,int high, int x)
{
if (low > high)
if (x >= A[high])
return A[high];
int mid = (low + high) / 2;
if (A[mid] == x)
return A[mid];
if (mid > 0 && A[mid - 1] <= x && x < A[mid])
return A[mid - 1];
if (x < A[mid])
return lower_Bound( A, low, mid - 1, x);
return lower_Bound(A, mid + 1, high, x);
}
static String f(String A)
{
String X="";
for(int i=A.length()-1; i>=0; i--)
{
int c=A.charAt(i)-'0';
X+=(c+1)%2;
}
return X;
}
static void sort(long[] a) //check for long
{
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 String swap(String X,int i,int j)
{
char ch[]=X.toCharArray();
char a=ch[i];
ch[i]=ch[j];
ch[j]=a;
return new String(ch);
}
static int sD(long n)
{
if (n % 2 == 0 )
return 2;
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0 )
return i;
}
return (int)n;
}
// static void setGraph(int N,int nodes)
// {
//// size=new int[N+1];
// par=new int[N+1];
// col=new int[N+1];
//// g=new int[N+1][];
// D=new int[N+1];
// int deg[]=new int[N+1];
// int A[][]=new int[nodes][2];
// for(int i=0; i<nodes; i++)
// {
// int a=i(),b=i();
// A[i][0]=a;
// A[i][1]=b;
// deg[a]++;
// deg[b]++;
// }
// for(int i=0; i<=N; i++)
// {
// g[i]=new int[deg[i]];
// deg[i]=0;
// }
// for(int a[]:A)
// {
// int x=a[0],y=a[1];
// g[x][deg[x]++]=y;
// g[y][deg[y]++]=x;
// }
// }
static long pow(long a,long b)
{
//long mod=1000000007;
long pow=1;
long x=a;
while(b!=0)
{
if((b&1)!=0)pow=(pow*x)%mod;
x=(x*x)%mod;
b/=2;
}
return pow;
}
static long toggleBits(long x)//one's complement || Toggle bits
{
int n=(int)(Math.floor(Math.log(x)/Math.log(2)))+1;
return ((1<<n)-1)^x;
}
static int countBits(long a)
{
return (int)(Math.log(a)/Math.log(2)+1);
}
static long fact(long N)
{
long n=2;
if(N<=1)return 1;
else
{
for(int i=3; i<=N; i++)n=(n*i)%mod;
}
return n;
}
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 boolean isPrime(long 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 void print(char A[])
{
for(char c:A)System.out.print(c+" ");
System.out.println();
}
static void print(boolean A[])
{
for(boolean c:A)System.out.print(c+" ");
System.out.println();
}
static void print(int A[])
{
for(int a:A)System.out.print(a+" ");
System.out.println();
}
static void print(long A[])
{
for(long i:A)System.out.print(i+ " ");
System.out.println();
}
static void print(boolean A[][])
{
for(boolean a[]:A)print(a);
}
static void print(long A[][])
{
for(long a[]:A)print(a);
}
static void print(int A[][])
{
for(int a[]:A)print(a);
}
static void print(ArrayList<Integer> A)
{
for(int a:A)System.out.print(a+" ");
System.out.println();
}
static int i()
{
return in.nextInt();
}
static long l()
{
return in.nextLong();
}
static int[] input(int N){
int A[]=new int[N];
for(int i=0; i<N; i++)
{
A[i]=in.nextInt();
}
return A;
}
static long[] inputLong(int N) {
long A[]=new long[N];
for(int i=0; i<A.length; i++)A[i]=in.nextLong();
return A;
}
static long GCD(long a,long b)
{
if(b==0)
{
return a;
}
else return GCD(b,a%b );
}
}
class segNode
{
long pref,suff,sum,max;
segNode(long a,long b,long c,long d)
{
pref=a;
suff=b;
sum=c;
max=d;
}
}
//class TreeNode
//{
// int cnt,index;
// TreeNode left,right;
// TreeNode(int c)
// {
// cnt=c;
// index=-1;
// }
// TreeNode(int c,int index)
// {
// cnt=c;
// this.index=index;
// }
//}
class role
{
String skill;
int level;
role(String s,int l)
{
skill=s;
level=l;
}
}
class project implements Comparable<project>
{
int score,index;
project(int s,int i)
{
// roles=r;
index=i;
score=s;
// skill=new String[r];
// lvl=new int[r];
}
public int compareTo(project x)
{
return x.score-this.score;
}
}
class post implements Comparable<post>
{
long x,y,d,t;
post(long a,long b,long c)
{
x=a;
y=b;
d=c;
}
public int compareTo(post X)
{
if(X.t==this.t)
{
return 0;
}
else
{
long xt=this.t-X.t;
if(xt>0)return 1;
return -1;
}
}
}
class TreeNode
{
int val;
TreeNode left, right,par;
TreeNode() {}
TreeNode(int item)
{
val = item;
left =null;
right = null;
par=null;
}
}
class edge
{
int a,wt;
edge(int a,int w)
{
this.a=a;
wt=w;
}
}
class pair3 implements Comparable<pair3>
{
long a;
int index;
pair3(long x,int i)
{
a=x;
index=i;
}
public int compareTo(pair3 x)
{
if(this.a>x.a)return 1;
if(this.a<x.a)return -1;
return 0;
// return this.index-x.index;
}
}
//Code For FastReader
//Code For FastReader
//Code For FastReader
//Code For FastReader
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 | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 13cd951840bb1ee55ac8afc2c5a47b9f | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
int q=sc.nextInt();
char[][] map=new char[n+1][m+1];
boolean[][] flag=new boolean[n+1][m+1];
int cnt=0;
for(int i=1;i<=n;i++) {
map[i]=(" "+sc.next()).toCharArray();
for(int j=1;j<=m;j++) {
if(map[i][j]=='*') {
flag[i][j]=true;
cnt++;
}
}
}
int t=0;
int c=0;
for(int i=1;i<=m && c<cnt;i++) {
for(int j=1;j<=n && c<cnt;j++) {
if(map[j][i]=='*')
t++;
c++;
}
}
//System.out.println("origin: "+t);
while(q-->0) {
int x=sc.nextInt(),y=sc.nextInt();
if(flag[x][y]) {
cnt--;
if(y<=cnt/n || (y==cnt/n+1 && x<=cnt%n))
t--;
int count=cnt+1;
if(count%n==0) {
if(flag[n][count/n])
t--;
}
else {
if(flag[count%n][count/n+1])
t--;
}
flag[x][y]=false;
}
else {
if(y<=cnt/n || (y==cnt/n+1 && x<=cnt%n))
t++;
cnt++;
flag[x][y]=true;
if(cnt%n==0) {
if(flag[n][cnt/n])
t++;
}
else {
if(flag[cnt%n][cnt/n+1])
t++;
}
}
System.out.println(cnt-t);
}
sc.close();
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 4dff11371ac692523876e1391058c7e8 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
int q=sc.nextInt();
char[][] map=new char[n+1][m+1];
boolean[][] flag=new boolean[n+1][m+1];
int cnt=0;
for(int i=1;i<=n;i++) {
map[i]=(" "+sc.next()).toCharArray();
for(int j=1;j<=m;j++) {
if(map[i][j]=='*') {
flag[i][j]=true;
cnt++;
}
}
}
int t=0;
int c=0;
for(int i=1;i<=m && c<cnt;i++) {
for(int j=1;j<=n && c<cnt;j++) {
if(map[j][i]=='*')
t++;
c++;
}
}
//System.out.println("origin: "+t);
while(q-->0) {
int x=sc.nextInt(),y=sc.nextInt();
if(flag[x][y]) {
cnt--;
if(y<=cnt/n || (y==cnt/n+1 && x<=cnt%n))
t--;
int count=cnt+1;
if(count%n==0) {
if(flag[n][count/n])
t--;
}
else {
if(flag[count%n][count/n+1])
t--;
}
flag[x][y]=false;
}
else {
if(y<=cnt/n || (y==cnt/n+1 && x<=cnt%n))
t++;
cnt++;
flag[x][y]=true;
if(cnt%n==0) {
if(flag[n][cnt/n])
t++;
}
else {
if(flag[cnt%n][cnt/n+1])
t++;
}
}
System.out.println(cnt-t);
}
sc.close();
}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 23149d9af840bb94f02b2c08e09f8785 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes |
import java.util.Arrays;
import java.util.Scanner;
public class F {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int q = sc.nextInt();
char[] arr = new char[n * m];
int totalCount = 0;
for (int r = 0; r < n; r++) {
String s = sc.next();
for (int c = 0; c < m; c++) {
arr[r + c * n] = s.charAt(c);
if (s.charAt(c) == '*') {
totalCount++;
}
}
}
int firstCount = 0;
for (int i = 0; i < totalCount; i++) {
if (arr[i] == '*') firstCount++;
}
while (q-- > 0) {
int r = sc.nextInt() - 1;
int c = sc.nextInt() - 1;
int idx = r + c * n;
if (arr[idx] == '*') {
arr[idx] = '.';
if (idx < totalCount) {
firstCount--;
}
if (arr[totalCount - 1] == '*') {
firstCount--;
}
totalCount--;
} else {
arr[idx] = '*';
if (idx < totalCount) {
firstCount++;
}
totalCount++;
if (arr[totalCount - 1] == '*') {
firstCount++;
}
}
System.out.println(totalCount - firstCount);
}
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 44b0010ea4ad013bef4ca1e2a5f6f150 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int row = in.nextInt();
int col = in.nextInt();
int n = in.nextInt();
int[] sTree = new int[row * col * 4];
int limit = limit(row * col);
in.nextLine();
int cnt = 0;
for (int i=0; i<row; i++) {
String s = in.nextLine();
for (int j=0; j<col; j++) {
if (s.charAt(j) == '*') {
update(sTree, limit + i + j * row, 1);
cnt++;
}
}
}
while (n > 0){
int r = in.nextInt() - 1;
int c = in.nextInt() - 1;
if (sTree[limit + r + c * row] == 1) {
update(sTree, limit + r + c * row, -1);
cnt--;
} else {
update(sTree, limit + r + c * row, 1);
cnt++;
}
if (cnt == 0)
System.out.println(0);
else
System.out.println(cnt - query(sTree, 0, limit-1, 0, cnt - 1, 1));
n--;
}
}
public static int limit(int num) {
int bit = 0;
while (num > 0) {
num = num >> 1;
bit++;
}
return 1 << bit;
}
public static void update(int[] sTree, int pos, int change) {
if (pos == 0)
return;
sTree[pos] += change;
update(sTree, pos >> 1, change);
}
public static int query(int[] sTree, int left, int right, int l, int r, int pos) {
int mid = (left + right) / 2;
if (l <= left && r >= right)
return sTree[pos];
int cnt = 0;
if (mid >= l)
cnt += query(sTree, left, mid, l, r, pos * 2);
if (mid < r)
cnt += query(sTree, mid+1, right, l, r, pos * 2 + 1);
return cnt;
}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 556719eb6eeefedcf05c09f308569ac3 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes |
import javax.swing.*;
import java.lang.reflect.Array;
import java.text.DecimalFormat;
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
import java.util.stream.Stream;
// Please name your class Main
public class Main {
static FastScanner fs=new FastScanner();
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
public String next() {
while (!st.hasMoreElements())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int Int() {
return Integer.parseInt(next());
}
long Long() {
return Long.parseLong(next());
}
String Str(){
return next();
}
}
public static void main (String[] args) throws java.lang.Exception {
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
//reading /writing file
//Scanner in=new Scanner(System.in);
//Scanner in=new Scanner(new File("input.txt"));
//PrintWriter pr=new PrintWriter("output.txt")
int T=1;
for(int t=0;t<T;t++){
Solution sol1=new Solution(out,fs);
sol1.solution(T,t);
}
out.flush();
}
public static int[] Arr(int n){
int A[]=new int[n];
for(int i=0;i<n;i++)A[i]=Int();
return A;
}
public static int Int(){
return fs.Int();
}
public static long Long(){
return fs.Long();
}
public static String Str(){
return fs.Str();
}
}
class Solution {
PrintWriter out;
int INF = Integer.MAX_VALUE;
int NINF = Integer.MIN_VALUE;
int MOD = 998244353;
int mod = 998244353;
Main.FastScanner fs;
public Solution(PrintWriter out, Main.FastScanner fs) {
this.out = out;
this.fs = fs;
}
public void add(Map<Integer, Integer> f, int key) {
Integer cnt = f.get(key);
if(cnt == null) {
f.put(key, 1);
} else {
f.put(key, cnt + 1);
}
}
public void del(Map<Integer, Integer> f, int key) {
Integer cnt = f.get(key);
if(cnt == 1) {
f.remove(key);
} else {
f.put(key, cnt - 1);
}
}
public void msg(String s) {
System.out.println(s);
}
public void solution(int all, int testcase) {
int n = fs.Int(), m = fs.Int(), q =fs.Int();
int a[][] = new int[n][m];
int ids[][] = new int[n][m];
int sum = 0;
for(int i = 0; i < n; i++) {
String s = fs.Str();
for(int j = 0; j < m; j++) {
if(s.charAt(j) == '*') {
a[i][j] = 1;
sum ++;
}
}
}
int id = 0;
FenWick fen = new FenWick(n * m + 1);
for(int c = 0; c < m; c++) {
for(int r = 0; r < n; r++) {
if(a[r][c] == 1) {
fen.update(id, 1);
}
ids[r][c] = id++;
}
}
//for(int p[]:ids){
//System.out.println(Arrays.toString(p));
//}
for(int i = 0; i < q; i++) {
int r = fs.Int(), c =fs.Int();
r--; c--;
int ith = ids[r][c];
if(a[r][c] == 1) {
sum--;
a[r][c] = 0;
fen.update(ith, -1);
} else {
a[r][c] = 1;
sum++;
fen.update(ith, 1);
}
int in = fen.sumRange(0, sum - 1);
out.println(sum - in);
}
}
}
class FenWick {
int tree[];//1-index based
public FenWick(int n) {
tree=new int[n+1];
}
public void update(int i, int val) {
i++;
while(i<tree.length){
tree[i]+=val;
i+=(i&-i);
}
}
public int sumRange(int i, int j) {
return pre(j+1)-pre(i);
}
public int pre(int i){
int sum=0;
while(i>0){
sum+=tree[i];
i-=(i&-i);
}
return sum;
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 8a4fca3a137cef6c82b1abd6436a7b46 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static int R, C, Q, N, bit[];
static void update(int i, int k) {
for(;i<=N; i+=-i&i) bit[i] += k;
}
static int sum(int i) {
int ret = 0;
for(; i>0; i-=-i&i) ret += bit[i];
return ret;
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
R = Integer.parseInt(st.nextToken());
C = Integer.parseInt(st.nextToken());
Q = Integer.parseInt(st.nextToken());
N = R*C;
bit = new int[N+1];
char board[][] = new char[R][C];
int cnt = 0;
for(int i=0; i<R; i++) {
board[i] = br.readLine().toCharArray();
for(int j=0; j<C; j++)
if(board[i][j] == '*') {
update(j*R+i+1, 1);
cnt++;
}
}
while(Q-- > 0) {
st = new StringTokenizer(br.readLine());
int r = Integer.parseInt(st.nextToken())-1;
int c = Integer.parseInt(st.nextToken())-1;
int idx = c*R+r+1;
if(board[r][c] == '*') {
update(idx, -1);
board[r][c] = '.';
cnt--;
}else {
update(idx, 1);
board[r][c] = '*';
cnt++;
}
bw.write((cnt - sum(cnt)) + "\n");
}
bw.close();
}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 6dbc51adb2b434dce308658ea7d6bc76 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import java.util.*;
import java.io.*;
import java.math.*;
/**
*
* @Har_Har_Mahadev
*/
/**
* Main , Solution , Remove Public
*/
public class F {
public static void process() throws IOException {
int n = sc.nextInt(), m = sc.nextInt(), q = sc.nextInt();
char[][] arr = new char[n][m];
for(int i = 0; i<n; i++)arr[i] = sc.next().toCharArray();
int cc = 0;
for(int i = 0; i<n; i++) {
for(int j = 0; j<m; j++) {
if(arr[i][j] == '*')cc++;
}
}
int empty = 0;
int x = 0, y = 0;
for(int i = 0; i<cc; i++) {
if(arr[x][y] == '.')empty++;
if(x+1 == n) {
x = 0;
y++;
continue;
}
x++;
}
for(int k = 0; k<q; k++) {
int l = sc.nextInt()-1, r = sc.nextInt()-1;
if(r < y || r == y && l < x) {
if(arr[l][r] == '.')empty--;
else empty++;
}
if(arr[l][r] == '.') {
arr[l][r] = '*';
if(y>=0 && y<m) {
if(arr[x][y] == '.')empty++;
}
if(x+1 == n) {
x = 0;
y++;
}
else {
x++;
}
}
else{
arr[l][r] = '.';
if(x == 0) {
x = n-1;
y--;
}
else {
x--;
}
if(y>=0 && y<m) {
if(arr[x][y] == '.')empty--;
}
}
System.out.println(empty);
}
}
//=============================================================================
//--------------------------The End---------------------------------
//=============================================================================
private static long INF = 2000000000000000000L, M = 1000000007, MM = 998244353;
private static int N = 0;
private static void google(int tt) {
System.out.print("Case #" + (tt) + ": ");
}
static FastScanner sc;
static FastWriter out;
public static void main(String[] args) throws IOException {
boolean oj = true;
if (oj) {
sc = new FastScanner();
out = new FastWriter(System.out);
} else {
sc = new FastScanner("input.txt");
out = new FastWriter("output.txt");
}
long s = System.currentTimeMillis();
int t = 1;
// t = sc.nextInt();
int TTT = 1;
while (t-- > 0) {
// google(TTT++);
process();
}
out.flush();
// tr(System.currentTimeMillis()-s+"ms");
}
private static boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private static void tr(Object... o) {
if (!oj)
System.err.println(Arrays.deepToString(o));
}
static class Pair implements Comparable<Pair> {
int x, y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
return Integer.compare(this.x, o.x);
}
/*
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Pair)) return false;
Pair key = (Pair) o;
return x == key.x && y == key.y;
}
@Override
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}
*/
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
static int ceil(int x, int y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
static long ceil(long x, long y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
static long sqrt(long z) {
long sqz = (long) Math.sqrt(z);
while (sqz * 1L * sqz < z) {
sqz++;
}
while (sqz * 1L * sqz > z) {
sqz--;
}
return sqz;
}
static int log2(int N) {
int result = (int) (Math.log(N) / Math.log(2));
return result;
}
public static long gcd(long a, long b) {
if (a > b)
a = (a + b) - (b = a);
if (a == 0L)
return b;
return gcd(b % a, a);
}
public static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
public static int lower_bound(int[] arr, int x) {
int low = 0, high = arr.length - 1, mid = -1;
int ans = -1;
while (low <= high) {
mid = (low + high) / 2;
if (arr[mid] > x) {
high = mid - 1;
} else {
ans = mid;
low = mid + 1;
}
}
return ans;
}
public static int upper_bound(int[] arr, int x) {
int low = 0, high = arr.length - 1, mid = -1;
int ans = arr.length;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] >= x) {
ans = mid;
high = mid - 1;
} else {
low = mid + 1;
}
}
return ans;
}
static void ruffleSort(int[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
Arrays.sort(a);
}
static void ruffleSort(long[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
long temp = a[i];
a[i] = a[r];
a[r] = temp;
}
Arrays.sort(a);
}
static void reverseArray(int[] a) {
int n = a.length;
int arr[] = new int[n];
for (int i = 0; i < n; i++)
arr[i] = a[n - i - 1];
for (int i = 0; i < n; i++)
a[i] = arr[i];
}
static void reverseArray(long[] a) {
int n = a.length;
long arr[] = new long[n];
for (int i = 0; i < n; i++)
arr[i] = a[n - i - 1];
for (int i = 0; i < n; i++)
a[i] = arr[i];
}
//custom multiset (replace with HashMap if needed)
public static void push(TreeMap<Integer, Integer> map, int k, int v) {
//map[k] += v;
if (!map.containsKey(k))
map.put(k, v);
else
map.put(k, map.get(k) + v);
}
public static void pull(TreeMap<Integer, Integer> map, int k, int v) {
//assumes map[k] >= v
//map[k] -= v
int lol = map.get(k);
if (lol == v)
map.remove(k);
else
map.put(k, lol - v);
}
// compress Big value to Time Limit
public static int[] compress(int[] arr) {
ArrayList<Integer> ls = new ArrayList<Integer>();
for (int x : arr)
ls.add(x);
Collections.sort(ls);
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int boof = 1; //min value
for (int x : ls)
if (!map.containsKey(x))
map.put(x, boof++);
int[] brr = new int[arr.length];
for (int i = 0; i < arr.length; i++)
brr[i] = map.get(arr[i]);
return brr;
}
// Fast Writer
public static class FastWriter {
private static final int BUF_SIZE = 1 << 13;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastWriter() {
out = null;
}
public FastWriter(OutputStream os) {
this.out = os;
}
public FastWriter(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastWriter write(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE)
innerflush();
return this;
}
public FastWriter write(char c) {
return write((byte) c);
}
public FastWriter write(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE)
innerflush();
}
return this;
}
public FastWriter write(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE)
innerflush();
});
return this;
}
private static int countDigits(int l) {
if (l >= 1000000000)
return 10;
if (l >= 100000000)
return 9;
if (l >= 10000000)
return 8;
if (l >= 1000000)
return 7;
if (l >= 100000)
return 6;
if (l >= 10000)
return 5;
if (l >= 1000)
return 4;
if (l >= 100)
return 3;
if (l >= 10)
return 2;
return 1;
}
public FastWriter write(int x) {
if (x == Integer.MIN_VALUE) {
return write((long) x);
}
if (ptr + 12 >= BUF_SIZE)
innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L)
return 19;
if (l >= 100000000000000000L)
return 18;
if (l >= 10000000000000000L)
return 17;
if (l >= 1000000000000000L)
return 16;
if (l >= 100000000000000L)
return 15;
if (l >= 10000000000000L)
return 14;
if (l >= 1000000000000L)
return 13;
if (l >= 100000000000L)
return 12;
if (l >= 10000000000L)
return 11;
if (l >= 1000000000L)
return 10;
if (l >= 100000000L)
return 9;
if (l >= 10000000L)
return 8;
if (l >= 1000000L)
return 7;
if (l >= 100000L)
return 6;
if (l >= 10000L)
return 5;
if (l >= 1000L)
return 4;
if (l >= 100L)
return 3;
if (l >= 10L)
return 2;
return 1;
}
public FastWriter write(long x) {
if (x == Long.MIN_VALUE) {
return write("" + x);
}
if (ptr + 21 >= BUF_SIZE)
innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
public FastWriter write(double x, int precision) {
if (x < 0) {
write('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
// if(x < 0){ x = 0; }
write((long) x).write(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
write((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastWriter writeln(char c) {
return write(c).writeln();
}
public FastWriter writeln(int x) {
return write(x).writeln();
}
public FastWriter writeln(long x) {
return write(x).writeln();
}
public FastWriter writeln(double x, int precision) {
return write(x, precision).writeln();
}
public FastWriter write(int... xs) {
boolean first = true;
for (int x : xs) {
if (!first)
write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter write(long... xs) {
boolean first = true;
for (long x : xs) {
if (!first)
write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter writeln() {
return write((byte) '\n');
}
public FastWriter writeln(int... xs) {
return write(xs).writeln();
}
public FastWriter writeln(long... xs) {
return write(xs).writeln();
}
public FastWriter writeln(char[] line) {
return write(line).writeln();
}
public FastWriter writeln(char[]... map) {
for (char[] line : map)
write(line).writeln();
return this;
}
public FastWriter writeln(String s) {
return write(s).writeln();
}
private void innerflush() {
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush() {
innerflush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
public FastWriter print(byte b) {
return write(b);
}
public FastWriter print(char c) {
return write(c);
}
public FastWriter print(char[] s) {
return write(s);
}
public FastWriter print(String s) {
return write(s);
}
public FastWriter print(int x) {
return write(x);
}
public FastWriter print(long x) {
return write(x);
}
public FastWriter print(double x, int precision) {
return write(x, precision);
}
public FastWriter println(char c) {
return writeln(c);
}
public FastWriter println(int x) {
return writeln(x);
}
public FastWriter println(long x) {
return writeln(x);
}
public FastWriter println(double x, int precision) {
return writeln(x, precision);
}
public FastWriter print(int... xs) {
return write(xs);
}
public FastWriter print(long... xs) {
return write(xs);
}
public FastWriter println(int... xs) {
return writeln(xs);
}
public FastWriter println(long... xs) {
return writeln(xs);
}
public FastWriter println(char[] line) {
return writeln(line);
}
public FastWriter println(char[]... map) {
return writeln(map);
}
public FastWriter println(String s) {
return writeln(s);
}
public FastWriter println() {
return writeln();
}
}
// Fast Inputs
static class FastScanner {
//I don't understand how this works lmao
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1)
return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] readArray(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] readArrayLong(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public int[][] readArrayMatrix(int N, int M, int Index) {
if (Index == 0) {
int[][] res = new int[N][M];
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++)
res[i][j] = (int) nextLong();
}
return res;
}
int[][] res = new int[N][M];
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= M; j++)
res[i][j] = (int) nextLong();
}
return res;
}
public long[][] readArrayMatrixLong(int N, int M, int Index) {
if (Index == 0) {
long[][] res = new long[N][M];
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++)
res[i][j] = nextLong();
}
return res;
}
long[][] res = new long[N][M];
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= M; j++)
res[i][j] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC)
c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-')
neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] readArrayDouble(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32)
c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32)
c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32)
return true;
while (true) {
c = getChar();
if (c == NC)
return false;
else if (c > 32)
return true;
}
}
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 892f69a8fd0f3f75b780d5318ab80f10 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | //package codeforces.round786div3;
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class F {
static InputReader in;
static PrintWriter out;
public static void main(String[] args) {
//initReaderPrinter(true);
initReaderPrinter(false);
//solve(in.nextInt());
solve(1);
}
/*
General tips
1. It is ok to fail, but it is not ok to fail for the same mistakes over and over!
2. Train smarter, not harder!
3. If you find an answer and want to return immediately, don't forget to flush before return!
*/
/*
Read before practice
1. Set a timer based on a problem's difficulty level: 45 minutes at your current target practice level;
2. During a problem solving session, focus! Do not switch problems or even worse switch to do something else;
3. If fail to solve within timer limit, read editorials to get as little help as possible to get yourself unblocked;
4. If after reading the entire editorial and other people's code but still can not solve, move this problem to to-do list
and re-try in the future.
5. Keep a practice log about new thinking approaches, good tricks, bugs; Review regularly;
6. Also try this new approach suggested by um_nik: Solve with no intention to read editorial.
If getting stuck, skip it and solve other similar level problems.
Wait for 1 week then try to solve again. Only read editorial after you solved a problem.
7. Remember to also submit in the original problem link (if using gym) so that the 1 v 1 bot knows which problems I have solved already.
8. Form the habit of writing down an implementable solution idea before coding! You've taken enough hits during contests because you
rushed to coding!
*/
/*
Read before contests and lockout 1 v 1
Mistakes you've made in the past contests:
1. Tried to solve without going through given test examples -> wasting time on solving a different problem than asked;
2. Rushed to coding without getting a comprehensive sketch of your solution -> implementation bugs and WA; Write down your idea step
by step, no need to rush. It is always better to have all the steps considered before hand! Think about all the past contests that
you have failed because slow implementation and implementation bugs! This will be greatly reduced if you take your time to get a
thorough idea steps!
3. Forgot about possible integer overflow;
When stuck:
1. Understand problem statements? Walked through test examples?
2. Take a step back and think about other approaches?
3. Check rank board to see if you can skip to work on a possibly easier problem?
4. If none of the above works, take a guess?
*/
static void solve(int testCnt) {
for (int testNumber = 0; testNumber < testCnt; testNumber++) {
int n = in.nextInt(), m = in.nextInt(), q = in.nextInt();
char[][] s = new char[n][];
int total = 0;
for(int i = 0; i < n; i++) {
s[i] = in.next().toCharArray();
}
FenwickTree_RSQ fenwickTree_rsq = new FenwickTree_RSQ(n * m + 5);
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(s[i][j] == '*') {
fenwickTree_rsq.adjust(j * n + i + 1, 1);
total++;
}
}
}
for(int i = 0; i < q; i++) {
int x = in.nextInt() - 1, y = in.nextInt() - 1;
int d = 0;
if(s[x][y] == '*') {
total--;
s[x][y] = '.';
d = -1;
}
else {
total++;
s[x][y] = '*';
d = 1;
}
fenwickTree_rsq.adjust(y * n + x + 1, d);
int inPosition = fenwickTree_rsq.rangeSumQuery(total);
out.println(total - inPosition);
}
}
out.close();
}
static class FenwickTree_RSQ {
private int[] ft;
public FenwickTree_RSQ(int n) {
ft = new int[n];
}
/*
query the sum in range [l, r], 1 index based
*/
public int rangeSumQuery(int l, int r) {
return rangeSumQuery(r) - (l == 1 ? 0 : rangeSumQuery(l - 1));
}
/*
query the sum in range[1, r], 1 index based
*/
public int rangeSumQuery(int r) {
int sum = 0;
for(; r > 0; r -= leastSignificantOne(r)) {
sum += ft[r];
}
return sum;
}
public void adjust(int k, int diff) {
for(; k < ft.length; k += leastSignificantOne(k)) {
ft[k] += diff;
}
}
private int leastSignificantOne(int i) {
return i & (-i);
}
}
static void initReaderPrinter(boolean test) {
if (test) {
try {
in = new InputReader(new FileInputStream("src/input.in"));
out = new PrintWriter(new FileOutputStream("src/output.out"));
} catch (IOException e) {
e.printStackTrace();
}
} else {
in = new InputReader(System.in);
out = new PrintWriter(System.out);
}
}
static class InputReader {
BufferedReader br;
StringTokenizer st;
InputReader(InputStream stream) {
try {
br = new BufferedReader(new InputStreamReader(stream), 32768);
} 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());
}
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;
}
Integer[] nextIntArray(int n) {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
int[] nextIntArrayPrimitive(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
int[] nextIntArrayPrimitiveOneIndexed(int n) {
int[] a = new int[n + 1];
for (int i = 1; i <= n; i++) a[i] = nextInt();
return a;
}
Long[] nextLongArray(int n) {
Long[] a = new Long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
long[] nextLongArrayPrimitive(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
long[] nextLongArrayPrimitiveOneIndexed(int n) {
long[] a = new long[n + 1];
for (int i = 1; i <= n; i++) a[i] = nextLong();
return a;
}
String[] nextStringArray(int n) {
String[] g = new String[n];
for (int i = 0; i < n; i++) g[i] = next();
return g;
}
List<Integer>[] readGraphOneIndexed(int n, int m) {
List<Integer>[] adj = new List[n + 1];
for (int i = 0; i <= n; i++) {
adj[i] = new ArrayList<>();
}
for (int i = 0; i < m; i++) {
int u = nextInt();
int v = nextInt();
adj[u].add(v);
adj[v].add(u);
}
return adj;
}
List<Integer>[] readGraphZeroIndexed(int n, int m) {
List<Integer>[] adj = new List[n];
for (int i = 0; i < n; i++) {
adj[i] = new ArrayList<>();
}
for (int i = 0; i < m; i++) {
int u = nextInt() - 1;
int v = nextInt() - 1;
adj[u].add(v);
adj[v].add(u);
}
return adj;
}
/*
A more efficient way of building an undirected graph using int[] instead of ArrayList to store each node's neighboring nodes.
1-indexed.
*/
int[][] buildUndirectedGraph(int nodeCnt, int edgeCnt) {
int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt];
int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1];
for (int i = 0; i < edgeCnt; i++) {
int u = in.nextInt(), v = in.nextInt();
edgeCntForEachNode[u]++;
edgeCntForEachNode[v]++;
end1[i] = u;
end2[i] = v;
}
int[][] adj = new int[nodeCnt + 1][];
for (int i = 1; i <= nodeCnt; i++) {
adj[i] = new int[edgeCntForEachNode[i]];
}
for (int i = 0; i < edgeCnt; i++) {
adj[end1[i]][idxForEachNode[end1[i]]] = end2[i];
idxForEachNode[end1[i]]++;
adj[end2[i]][idxForEachNode[end2[i]]] = end1[i];
idxForEachNode[end2[i]]++;
}
return adj;
}
/*
A more efficient way of building a directed graph using int[] instead of ArrayList to store each node's neighboring nodes.
1-indexed.
*/
int[][] buildDirectedGraph(int nodeCnt, int edgeCnt) {
int[] from = new int[edgeCnt], to = new int[edgeCnt];
int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1];
//from u to v: u -> v
for (int i = 0; i < edgeCnt; i++) {
int u = in.nextInt(), v = in.nextInt();
edgeCntForEachNode[u]++;
from[i] = u;
to[i] = v;
}
int[][] adj = new int[nodeCnt + 1][];
for (int i = 1; i <= nodeCnt; i++) {
adj[i] = new int[edgeCntForEachNode[i]];
}
for (int i = 0; i < edgeCnt; i++) {
adj[from[i]][idxForEachNode[from[i]]] = to[i];
idxForEachNode[from[i]]++;
}
return adj;
}
}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 0c41c6bcd9369ef824996905371cd695 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.io.*;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
public class Main {
public static int n, m, q, in, tot;
public static char[][] s;
public static int[] get(int count) {
int j = count / n, i = count % n;
return new int[]{i, j};
}
public static void main(String[] args) throws IOException {
fs = new FastReader();
out = new PrintWriter(System.out);
n = fs.nextInt();
m = fs.nextInt();
q = fs.nextInt();
s = new char[n][];
in = 0;
tot = 0;
for (int i = 0; i < n; ++i) {
s[i] = fs.next().toCharArray();
for (int j = 0; j < m; ++j) {
if (s[i][j] == '*') {
++tot;
}
}
}
int[] ij = get(tot);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (s[i][j] == '*') {
if ((j < ij[1] || (j == ij[1] && i < ij[0]))) {
++in;
}
}
}
}
while (q-- > 0) {
int i = fs.nextInt() - 1;
int j = fs.nextInt() - 1;
ij = get(tot);
if (s[i][j] == '*') {
s[i][j] = '.';
if ((j < ij[1] || (j == ij[1] && i < ij[0]))) {
--in;
}
--tot;
ij = get(tot);
if (s[ij[0]][ij[1]] == '*') --in;
} else {
if (s[ij[0]][ij[1]] == '*') ++in;
++tot;
ij = get(tot);
s[i][j] = '*';
if ((j < ij[1] || (j == ij[1] && i < ij[0]))) {
++in;
}
}
out.println(tot - in);
}
out.close();
}
public static PrintWriter out;
public static FastReader fs;
public static final Random random = new Random();
public static void ruffleSort(int[] a) {
int n = a.length;
for (int i = 0; i < n; ++i) {
int oi = random.nextInt(n), tmp = a[oi];
a[oi] = a[i];
a[i] = tmp;
}
Arrays.sort(a);
}
public static class FastReader {
private BufferedReader br;
private StringTokenizer st = new StringTokenizer("");
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String file_name) throws FileNotFoundException {
br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(file_name))));
}
public String next() {
while (!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; ++i)
a[i] = nextInt();
return a;
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 3cdbcf425d24c13bbd4700bcb9e7ab8b | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.io.*;
import java.util.*;
public class CodeForces {
/*-------------------------------------------EDITING CODE STARTS HERE-------------------------------------------*/
public static void solve(int tCase) throws IOException {
int n = sc.nextInt();
int m = sc.nextInt();
int q = sc.nextInt();
char[][] str = new char[n][m];
for(int i=0;i<n;i++)str[i] = sc.next().toCharArray();
int inc = 0;
int tc = 0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(str[i][j]=='*')tc++;
}
}
int c = (-1 + tc) / n ;
int r = (tc - c*n - 1);
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(str[i][j]=='*'){
if( j < c || ( j==c && i <= r))inc++;
}
}
}
// out.println(r+" "+c+" "+tc+" "+inc);
for(int i=0;i<q;i++){
int x = sc.nextInt()-1;
int y = sc.nextInt()-1;
if(str[x][y] == '*'){
if(str[r][c] == '*')inc--;
tc--;
str[x][y] = '.';
if(r==0){
r = n-1;
c--;
}else {
r--;
}
if( y < c || ( y==c && x <= r))inc--;
}else {
str[x][y] = '*';
tc++;
if(r==n-1){
c++;
r = 0;
}else {
r++;
}
if(r == x && c==y){
inc++;
}else {
if( y < c || ( y==c && x <= r))inc++;
if(str[r][c]=='*')inc++;
}
}
// out.println(r+" "+c+" "+tc+" "+inc);
out.println(tc - inc);
}
}
public static void main(String[] args) throws IOException {
openIO();
int testCase = 1;
// testCase = sc.nextInt();
for (int i = 1; i <= testCase; i++) solve(i);
closeIO();
}
/*-------------------------------------------EDITING CODE ENDS HERE-------------------------------------------*/
/*--------------------------------------HELPER FUNCTIONS STARTS HERE-----------------------------------------*/
public static int mod = (int) 1e9 + 7;
// public static int mod = 998244353;
public static int inf_int = (int) 2e8;
public static long inf_long = (long) 2e18;
public static void _sort(int[] arr, boolean isAscending) {
int n = arr.length;
List<Integer> list = new ArrayList<>();
for (int ele : arr) list.add(ele);
Collections.sort(list);
if (!isAscending) Collections.reverse(list);
for (int i = 0; i < n; i++) arr[i] = list.get(i);
}
public static void _sort(long[] arr, boolean isAscending) {
int n = arr.length;
List<Long> list = new ArrayList<>();
for (long ele : arr) list.add(ele);
Collections.sort(list);
if (!isAscending) Collections.reverse(list);
for (int i = 0; i < n; i++) arr[i] = list.get(i);
}
// time : O(1), space : O(1)
public static int _digitCount(long num,int base){
// this will give the # of digits needed for a number num in format : base
return (int)(1 + Math.log(num)/Math.log(base));
}
// time : O(n), space: O(n)
public static long _fact(int n){
// simple factorial calculator
long ans = 1;
for(int i=2;i<=n;i++)
ans = ans * i % mod;
return ans;
}
// time for pre-computation of factorial and inverse-factorial table : O(nlog(mod))
public static long[] factorial , inverseFact;
public static void _ncr_precompute(int n){
factorial = new long[n+1];
inverseFact = new long[n+1];
factorial[0] = inverseFact[0] = 1;
for (int i = 1; i <=n; i++) {
factorial[i] = (factorial[i - 1] * i) % mod;
inverseFact[i] = _modExpo(factorial[i], mod - 2);
}
}
// time of factorial calculation after pre-computation is O(1)
public static int _ncr(int n,int r){
if(r > n)return 0;
return (int)(factorial[n] * inverseFact[r] % mod * inverseFact[n - r] % mod);
}
public static int _npr(int n,int r){
if(r > n)return 0;
return (int)(factorial[n] * inverseFact[n - r] % mod);
}
// euclidean algorithm time O(max (loga ,logb))
public static long _gcd(long a, long b) {
while (a>0){
long x = a;
a = b % a;
b = x;
}
return b;
// if (a == 0)
// return b;
// return _gcd(b % a, a);
}
// lcm(a,b) * gcd(a,b) = a * b
public static long _lcm(long a, long b) {
return (a / _gcd(a, b)) * b;
}
// binary exponentiation time O(logn)
public static long _modExpo(long x, long n) {
long ans = 1;
while (n > 0) {
if ((n & 1) == 1) {
ans *= x;
ans %= mod;
n--;
} else {
x *= x;
x %= mod;
n >>= 1;
}
}
return ans;
}
// function to find a/b under modulo mod. time : O(logn)
public static long _modInv(long a,long b){
return (a * _modExpo(b,mod-2)) % mod;
}
//sieve or first divisor time : O(mx * log ( log (mx) ) )
public static int[] _seive(int mx){
int[] firstDivisor = new int[mx+1];
for(int i=0;i<=mx;i++)firstDivisor[i] = i;
for(int i=2;i*i<=mx;i++)
if(firstDivisor[i] == i)
for(int j = i*i;j<=mx;j+=i)
if(firstDivisor[j]==j)firstDivisor[j] = i;
return firstDivisor;
}
// check if x is a prime # of not. time : O( n ^ 1/2 )
private static boolean _isPrime(long x){
for(long i=2;i*i<=x;i++)
if(x%i==0)return false;
return true;
}
static class Pair<K, V>{
K ff;
V ss;
public Pair(K ff, V ss) {
this.ff = ff;
this.ss = ss;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || this.getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
return ff.equals(pair.ff) && ss.equals(pair.ss);
}
@Override
public int hashCode() {
return Objects.hash(ff, ss);
}
@Override
public String toString(){
return ff.toString()+" "+ss.toString();
}
}
/*--------------------------------------HELPER FUNCTIONS ENDS HERE-----------------------------------------*/
/*-------------------------------------------FAST INPUT STARTS HERE---------------------------------------------*/
static FastestReader sc;
static PrintWriter out;
private static void openIO() throws IOException {
sc = new FastestReader();
out = new PrintWriter(System.out);
}
public static void closeIO() throws IOException {
out.flush();
out.close();
sc.close();
}
private static final class FastestReader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
public FastestReader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastestReader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
private static boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() throws IOException {
int b;
//noinspection StatementWithEmptyBody
while ((b = read()) != -1 && isSpaceChar(b)) {}
return b;
}
public String next() throws IOException {
int b = skip();
final StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
final boolean neg = c == '-';
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
return neg?-ret:ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
final boolean neg = c == '-';
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
return neg?-ret:ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') c = read();
final boolean neg = c == '-';
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.')
while ((c = read()) >= '0' && c <= '9')
ret += (c - '0') / (div *= 10);
return neg?-ret:ret;
}
public String nextLine() throws IOException {
final byte[] buf = new byte[(1<<10)]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
break;
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
din.close();
}
}
/*---------------------------------------------FAST INPUT ENDS HERE ---------------------------------------------*/
}
/** Some points to keep in mind :
* 1. don't use Arrays.sort(primitive data type array)
* 2. try to make the parameters of a recursive function as less as possible,
* more use static variables.
*
**/ | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | dae6782ee45ac7be4ef7006b57f73896 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main{
static void main() throws Exception{
int n=sc.nextInt(),m=sc.nextInt(),q=sc.nextInt();
int[]in=new int[n*m];
for(int i=0;i<n;i++){
char[]x=sc.nextLine().toCharArray();
for(int j=0;j<m;j++){
in[i+n*j]=x[j]=='*'?1:0;
}
}
int cnt=0;
for(int i=0;i<n*m;i++)cnt+=in[i];
int sum=0;
for(int i=0;i<cnt;i++){
sum+=in[i];
}
for(int i=0;i<q;i++){
int x=sc.nextInt()-1,y=sc.nextInt()-1;
int idx=x+n*y;
// System.out.println(cnt+" "+sum+" "+idx+" "+in[idx]);
if(idx<cnt){
if(in[idx]==0){
sum++;
}
else{
sum--;
}
}
in[idx]^=1;
if(in[idx]==1){
if(in[cnt]==1)sum++;
cnt++;
}
else{
cnt--;
if(in[cnt]==1)sum--;
}
pw.println(cnt-sum);
// break;
}
}
public static void main(String[] args) throws Exception{
sc=new MScanner(System.in);
pw = new PrintWriter(System.out);
int tc=1;
// tc=sc.nextInt();
for(int test=1;test<=tc;test++) {
main();
}
pw.flush();
}
static PrintWriter pw;
static MScanner sc;
static class MScanner {
StringTokenizer st;
BufferedReader br;
public MScanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public MScanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int[] intArr(int n) throws IOException {
int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public long[] longArr(int n) throws IOException {
long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public int[] intSortedArr(int n) throws IOException {
int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
shuffle(in);
Arrays.sort(in);
return in;
}
public long[] longSortedArr(int n) throws IOException {
long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
shuffle(in);
Arrays.sort(in);
return in;
}
public Integer[] IntegerArr(int n) throws IOException {
Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public Long[] LongArr(int n) throws IOException {
Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
static void shuffle(int[]in) {
for(int i=0;i<in.length;i++) {
int idx=(int)(Math.random()*in.length);
int tmp=in[i];
in[i]=in[idx];
in[idx]=tmp;
}
}
static void shuffle(long[]in) {
for(int i=0;i<in.length;i++) {
int idx=(int)(Math.random()*in.length);
long tmp=in[i];
in[i]=in[idx];
in[idx]=tmp;
}
}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | d7b2fb56a7650c69a351122cf5bbbf86 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static long mod=(long)1e18+7;
static long[]fac=new long[1002];
static int n, x=0,me,op;
static int[]pe,a,aa, prime=new int[(int)1e7+1];
static int[][]perm;
static long[][]memo;
static Integer[]ps;
static TreeSet<Long>p=new TreeSet<Long>();
public static void main(String[] args) throws Exception{
int n =sc.nextInt();
int m =sc.nextInt();
int q =sc.nextInt();
int icon = 0;
char[][]a=new char[n][];
for (int i = 0; i < a.length; i++) {
a[i]=sc.next().toCharArray();
for (int j = 0; j < a[i].length; j++) {
if(a[i][j]=='*')icon++;
}
}
int[]st = new int[n*m];
int c = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
st[c] = a[j][i]=='*'?1:0;
c++;
}
}
STree s=new STree(st,0);
while(q-->0) {
int x = sc.nextInt();
int y = sc.nextInt()-1;
int pos = y*n+x;
if(s.q(pos, pos)==0) {
s.update(pos, 1);
icon++;
}else {
s.update(pos, 0);
icon--;
}
pw.println(icon-s.q(1, icon));
}
pw.close();
}
public static class STree{
int N;
long[]arr;
long[]tree;
long id;
public static long operation(long x,long y) {
return x+y;
}
public STree(int[]a,long id) {
this.id=id;
N=1;
int n=a.length;
while(N<n) {
N*=2;
}
arr=new long[N+1];
Arrays.fill(arr, id);
for (int i = 1; i <= a.length; i++) {
arr[i]=a[i-1];
}
tree=new long[2*N];
Arrays.fill(tree, id);
build(1,N,1);
}
public void build(int l,int r,int node) {
if(l==r) {
tree[node]=arr[l];
return;
}
int mid=(l+r)/2;
build(mid+1,r,node*2+1);
build(l,mid,node*2);
tree[node]=operation(tree[node*2],tree[node*2+1]);
}
public void update(int node,long value) {
long diff=value-tree[node+N-1];
int i=node+N-1;
while(i>0) {
tree[i]+=diff;
i/=2;
}
}
public long q(int l,int r) {
return q(1,N,l,r,1);
}
public long q(int s,int e,int l,int r,int node) {
if(s>=l&&r>=e)
return tree[node];
if(s>r||e<l)
return id;
int mid=(s+e)/2;
return operation(q(s,mid,l,r,node*2), q(mid+1,e,l,r,node*2+1));
}
}
public static long pow(long a,long b) {
long ans=1;a%=mod;
for(long i=b;i>0;i/=2) {
if((i&1)!=0)
ans=ans*a%mod;
a=a*a%mod;
}
return ans;
}
public static void pre(){
fac[0]=1;
fac[1]=1;
fac[2]=2;
for (int i = 3; i < fac.length; i++) {
fac[i]=fac[i-1]*i%mod;
}
}
public static long eval(String s) {
long p=1;
long res=0;
for (int i = 0; i < s.length(); i++) {
res+=p*(s.charAt(s.length()-1-i)=='1'?1:0);
p*=2;
}
return res;
}
public static String binary(long x) {
String s="";
while(x!=0) {
s=(x%2)+s;
x/=2;
}
return s;
}
public static boolean allSame(String s) {
char x=s.charAt(0);
for (int i = 0; i < s.length(); i++) {
if(s.charAt(i)!=x)return false;
}
return true;
}
public static boolean isPalindrom(String s) {
int l=0;
int r=s.length()-1;
while(l<r) {
if(s.charAt(r--)!=s.charAt(l++))return false;
}
return true;
}
public static boolean isSubString(String s,String t) {
int ls=s.length();
int lt=t.length();
boolean res=false;
for (int i = 0; i <=lt-ls; i++) {
if(t.substring(i, i+ls).equals(s)) {
res=true;
break;
}
}
return res;
}
public static boolean isSorted(long[]a) {
for (int i = 0; i < a.length-1; i++) {
if(a[i]>a[i+1])return false;
}
return true;
}
public static long evaln(String x,int n) {
long res=0;
for (int i = 0; i < x.length(); i++) {
res+=Long.parseLong(x.charAt(x.length()-1-i)+"")*Math.pow(n, i);
}
return res;
}
static void mergesort(int[] arr,int b,int e) {
if(b<e) {
int m=b+(e-b)/2;
mergesort(arr,b,m);
mergesort(arr,m+1,e);
merge(arr,b,m,e);
}
return;
}
static void merge(int[] arr,int b,int m,int e) {
int len1=m-b+1,len2=e-m;
int[] l=new int[len1];
int[] r=new int[len2];
for(int i=0;i<len1;i++)l[i]=arr[b+i];
for(int i=0;i<len2;i++)r[i]=arr[m+1+i];
int i=0,j=0,k=b;
while(i<len1 && j<len2) {
if(l[i]<r[j])arr[k++]=l[i++];
else arr[k++]=r[j++];
}
while(i<len1)arr[k++]=l[i++];
while(j<len2)arr[k++]=r[j++];
return;
}
static void mergesortidx(long[] arr,long[]idx,int b,int e) {
if(b<e) {
int m=b+(e-b)/2;
mergesortidx(arr,idx,b,m);
mergesortidx(arr,idx,m+1,e);
mergeidx(arr,idx,b,m,e);
}
return;
}
static void mergeidx(long[] arr,long[]idx,int b,int m,int e) {
int len1=m-b+1,len2=e-m;
long[] l=new long[len1];
long[] lidx=new long[len1];
long[] r=new long[len2];
long[] ridx=new long[len2];
for(int i=0;i<len1;i++) {
l[i]=arr[b+i];
lidx[i]=idx[b+i];
}
for(int i=0;i<len2;i++) {
r[i]=arr[m+1+i];
ridx[i]=idx[m+1+i];
}
int i=0,j=0,k=b;
while(i<len1 && j<len2) {
if(l[i]<=r[j]) {
arr[k++]=l[i++];
idx[k-1]=lidx[i-1];
}
else {
arr[k++]=r[j++];
idx[k-1]=ridx[j-1];
}
}
while(i<len1) {
idx[k]=lidx[i];
arr[k++]=l[i++];
}
while(j<len2) {
idx[k]=ridx[j];
arr[k++]=r[j++];
}
return;
}
static long mergen(int[] arr,int b,int m,int e) {
int len1=m-b+1,len2=e-m;
int[] l=new int[len1];
int[] r=new int[len2];
for(int i=0;i<len1;i++)l[i]=arr[b+i];
for(int i=0;i<len2;i++)r[i]=arr[m+1+i];
int i=0,j=0,k=b;
long c=0;
while(i<len1 && j<len2) {
if(l[i]<r[j])arr[k++]=l[i++];
else {
arr[k++]=r[j++];
c=c+(long)(len1-i);
}
}
while(i<len1)arr[k++]=l[i++];
while(j<len2)arr[k++]=r[j++];
return c;
}
static long mergesortn(int[] arr,int b,int e) {
long c=0;
if(b<e) {
int m=b+(e-b)/2;
c=c+(long)mergesortn(arr,b,m);
c=c+(long)mergesortn(arr,m+1,e);
c=c+(long)mergen(arr,b,m,e);
}
return c;
}
public static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
public static long sumd(long x) {
long sum=0;
while(x!=0) {
sum+=x%10;
x=x/10;
}
return sum;
}
public static ArrayList<Integer> findDivisors(int n){
ArrayList<Integer>res=new ArrayList<Integer>();
for (int i=1; i<=Math.sqrt(n); i++)
{
if (n%i==0)
{
// If divisors are equal, print only one
if (n/i == i)
res.add(i);
else {
res.add(i);
res.add(n/i);
}
}
}
return res;
}
public static void sort2darray(Integer[][]a){
Arrays.sort(a,Comparator.<Integer[]>comparingInt(x -> x[0]).thenComparingInt(x -> x[1]));
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String file) throws FileNotFoundException {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public int[] nextArrint(int size) throws IOException {
int[] a=new int[size];
for (int i = 0; i < a.length; i++) {
a[i]=sc.nextInt();
}
return a;
}
public long[] nextArrlong(int size) throws IOException {
long[] a=new long[size];
for (int i = 0; i < a.length; i++) {
a[i]=sc.nextLong();
}
return a;
}
public int[][] next2dArrint(int rows,int columns) throws IOException{
int[][]a=new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
a[i][j]=sc.nextInt();
}
}
return a;
}
public long[][] next2dArrlong(int rows,int columns) throws IOException{
long[][]a=new long[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
a[i][j]=sc.nextLong();
}
}
return a;
}
}
static class Segment{
long x;
long y;
long m;
public Segment(long x,long y, long m) {
this.x=x;
this.y=y;
this.m=m;
}
@Override
public String toString() {
return x+" "+y+" "+m;
}
}
static Scanner sc=new Scanner(System.in);
static PrintWriter pw=new PrintWriter(System.out);
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 713ee4240bc80ae7e4f90f97927d2003 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes |
import javax.swing.*;
import java.lang.reflect.Array;
import java.text.DecimalFormat;
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
import java.util.stream.Stream;
// Please name your class Main
public class Main {
static FastScanner fs=new FastScanner();
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
public String next() {
while (!st.hasMoreElements())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int Int() {
return Integer.parseInt(next());
}
long Long() {
return Long.parseLong(next());
}
String Str(){
return next();
}
}
public static void main (String[] args) throws java.lang.Exception {
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
//reading /writing file
//Scanner in=new Scanner(System.in);
//Scanner in=new Scanner(new File("input.txt"));
//PrintWriter pr=new PrintWriter("output.txt")
int T=1;
for(int t=0;t<T;t++){
Solution sol1=new Solution(out,fs);
sol1.solution(T,t);
}
out.flush();
}
public static int[] Arr(int n){
int A[]=new int[n];
for(int i=0;i<n;i++)A[i]=Int();
return A;
}
public static int Int(){
return fs.Int();
}
public static long Long(){
return fs.Long();
}
public static String Str(){
return fs.Str();
}
}
class Solution {
PrintWriter out;
int INF = Integer.MAX_VALUE;
int NINF = Integer.MIN_VALUE;
int MOD = 998244353;
int mod = 998244353;
Main.FastScanner fs;
public Solution(PrintWriter out, Main.FastScanner fs) {
this.out = out;
this.fs = fs;
}
public void add(Map<Integer, Integer> f, int key) {
Integer cnt = f.get(key);
if(cnt == null) {
f.put(key, 1);
} else {
f.put(key, cnt + 1);
}
}
public void del(Map<Integer, Integer> f, int key) {
Integer cnt = f.get(key);
if(cnt == 1) {
f.remove(key);
} else {
f.put(key, cnt - 1);
}
}
public void msg(String s) {
System.out.println(s);
}
public void solution(int all, int testcase) {
int n = fs.Int(), m = fs.Int(), q =fs.Int();
int a[][] = new int[n][m];
int ids[][] = new int[n][m];
int sum = 0;
for(int i = 0; i < n; i++) {
String s = fs.Str();
for(int j = 0; j < m; j++) {
if(s.charAt(j) == '*') {
a[i][j] = 1;
sum ++;
}
}
}
int id = 0;
FenWick fen = new FenWick(n * m + 1);
for(int c = 0; c < m; c++) {
for(int r = 0; r < n; r++) {
if(a[r][c] == 1) {
fen.update(id, 1);
}
ids[r][c] = id++;
}
}
//for(int p[]:ids){
//System.out.println(Arrays.toString(p));
//}
for(int i = 0; i < q; i++) {
int r = fs.Int(), c =fs.Int();
r--; c--;
int ith = ids[r][c];
if(a[r][c] == 1) {
sum--;
a[r][c] = 0;
fen.update(ith, -1);
} else {
a[r][c] = 1;
sum++;
fen.update(ith, 1);
}
int in = fen.sumRange(0, sum - 1);
out.println(sum - in);
}
}
}
class FenWick {
int tree[];//1-index based
public FenWick(int n) {
tree=new int[n+1];
}
public void update(int i, int val) {
i++;
while(i<tree.length){
tree[i]+=val;
i+=(i&-i);
}
}
public int sumRange(int i, int j) {
return pre(j+1)-pre(i);
}
public int pre(int i){
int sum=0;
while(i>0){
sum+=tree[i];
i-=(i&-i);
}
return sum;
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 70670754c66476d48b316c07ab6e4027 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.io.*;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.StringTokenizer;
public class F {
static FastScanner sc = new FastScanner(System.in);
static FastPrintStream out = new FastPrintStream(System.out);
public static void main(String[] args) {
int n = sc.nextInt(), m = sc.nextInt(), q = sc.nextInt();
char[][] f = new char[n][m];
int[][] t = new int[n][m];
int total = 0;
for (int i = 0; i < n; i++) {
String s = sc.next();
for (int j = 0; j < m; j++) {
f[i][j] = s.charAt(j);
if (f[i][j] == '*') {
inc(i, j, 1, t);
total++;
}
}
}
for (int i = 0; i < q; i++) {
int x = sc.nextInt() - 1, y = sc.nextInt() - 1;
if (f[x][y] == '*') {
total--;
f[x][y] = '.';
inc(x, y, -1, t);
} else {
total++;
f[x][y] = '*';
inc(x, y, 1, t);
}
int fullColumns = total / n;
int lastColumn = total % n;
int count = sum(n - 1, fullColumns - 1, t);
count += sum(lastColumn - 1, fullColumns, t);
count -= sum(lastColumn - 1, fullColumns - 1, t);
out.println(total - count);
}
out.flush();
}
private static void inc(int x, int y, int delta, int[][] t) {
int n = t.length;
int m = t[0].length;
for (int i = x; i < n; i = (i | (i + 1))) {
for (int j = y; j < m; j = (j | (j + 1))) {
t[i][j] += delta;
}
}
}
private static int sum(int x, int y, int[][] t) {
if (x < 0 || y < 0) {
return 0;
}
int res = 0;
for (int i = x; i >= 0; i = (i & (i + 1)) - 1) {
for (int j = y; j >= 0; j = (j & (j + 1)) - 1) {
res += t[i][j];
}
}
return res;
}
static long[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextLong();
}
return a;
}
static int[] readIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
return a;
}
static int[] sorted(int[] array) {
ArrayList<Integer> list = new ArrayList<>(array.length);
for (int val : array) {
list.add(val);
}
list.sort(Comparator.naturalOrder());
return list.stream().mapToInt(val -> val).toArray();
}
static long[] sorted(long[] array) {
ArrayList<Long> list = new ArrayList<>(array.length);
for (long val : array) {
list.add(val);
}
list.sort(Comparator.naturalOrder());
return list.stream().mapToLong(val -> val).toArray();
}
static int[] sortedReverse(int[] array) {
ArrayList<Integer> list = new ArrayList<>(array.length);
for (int val : array) {
list.add(val);
}
list.sort(Comparator.reverseOrder());
return list.stream().mapToInt(val -> val).toArray();
}
static long[] sort(long[] array) {
ArrayList<Long> list = new ArrayList<>(array.length);
for (long val : array) {
list.add(val);
}
list.sort(Comparator.naturalOrder());
return list.stream().mapToLong(val -> val).toArray();
}
static long[] sortedReverse(long[] array) {
ArrayList<Long> list = new ArrayList<>(array.length);
for (long val : array) {
list.add(val);
}
list.sort(Comparator.reverseOrder());
return list.stream().mapToLong(val -> val).toArray();
}
private static class FastPrintStream {
private final BufferedWriter writer;
public FastPrintStream(PrintStream out) {
writer = new BufferedWriter(new OutputStreamWriter(out));
}
public void print(char c) {
try {
writer.write(Character.toString(c));
} catch (IOException e) {
e.printStackTrace();
}
}
public void print(int val) {
try {
writer.write(Integer.toString(val));
} catch (IOException e) {
e.printStackTrace();
}
}
public void print(long val) {
try {
writer.write(Long.toString(val));
} catch (IOException e) {
e.printStackTrace();
}
}
public void print(double val) {
try {
writer.write(Double.toString(val));
} catch (IOException e) {
e.printStackTrace();
}
}
public void print(String val) {
try {
writer.write(val);
} catch (IOException e) {
e.printStackTrace();
}
}
public void println(char c) {
print(c + "\n");
}
public void println(int val) {
print(val + "\n");
}
public void println(long val) {
print(val + "\n");
}
public void println(double val) {
print(val + "\n");
}
public void println(String str) {
print(str + "\n");
}
public void println() {
print("\n");
}
public void flush() {
try {
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static class FastScanner {
private final BufferedReader br;
private StringTokenizer st;
public FastScanner(InputStream inputStream) {
br = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public byte nextByte() {
return Byte.parseByte(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 8 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | d7b168de16985d34b25ae331a9e704ad | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.sql.Array;
import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class Main {
public static FastReader cin;
public static PrintWriter out;
public static void main(String[] args) throws Exception {
out = new PrintWriter(new BufferedOutputStream(System.out));
cin = new FastReader();
// int qq = cin.nextInt();
//// int qq = 1;
// label:for(int rrr = 0 ;rrr<qq;rrr++){
//
// }
int n = cin.nextInt();
int m = cin.nextInt();
int q = cin.nextInt();
StringBuilder sb = new StringBuilder();
int icons = 0;
char[][]arr = new char[n][m];//* icon
for(int i = 0 ; i < n ;i++){
String s = cin.next();
arr[i] = s.toCharArray();
}
for(int i = 0; i < m;i++){
for(int j = 0 ; j < n ; j++){
sb.append(arr[j][i]);
if(arr[j][i] =='*'){
icons ++;
}
}
}
int sum = icons;
int res = 0;
for(int i = 0 ; i < sum ;i++){
char ch = sb.charAt(i);
if(ch == '.')res++;
}
for(int i = 0 ; i < q ;i++){
int x = cin.nextInt() - 1;
int y = cin.nextInt() - 1;
int times = 0;
int pos = y * n + x;
if(pos < sum){
if(sb.charAt(pos) == '.'){
--res;
}else{
++res;
}
}
if(sb.charAt(pos) == '.'){
sb.replace(pos,pos + 1,"*");
}else{
sb.replace(pos,pos + 1,".");
}
if(sb.charAt(pos) == '*'){
if(sb.charAt(sum) == '.')res++;
sum++;
}else{
if(sb.charAt(sum - 1) == '.')res--;
sum--;
}
out.println(res);
}
out.close();
}
public static long lcm(long a,long b ){
long ans = a / gcd(a,b) * b ;
return ans;
}
public static long gcd(long a,long b){
if(b==0)return a;
else return gcd(b,a%b);
}
static class SparseTable
{
public int[] log;
public int[][] table;
public int N;
public int K;
public SparseTable(int N)
{
this.N = N;
log = new int[N+2];
K = Integer.numberOfTrailingZeros(Integer.highestOneBit(N));
table = new int[K+1][N];
init();
}
private void init()
{
log[1] = 0;
for(int i = 2; i <= N+1; i++)
log[i] = log[i/2]+1;
}
public void lift(int[] arr)
{
int n = arr.length;
for(int i = 0; i < n; i++)
table[0][i] = arr[i];
for(int i = 1; i <= K; i++)
for(int j = 0; j + (1 << i) <= n; j++)
table[i][j] = Math.max(table[i-1][j], table[i-1][j+(1 << (i - 1))]);
}
public int query(int L, int R)//[L,R]~[1,n]
{
//inclusive, 1 indexed
if (L > R) {
L = L^R;
R = L^R;
L = L^R; // 交换 a 和 b 的值
}
L--; R--;
int s = log[R-L+1];
return Math.max(table[s][L], table[s][R-(1 << s)+1]);
}
}
static class FastReader {
BufferedReader br;
StringTokenizer str;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (str == null || !str.hasMoreElements()) {
try {
str = new StringTokenizer(br.readLine());
} catch (IOException lastMonthOfVacation) {
lastMonthOfVacation.printStackTrace();
}
}
return str.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 lastMonthOfVacation) {
lastMonthOfVacation.printStackTrace();
}
return str;
}
}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 17 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 63c30b5c1387c97ce5ad0347bb3a7028 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes |
import java.io.*;
import java.util.*;
public class DesktopRearrangement {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
int n = sc.nextInt();
int m = sc.nextInt();
int q = sc.nextInt();
char[][] mat = new char[n][m];
for(int i=0;i<n;i++){
mat[i] = sc.next().toCharArray();
}
int c = 0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(mat[i][j] == '*'){
c++;
}
}
}
int col = -1, row = -1, d = 0;
if(c > 0){
col = (c - 1) / n;
row = (c - 1 + n) % n;
for(int j=0;j<col;j++){
for(int i=0;i<n;i++){
if(mat[i][j] == '*'){
d++;
}
}
}
for(int i=0;i<=row;i++){
if(mat[i][col] == '*'){
d++;
}
}
}
while(q-->0){
int x = sc.nextInt()-1;
int y = sc.nextInt()-1;
if(c == 0){
c++;
if(x == 0 && y == 0){
d++;
}
mat[x][y] = '*';
row = 0; col = 0;
}
else if(mat[x][y] == '*'){
c--;
if(y<col || (y==col && x<=row)){
d--;
}
mat[x][y] = '.';
if(mat[row][col] == '*'){
d--;
}
row = (row - 1 + n) % n;
if(row == n-1)
col--;
}
else{
c++;
if(y<col || (y==col && x<=row)){
d++;
}
mat[x][y] = '*';
row = (row + 1) % n;
if(row == 0)
col++;
if(mat[row][col] == '*'){
d++;
}
}
sb.append(c - d).append("\n");
}
System.out.println(sb);
sc.close();
}
static class Soumit {
final private int BUFFER_SIZE = 1 << 18;
final private DataInputStream din;
final private byte[] buffer;
private PrintWriter pw;
private int bufferPointer, bytesRead;
StringTokenizer st;
public Soumit() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Soumit(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public void streamOutput(String file) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
pw = new PrintWriter(bw);
}
public void println(String a) {
pw.println(a);
}
public void print(String a) {
pw.print(a);
}
public String readLine() throws IOException {
byte[] buf = new byte[3000064]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public void sort(int[] arr) {
ArrayList<Integer> arlist = new ArrayList<>();
for (int i : arr)
arlist.add(i);
Collections.sort(arlist);
for (int i = 0; i < arr.length; i++)
arr[i] = arlist.get(i);
}
public void sort(long[] arr) {
ArrayList<Long> arlist = new ArrayList<>();
for (long i : arr)
arlist.add(i);
Collections.sort(arlist);
for (int i = 0; i < arr.length; i++)
arr[i] = arlist.get(i);
}
public int[] nextIntArray(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
public double[] nextDoubleArray(int n) throws IOException {
double[] arr = new double[n];
for (int i = 0; i < n; i++) {
arr[i] = nextDouble();
}
return arr;
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
/*if (din == null)
return;*/
if (din != null) din.close();
if (pw != null) pw.close();
}
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 17 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 7cbf3583116ef011dbbd45e2d66c2c5a | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int q = Integer.parseInt(st.nextToken());
char[] d = new char[n * m];
int cnt = 0;
for (int i = 0; i < n; i++) {
String s = br.readLine();
for (int j = 0; j < m; j++) {
d[i + j * n] = s.charAt(j);
if (d[i + j * n] == '*') {
cnt++;
}
}
}
int fill = getFill(d, cnt);
for (int i = 0; i < q; i++) {
st = new StringTokenizer(br.readLine());
int x = Integer.parseInt(st.nextToken()) - 1;
int y = Integer.parseInt(st.nextToken()) - 1;
int idx = x + y * n;
d[idx] = d[idx] == '.' ? '*' : '.';
if (d[idx] == '*') {
cnt++;
if (d[cnt - 1] == '*') {
fill++;
}
if (idx < cnt - 1) {
fill++;
}
} else {
cnt--;
if (d[cnt] == '*') {
fill--;
}
if (idx < cnt + 1) {
fill--;
}
}
bw.write((cnt - fill) + "\n");
}
bw.flush();
}
public static int getFill(char[] d, int cnt) {
int result = 0;
for (int i = 0; i < d.length && i < cnt; i++) {
if (d[i] == '*') {
result++;
}
}
return result;
}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 11 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 1528500031e65d0c3451c1da202f028d | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.math.BigInteger;
import static java.lang.System.in;
import static java.lang.System.out;
import static java.lang.Math.*;
import java.util.*;
public class Main {
static public void main(String[] args){
Read in = new Read(System.in);
solve(in);
}
static void solve(Read in){
int n = in.nextInt();
int m = in.nextInt();
int q = in.nextInt();
boolean[][] map = new boolean[n][m];
int cot = 0;
for(int i = 0; i < n; i++){
String s = in.next();
for(int j = 0; j < m; j++){
char c = s.charAt(j);
if(c=='*'){
map[i][j] = true;
cot++;
}
else map[i][j] = false;
}
}
int a = n-1;
int b = -1;
int ans = 0;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(cot <= 0 && map[j][i]){
ans++;
}
if(cot == 1){
a=j;
b=i;
}
cot--;
}
}
while(q > 0){
q--;
int x = in.nextInt()-1;
int y = in.nextInt()-1;
if(map[x][y]){
//删
int a_ = a;
int b_ = b;
if(a_ == 0){
a_ = n - 1;
b_ --;
}else{
a_--;
}
if(y < b_ || y == b_ && x <= a_){
if(map[a][b]){
ans++;
}
}else{
if(!map[a][b]){
ans--;
}
}
map[x][y] = false;
a=a_;
b=b_;
}else{
//增
int a_ = a;
int b_ = b;
if(a_ == n - 1){
b_ ++;
a_ = 0;
}else{
a_ ++;
}
if(y < b_ || y == b_ && x <= a_){
if(map[a_][b_]){
ans--;
}
}else{
if(!map[a_][b_]){
ans++;
}
}
map[x][y] = true;
a = a_;
b = b_;
}
out.println(ans);
}
}
static class Read {//自定义快读 Read
public BufferedReader reader;
public StringTokenizer tokenizer;
public Read(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 String nextLine() {
String str = null;
try {
str = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public Double nextDouble() {
return Double.parseDouble(next());
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
}
static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
static long gcd(long a, long b) {
return (a % b == 0) ? b : gcd(b, a % b);
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 11 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | f24e5b3ea60877b506c72d5f4cff0b18 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
public class F {
//java -Xss515m Solution.java < input.txt
private static final String SPACE = "\\s+";
private static final int MOD = 1_000_000_007;
private static final Reader in = new Reader();
public static void main(String[] args) throws IOException {
int m = in.readInt();
int n = in.readInt();
int q = in.readInt();
char[][] board = new char[m][n];
for (int i = 0; i < m; i++) {
board[i] = in.readString().toCharArray();
}
int[] A = new int[m * n];
int total = 0;
for (int i = 0; i < A.length; i++) {
char c = board[i % m][i / m];
if (c == '*') {
A[i] = 1;
total++;
}
}
int slotted = 0;
for (int i = 0; i < total; i++) {
if (A[i] == 1) {
slotted++;
}
}
while (q-- > 0) {
int i = indexOf(in.readInt(), in.readInt(), m);
if (A[i] == 1) {
if (A[total - 1] == 1) {
slotted--;
}
total--;
if (i < total) {
slotted--;
}
} else {
if (A[total] == 1) {
slotted++;
}
total++;
if (i < total) {
slotted++;
}
}
A[i] ^= 1;
// System.out.println("total: " + total);
// System.out.println("slotted: " + slotted);
// print(A);
System.out.println(total - slotted);
}
}
private static int indexOf(int a, int b, int m) throws IOException {
return (b - 1) * m + (a - 1);
}
// Utility functions
private static int max(int... nums) {
int max = Integer.MIN_VALUE;
for (int num : nums) {
max = Math.max(max, num);
}
return max;
}
private static int min(int... nums) {
int min = Integer.MAX_VALUE;
for (int num : nums) {
min = Math.min(min, num);
}
return min;
}
private static long max(long... nums) {
long max = Long.MIN_VALUE;
for (long num : nums) {
max = Math.max(max, num);
}
return max;
}
private static long min(long... nums) {
long min = Long.MAX_VALUE;
for (long num : nums) {
min = Math.min(min, num);
}
return min;
}
private static void shuffleSort(int[] nums) {
shuffle(nums);
Arrays.sort(nums);
}
private static void shuffle(int[] nums) {
Random random = ThreadLocalRandom.current();
for (int i = nums.length - 1; i > 0; i--) {
swap(random.nextInt(i), i, nums);
}
}
private static void swap(int a, int b, int[] nums) {
int temp = nums[a];
nums[a] = nums[b];
nums[b] = temp;
}
private static void shuffleSort(long[] nums) {
shuffle(nums);
Arrays.sort(nums);
}
private static void shuffle(long[] nums) {
Random random = ThreadLocalRandom.current();
for (int i = nums.length - 1; i > 0; i--) {
swap(random.nextInt(i), i, nums);
}
}
private static void swap(int a, int b, long[] nums) {
long temp = nums[a];
nums[a] = nums[b];
nums[b] = temp;
}
private static long pow(int base, int exp) {
long res = 1;
while (exp-- > 0) {
res *= base;
}
return res;
}
private static long pow(int base, int exp, Long[][] memo) {
if (exp == 0) return 1;
if (memo[base][exp] != null) return memo[base][exp];
return memo[base][exp] = base * pow(base, exp - 1, memo) % MOD;
}
private static void print(int[] nums) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < nums.length; i++) {
sb.append(nums[i]).append(" ");
}
System.out.println(sb);
}
private static void print(long[] nums) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < nums.length; i++) {
sb.append(nums[i]).append(" ");
}
System.out.println(sb);
}
private static void print(String[] A) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < A.length; i++) {
sb.append(A[i]).append(" ");
}
System.out.println(sb);
}
private static int gcd(int p, int q) {
if (q == 0) return p;
return gcd(q, p % q);
}
private static class Reader {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int index = 0;
String[] tokens = {};
public int readInt() throws IOException {
read();
return Integer.parseInt(tokens[index++]);
}
public long readLong() throws IOException {
read();
return Long.parseLong(tokens[index++]);
}
public String readString() throws IOException {
read();
return tokens[index++];
}
public String readLine() throws IOException {
return in.readLine();
}
public int[] readInts() throws IOException {
return Arrays.stream(in.readLine().split(SPACE)).mapToInt(Integer::parseInt).toArray();
}
public long[] readLongs() throws IOException {
return Arrays.stream(in.readLine().split(SPACE)).mapToLong(Long::parseLong).toArray();
}
public String[] readStrings() throws IOException {
return in.readLine().split(SPACE);
}
private void read() throws IOException {
if (index >= tokens.length) {
tokens = in.readLine().split(SPACE);
index = 0;
}
}
}
private static class UnionFind {
int[] p;
public UnionFind(int n) {
Arrays.fill(p = new int[n], -1);
}
public int find(int i) {
return p[i] < 0 ? i : (p[i] = find(p[i]));
}
public boolean union(int i, int j) {
if ((i = find(i)) == (j = find(j))) return false;
if (p[i] == p[j]) p[i]--;
if (p[i] <= p[j]) p[j] = i;
else p[i] = j;
return true;
}
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 11 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 69bf65e2047ca6709c43129f19241f9a | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | /*
4 4 8
..**
.*..
*...
...*
1 3
2 3
3 1
2 3
3 4
4 3
2 3
2 2
*/
import java.util.*;
import java.io.*;
public class Main{
public static int n;
public static int m;
public static char[][] grid; //n by m desktop
public static boolean[][] inPlace; //true if an asterisk is in place, false if not
public static int q; //# of queries, up to 2 * 10^5
public static int asterisks = 0; //# of asterisks
public static int min = 0; //min # of moves to rearrange desktop so that it is "good"
public static int[] threshold = {0,0}; //n,m of the last asterisk on the 'good' arrangement
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer details = new StringTokenizer(br.readLine());
n = Integer.parseInt(details.nextToken());
m = Integer.parseInt(details.nextToken());
q = Integer.parseInt(details.nextToken());
//min cost to rearrange desktop is the # of asterisks minus the # of asterisks in the 'right' places (where an asterisk is placed correctly if it is in the first (# of asterisks/n) columns or the # of asterisks % mth row of the ((# of asterisks/n) + 1)th column
grid = new char[n][m];
inPlace = new boolean[n][m];
for(int a = 0; a < n; a++){
String row = br.readLine();
for(int b = 0; b < m; b++){
grid[a][b] = row.charAt(b);
if(grid[a][b] == '*') asterisks++;
}
}
threshold[0] = asterisks/n;
threshold[1] = asterisks%n;
min = n * m;
//System.out.println(Arrays.toString(threshold));
for(int a = 0; a < m; a++) for(int b = 0; b < n; b++) update(a,b);
//for(boolean[] row : inPlace) System.out.println(Arrays.toString(row));
//System.out.println(min);
//System.out.println();
for(int a = 0; a < q; a++){
StringTokenizer toggle = new StringTokenizer(br.readLine());
int x = Integer.parseInt(toggle.nextToken())-1;
int y = Integer.parseInt(toggle.nextToken())-1;
if(grid[x][y] == '*'){
asterisks--;
grid[x][y] = '.';
//move one up from original threshold position, need to update the position where the threshold was originally
int px = threshold[0];
int py = threshold[1];
threshold[1]--;
if(threshold[1] < 0){
threshold[1] = n-1;
threshold[0]--;
}
update(px, py);
update(threshold[0], threshold[1]);
update(y,x);
}
else{
asterisks++;
grid[x][y] = '*';
//move one down from original threshold position, need to update the new spot that the threshold fills
int px = threshold[0];
int py = threshold[1];
threshold[1]++;
if(threshold[1] >= n){
threshold[1] = 0;
threshold[0]++;
}
//System.out.println("threshold is " + Arrays.toString(threshold));
update(px, py);
update(threshold[0], threshold[1]);
update(y,x);
}
//System.out.println("threshold is " + Arrays.toString(threshold));
//System.out.println();
//for(char[] row : grid) System.out.println(String.valueOf(row));
//System.out.println();
//for(boolean[] row : inPlace) System.out.println(Arrays.toString(row));
//System.out.println();
System.out.println(min);
//System.out.println("----------------------");
}
br.close();
}
public static void update(int x, int y){
//given a new # of asterisks + different threshold, update this position and min
if(y >= n || x >= m) return;
if(grid[y][x] == '.'){
if(!inPlace[y][x]){
inPlace[y][x] = true;
min--;
}
return;
}
//System.out.println("is " + x + " " + y + " within " + Arrays.toString(threshold));
if(x < threshold[0] || (x <= threshold[0] && y < threshold[1])){
if(!inPlace[y][x]){
inPlace[y][x] = true;
min--;
}
//System.out.println("yes");
}
else{
//System.out.println("no");
if(inPlace[y][x]){
inPlace[y][x] = false;
min++;
}
}
}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 11 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | ab57b6278a89a124bc5dfb4fe918df16 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.util.StringTokenizer;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.Array;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;
import java.util.ArrayList;
public class p4
{
BufferedReader br;
StringTokenizer st;
BufferedWriter bw;
public static void main(String[] args)throws Exception
{
new p4().run();
}
void run()throws IOException
{
br = new BufferedReader(new InputStreamReader(System.in));
bw=new BufferedWriter(new OutputStreamWriter(System.out));
solve();
}
void solve() throws IOException
{
int n=ni();
int m=ni();
int q=ni();
char c[][]=nmc(n);
data []d=dataArray(q);
int star=0;
for(int i=-1;++i<n*m;)
{
if(c[i/m][i%m]=='*')
star++;
}
int x=star%n, y=star/n;
x--;
if(x<0 && y>0)
{
x+=n;
y--;
}
int ans=0;
for(int i=-1;++i<n*m;)
{
if(c[i/m][i%m]=='*')
{
if(i%m>y)
ans++;
else if(i%m==y && i/m>x)
ans++;
}
}
for(int i=-1;++i<q;)
{
int X=d[i].x-1, Y=d[i].y-1;
if(c[X][Y]=='*')
{
if(c[x][y]=='*')
{
if((Y<y) || (Y==y && X<x))
ans++;
}
else
{
if((Y>y) || (Y==y && X>x))
ans--;
}
x--;
if(x==-1 && y>0)
{
x=n-1;
y--;
}
c[X][Y]='.';
}
else
{
x++;
if(x==n)
{
x=0;
y++;
}
if(c[x][y]=='*')
{
if((Y<y) || (Y==y && X<x))
ans--;
}
else
{
if((Y>y) || (Y==y && X>x))
ans++;
}
c[X][Y]='*';
}
bw.write(ans+"\n");
}
bw.flush();
}
public int gcd(int a, int b)
{
if(a==0)
return b;
else
return gcd(b%a,a);
}
int[] nai(int n) { int a[]=new int[n]; for(int i=-1;++i<n;)a[i]=ni(); return a;}
Integer[] naI(int n) { Integer a[]=new Integer[n]; for(int i=-1;++i<n;)a[i]=ni(); return a;}
long[] nal(int n) { long a[]=new long[n]; for(int i=-1;++i<n;)a[i]=nl(); return a;}
char[] nac() {char c[]=nextLine().toCharArray(); return c;}
char [][] nmc(int n) {char c[][]=new char[n][]; for(int i=-1;++i<n;)c[i]=nac(); return c;}
int[][] nmi(int r, int c) {int a[][]=new int[r][c]; for(int i=-1;++i<r;)a[i]=nai(c); return a;}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int[] intArray(Integer[] a) {
int n=a.length;
int b[]=new int[n];
for(int i=-1;++i<n;)
b[i]=a[i].intValue();
return b;
}
int ni() { return Integer.parseInt(next()); }
byte nb() { return Byte.parseByte(next()); }
short ns() { return Short.parseShort(next()); }
long nl() { return Long.parseLong(next()); }
double nd() { return Double.parseDouble(next()); }
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
int countDigits(int l) {
if (l >= 1000000000) return 10;
if (l >= 100000000) return 9;
if (l >= 10000000) return 8;
if (l >= 1000000) return 7;
if (l >= 100000) return 6;
if (l >= 10000) return 5;
if (l >= 1000) return 4;
if (l >= 100) return 3;
if (l >= 10) return 2;
return 1;
}
int countDigits(long l) {
if (l >= 1000000000000000000L) return 19;
if (l >= 100000000000000000L) return 18;
if (l >= 10000000000000000L) return 17;
if (l >= 1000000000000000L) return 16;
if (l >= 100000000000000L) return 15;
if (l >= 10000000000000L) return 14;
if (l >= 1000000000000L) return 13;
if (l >= 100000000000L) return 12;
if (l >= 10000000000L) return 11;
if (l >= 1000000000L) return 10;
if (l >= 100000000L) return 9;
if (l >= 10000000L) return 8;
if (l >= 1000000L) return 7;
if (l >= 100000L) return 6;
if (l >= 10000L) return 5;
if (l >= 1000L) return 4;
if (l >= 100L) return 3;
if (l >= 10L) return 2;
return 1;
}
public int[] primeNO(long limit)
{
int size=(int)Math.sqrt(limit)+1;
int size1=size/2;
boolean composite[]=new boolean[size1];
int zz=(int)Math.sqrt(size-1);
for(int i=3;i<=zz;)
{
for(int j=(i*i)/2;j<size1;j+=i)
composite[j]=true;
for(i+=2;composite[i/2];i+=2);
}
int prime[]=new int[3401];
prime[0]=2;
int p=1;
for(int i=1;i<size1;i++)
{
if(!composite[i])
prime[p++]=2*i+1;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
// System.out.println(p);
////////////////////////////////////////////////////////////////////////////////////////////////////////
prime=Arrays.copyOf(prime, p);
return prime;
}
public static class queue
{
public static class node
{
node next;
int val;
public node(int val)
{
this.val=val;
}
}
node head,tail;
public void add(int val)
{
node a=new node(val);
if(head==null)
{
head=tail=a;
return;
}
tail.next=a;
tail=a;
}
public int remove()
{
int a=head.val;
head=head.next;
if(head==null)
tail=null;
return a;
}
}
public static class stack
{
public static class node
{
node next;
int val;
public node(int val)
{
this.val=val;
}
}
node head;
public void add(int val)
{
node a=new node(val);
a.next=head;
head=a;
}
public int remove()
{
int a=head.val;
head=head.next;
return a;
}
}
public static class data
{
int x,y;
public data(int a, int b)
{
this.x=a;
this.y=b;
}
}
public data[] dataArray(int n)
{
data d[]=new data[n];
for(int i=-1;++i<n;)
d[i]=new data(ni(), ni());
return d;
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 11 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | cf27b4b7b77ddc27addcdf69f69a8245 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.util.StringTokenizer;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.Array;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;
import java.util.ArrayList;
public class p4
{
BufferedReader br;
StringTokenizer st;
BufferedWriter bw;
public static void main(String[] args)throws Exception
{
new p4().run();
}
void run()throws IOException
{
br = new BufferedReader(new InputStreamReader(System.in));
bw=new BufferedWriter(new OutputStreamWriter(System.out));
solve();
}
void solve() throws IOException
{
int n=ni();
int m=ni();
int q=ni();
char c[][]=nmc(n);
data []d=dataArray(q);
int star=0;
for(int i=-1;++i<n*m;)
{
if(c[i/m][i%m]=='*')
star++;
}
int x=star%n, y=star/n;
x--;
if(x<0 && y>0)
{
x+=n;
y--;
}
int ans=0;
for(int i=-1;++i<n*m;)
{
if(c[i/m][i%m]=='*')
{
if(i%m>y)
ans++;
else if(i%m==y && i/m>x)
ans++;
}
}
for(int i=-1;++i<q;)
{
int X=d[i].x-1, Y=d[i].y-1;
if(c[X][Y]=='*')
{
if(c[x][y]=='*')
{
if((Y<y) || (Y==y && X<x))
ans++;
}
else
{
if((Y>y) || (Y==y && X>x))
ans--;
}
x--;
if(x==-1 && y>0)
{
x=n-1;
y--;
}
c[X][Y]='.';
}
else
{
x++;
if(x==n)
{
x=0;
y++;
}
if(c[x][y]=='*')
{
if((Y<y) || (Y==y && X<x))
ans--;
}
else
{
if((Y>y) || (Y==y && X>x))
ans++;
}
c[X][Y]='*';
}
System.out.println(ans);
}
}
public int gcd(int a, int b)
{
if(a==0)
return b;
else
return gcd(b%a,a);
}
int[] nai(int n) { int a[]=new int[n]; for(int i=-1;++i<n;)a[i]=ni(); return a;}
Integer[] naI(int n) { Integer a[]=new Integer[n]; for(int i=-1;++i<n;)a[i]=ni(); return a;}
long[] nal(int n) { long a[]=new long[n]; for(int i=-1;++i<n;)a[i]=nl(); return a;}
char[] nac() {char c[]=nextLine().toCharArray(); return c;}
char [][] nmc(int n) {char c[][]=new char[n][]; for(int i=-1;++i<n;)c[i]=nac(); return c;}
int[][] nmi(int r, int c) {int a[][]=new int[r][c]; for(int i=-1;++i<r;)a[i]=nai(c); return a;}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int[] intArray(Integer[] a) {
int n=a.length;
int b[]=new int[n];
for(int i=-1;++i<n;)
b[i]=a[i].intValue();
return b;
}
int ni() { return Integer.parseInt(next()); }
byte nb() { return Byte.parseByte(next()); }
short ns() { return Short.parseShort(next()); }
long nl() { return Long.parseLong(next()); }
double nd() { return Double.parseDouble(next()); }
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
int countDigits(int l) {
if (l >= 1000000000) return 10;
if (l >= 100000000) return 9;
if (l >= 10000000) return 8;
if (l >= 1000000) return 7;
if (l >= 100000) return 6;
if (l >= 10000) return 5;
if (l >= 1000) return 4;
if (l >= 100) return 3;
if (l >= 10) return 2;
return 1;
}
int countDigits(long l) {
if (l >= 1000000000000000000L) return 19;
if (l >= 100000000000000000L) return 18;
if (l >= 10000000000000000L) return 17;
if (l >= 1000000000000000L) return 16;
if (l >= 100000000000000L) return 15;
if (l >= 10000000000000L) return 14;
if (l >= 1000000000000L) return 13;
if (l >= 100000000000L) return 12;
if (l >= 10000000000L) return 11;
if (l >= 1000000000L) return 10;
if (l >= 100000000L) return 9;
if (l >= 10000000L) return 8;
if (l >= 1000000L) return 7;
if (l >= 100000L) return 6;
if (l >= 10000L) return 5;
if (l >= 1000L) return 4;
if (l >= 100L) return 3;
if (l >= 10L) return 2;
return 1;
}
public int[] primeNO(long limit)
{
int size=(int)Math.sqrt(limit)+1;
int size1=size/2;
boolean composite[]=new boolean[size1];
int zz=(int)Math.sqrt(size-1);
for(int i=3;i<=zz;)
{
for(int j=(i*i)/2;j<size1;j+=i)
composite[j]=true;
for(i+=2;composite[i/2];i+=2);
}
int prime[]=new int[3401];
prime[0]=2;
int p=1;
for(int i=1;i<size1;i++)
{
if(!composite[i])
prime[p++]=2*i+1;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
// System.out.println(p);
////////////////////////////////////////////////////////////////////////////////////////////////////////
prime=Arrays.copyOf(prime, p);
return prime;
}
public static class queue
{
public static class node
{
node next;
int val;
public node(int val)
{
this.val=val;
}
}
node head,tail;
public void add(int val)
{
node a=new node(val);
if(head==null)
{
head=tail=a;
return;
}
tail.next=a;
tail=a;
}
public int remove()
{
int a=head.val;
head=head.next;
if(head==null)
tail=null;
return a;
}
}
public static class stack
{
public static class node
{
node next;
int val;
public node(int val)
{
this.val=val;
}
}
node head;
public void add(int val)
{
node a=new node(val);
a.next=head;
head=a;
}
public int remove()
{
int a=head.val;
head=head.next;
return a;
}
}
public static class data
{
int x,y;
public data(int a, int b)
{
this.x=a;
this.y=b;
}
}
public data[] dataArray(int n)
{
data d[]=new data[n];
for(int i=-1;++i<n;)
d[i]=new data(ni(), ni());
return d;
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 11 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | b411f089c3286428a88526f62eed3756 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static int n, m, q, ha, test, N = 1001;
static int[] g = new int[N*N];
static int[] tr = new int[N*N];
static String io[], s;
static void add(int x, int w){
for (int i = x;i <= n+(m-1)*n;i += i&-i) tr[i] += w;
}
static int sum(int x){
int res = 0;
for (int i = x;i > 0;i -= i&-i) res += tr[i];
return res;
}
public static void main(String[] args) throws Exception {
io = in.readLine().split(" ");
n = Integer.parseInt(io[0]); m = Integer.parseInt(io[1]);
q = Integer.parseInt(io[2]);
for (int i = 0;i < n;i++){
s = in.readLine();
for (int j = 0;j < m;j++){
g[i+j*n+1] = s.charAt(j)=='.' ? 0 : 1;
if (g[i+j*n+1] == 1){
add(i+j*n+1, 1);
ha++;
}
}
}
while (q-- > 0){
io = in.readLine().split(" ");
int x = Integer.parseInt(io[0])-1, y = Integer.parseInt(io[1])-1, ans = 0;
if (g[x+y*n+1] == 1){
ha--;
add(x+y*n+1, -1);
}else{
ha++;
add(x+y*n+1, 1);
}
g[x+y*n+1] = 1-g[x+y*n+1];
ans = ha-sum(ha);
out.println(ans);
}
out.flush();
}
static int ni() throws IOException {
input.nextToken();
return (int) input.nval;
}
static long nl() throws IOException {
input.nextToken();
return (long) input.nval;
}
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static StreamTokenizer input = new StreamTokenizer(in);
static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
}
class E{
int to, ne, wt;
E(int t, int n) {to = t;ne = n;}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 11 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 5a0157760b2921a7fe549964eb640966 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
in = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
try {
// int t = in.nextInt(); while(t-- > 0) { solve(); out.println();}
solve();
} finally {
out.close();
}
return;
}
public static void solve() {
int n = in.nextInt(), m = in.nextInt(), q = in.nextInt();
char[][] s = new char[n][m];
for(int i = 0; i < n; i++) {
s[i] = fillArray();
}
Vector<Long> ss = new Vector<Long>();
int cnt = 0;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(s[i][j] == '*') {
cnt++;
long val = (long)n * (long)j + (long)i;
ss.add(val);
}
}
}
Set<Long> lower = new TreeSet<Long>();
Set<Long> higher =new TreeSet<Long>();
for(long el : ss) {
if(el >= cnt) {
higher.add(el);
} else {
lower.add(el);
}
}
for(int i = 0; i < q; i++) {
int row = in.nextInt() - 1;
int col = in.nextInt() - 1;
long candidate = (long)n * (long)(col) + (long)row;
if(s[row][col] == '*') {
s[row][col] = '.';
boolean wasRemoved = lower.remove((long)(cnt - 1));
if(wasRemoved) {
higher.add((long)(cnt -1));
}
lower.remove(candidate);
higher.remove(candidate);
cnt--;
} else {
s[row][col] = '*';
boolean wasRemoved = higher.remove((long)cnt);
if(wasRemoved) {
lower.add((long)cnt);
}
if(candidate <= cnt) {
lower.add((long)candidate);
} else {
higher.add((long)candidate);
}
cnt++;
}
out.println(cnt - lower.size());
}
return;
}
//-------------- Helper methods-------------------
public static int[] fillArray(int n) {
int[] array = new int[n];
for(int i = 0; i < n; i++) {
array[i] = in.nextInt();
}
return array;
}
public static char[] fillArray() {
char[] array = in.next().toCharArray();
return array;
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
public static MyScanner in;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
void shuffleArray(int[] arr){
int n = arr.length;
Random rnd = new Random();
for(int i=0; i<n; ++i){
int tmp = arr[i];
int randomPos = i + rnd.nextInt(n-i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
}
//--------------------------------------------------------
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 11 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 7b5941fc185792b301ed2faaa9e816db | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.io.*;
import java.util.*;
public class F {
void go() {
int m = Reader.nextInt();
int n = Reader.nextInt();
int q = Reader.nextInt();
char[][] g = new char[m][n];
int[][] qs = new int[q][2];
int tot = 0;
//Queue<Integer> in = new PriorityQueue<>(Comparator.reverseOrder());
//Queue<Integer> out = new PriorityQueue<>();
TreeSet<Integer> in = new TreeSet<>();
TreeSet<Integer> out = new TreeSet<>();
for(int i = 0; i < m; i++) {
String s = Reader.next();
for(int j = 0; j < n; j++) {
g[i][j] = s.charAt(j);
if(g[i][j] == '*') {
tot++;
}
}
}
for(int i = 0; i < q; i++) {
qs[i] = new int[] {Reader.nextInt(), Reader.nextInt()};
}
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(g[i][j] == '*') {
if(j * m + i < tot) {
in.add(j * m + i);
} else {
out.add(j * m + i);
}
}
}
}
for(int i = 0; i < q; i++) {
int r = qs[i][0] - 1;
int c = qs[i][1] - 1;
if(g[r][c] == '*') {
int idx = c * m + r;
if(in.contains(idx)) {
in.remove(idx);
} else {
out.remove(idx);
}
tot--;
if(!in.isEmpty() && in.last() >= tot) {
out.add(in.pollLast());
}
g[r][c] = '.';
} else {
int idx = c * m + r;
tot++;
if(idx < tot) {
in.add(idx);
} else {
out.add(idx);
}
if(!out.isEmpty() && out.first() < tot) {
in.add(out.pollFirst());
}
g[r][c] = '*';
}
Writer.println(out.size());
}
}
void solve() {
go();
}
void run() throws Exception {
Reader.init(System.in);
Writer.init(System.out);
solve();
Writer.close();
}
public static void main(String[] args) throws Exception {
new F().run();
}
public static class Reader {
public static StringTokenizer st;
public static BufferedReader br;
public static void init(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
st = new StringTokenizer("");
}
public static String next() {
while(!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new InputMismatchException();
}
}
return st.nextToken();
}
public static int nextInt() {
return Integer.parseInt(next());
}
public static long nextLong() {
return Long.parseLong(next());
}
public static double nextDouble() {
return Double.parseDouble(next());
}
}
public static class Writer {
public static PrintWriter pw;
public static void init(OutputStream os) {
pw = new PrintWriter(new BufferedOutputStream(os));
}
public static void print(String s) {
pw.print(s);
}
public static void print(char c) {
pw.print(c);
}
public static void print(int x) {
pw.print(x);
}
public static void print(long x) {
pw.print(x);
}
public static void println(String s) {
pw.println(s);
}
public static void println(char c) {
pw.println(c);
}
public static void println(int x) {
pw.println(x);
}
public static void flush() {
pw.flush();
}
public static void println(long x) {
pw.println(x);
}
public static void close() {
pw.close();
}
}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 11 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 520a98400216736dcc7dd9d77a8e9001 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.util.*;
import java.io.*;
public class F {
static class Scan {
private byte[] buf=new byte[1024];
private int index;
private InputStream in;
private int total;
public Scan()
{
in=System.in;
}
public int scan()throws IOException
{
if(total<0)
throw new InputMismatchException();
if(index>=total)
{
index=0;
total=in.read(buf);
if(total<=0)
return -1;
}
return buf[index++];
}
public int scanInt()throws IOException
{
int integer=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
integer*=10;
integer+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
return neg*integer;
}
public double scanDouble()throws IOException
{
double doub=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n)&&n!='.')
{
if(n>='0'&&n<='9')
{
doub*=10;
doub+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
if(n=='.')
{
n=scan();
double temp=1;
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
temp/=10;
doub+=(n-'0')*temp;
n=scan();
}
else throw new InputMismatchException();
}
}
return doub*neg;
}
public String scanString()throws IOException
{
StringBuilder sb=new StringBuilder();
int n=scan();
while(isWhiteSpace(n))
n=scan();
while(!isWhiteSpace(n))
{
sb.append((char)n);
n=scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n)
{
if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
return true;
return false;
}
}
public static void sort(int arr[],int l,int r) { //sort(arr,0,n-1);
if(l==r) {
return;
}
int mid=(l+r)/2;
sort(arr,l,mid);
sort(arr,mid+1,r);
merge(arr,l,mid,mid+1,r);
}
public static void merge(int arr[],int l1,int r1,int l2,int r2) {
int tmp[]=new int[r2-l1+1];
int indx1=l1,indx2=l2;
//sorting the two halves using a tmp array
for(int i=0;i<tmp.length;i++) {
if(indx1>r1) {
tmp[i]=arr[indx2];
indx2++;
continue;
}
if(indx2>r2) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
if(arr[indx1]<arr[indx2]) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
tmp[i]=arr[indx2];
indx2++;
}
//Copying the elements of tmp into the main array
for(int i=0,j=l1;i<tmp.length;i++,j++) {
arr[j]=tmp[i];
}
}
public static void sort(long arr[],int l,int r) { //sort(arr,0,n-1);
if(l==r) {
return;
}
int mid=(l+r)/2;
sort(arr,l,mid);
sort(arr,mid+1,r);
merge(arr,l,mid,mid+1,r);
}
public static void merge(long arr[],int l1,int r1,int l2,int r2) {
long tmp[]=new long[r2-l1+1];
int indx1=l1,indx2=l2;
//sorting the two halves using a tmp array
for(int i=0;i<tmp.length;i++) {
if(indx1>r1) {
tmp[i]=arr[indx2];
indx2++;
continue;
}
if(indx2>r2) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
if(arr[indx1]<arr[indx2]) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
tmp[i]=arr[indx2];
indx2++;
}
//Copying the elements of tmp into the main array
for(int i=0,j=l1;i<tmp.length;i++,j++) {
arr[j]=tmp[i];
}
}
static class seg_tree {
int seg_tree[];
public seg_tree(int n,int arr[]) {
seg_tree=new int[4*n];
create_seg_tree(arr,0,0,n-1);
}
//0 index-Left child-(2*i+1) Right Child-(2*i+2)
public void create_seg_tree(int arr[],int vertex,int l,int r) {
if(l==r) {
seg_tree[vertex]=arr[r];
return;
}
int mid=(l+r)/2;
//Left Child
create_seg_tree(arr,(2*vertex)+1,l,mid);
//Right Child
create_seg_tree(arr,(2*vertex)+2,mid+1,r);
//Filling this node
seg_tree[vertex]=seg_tree[(2*vertex)+1]+seg_tree[(2*vertex)+2];
}
public int sum(int vertex,int l,int r,int ql,int qr) { //ql->query left , qr-> query right l->curr Segmrnt left r->curr segment right
if(ql>qr) {
return 0;
}
if(ql==l && qr==r) {
return seg_tree[vertex];
}
int mid=(l+r)/2;
int total=0;
//Left Child
total+=sum((2*vertex)+1,l,mid,ql,Math.min(qr, mid));
//Right Child
total+=sum((2*vertex)+2,mid+1,r,Math.max(mid+1,ql),qr);
return total;
}
public void update(int vertex,int l,int r,int pos,int value) { //pos->Position of the update value->updates value
if(l==r) {
seg_tree[vertex]=value;
return;
}
int mid=(l+r)/2;
//Left Child
if(pos<=mid) {
update((2*vertex)+1,l,mid,pos,value);
}
//Right Child
else {
update((2*vertex)+2,mid+1,r,pos,value);
}
seg_tree[vertex]=seg_tree[(2*vertex)+1]+seg_tree[(2*vertex)+2];
}
}
public static void main(String args[]) throws IOException {
Scan input=new Scan();
StringBuilder ans=new StringBuilder("");
int n=input.scanInt();
int m=input.scanInt();
int qq=input.scanInt();
int arr[][]=new int[n][m];
int cnt=0;
for(int i=0;i<n;i++) {
String str=input.scanString();
for(int j=0;j<m;j++) {
if(str.charAt(j)=='*') {
arr[i][j]=1;
cnt++;
}
}
}
arr=tp(n,m,arr);
int tmp=n;
n=m;
m=tmp;
seg_tree st[]=new seg_tree[n];
int total[]=new int[n];
// for(int i=0;i<n;i++) {
// for(int j=0;j<m;j++) {
// System.out.print(arr[i][j]+" ");
// }
// System.out.println();
// }
for(int i=0;i<n;i++) {
st[i]=new seg_tree(m,arr[i]);
total[i]=st[i].sum(0, 0, m-1, 0, m-1);
// System.out.println(total[i]);
}
seg_tree st_total=new seg_tree(n,total);
for(int q=1;q<=qq;q++) {
int v=input.scanInt()-1;
int u=input.scanInt()-1;
if(arr[u][v]==0) {
arr[u][v]=1;
cnt++;
st[u].update(0, 0, m-1, v, 1);
}
else {
arr[u][v]=0;
cnt--;
st[u].update(0, 0, m-1, v, 0);
}
st_total.update(0, 0, n-1, u, st[u].sum(0, 0, m-1, 0, m-1));
int rows=cnt/m;
int nxt=cnt%m;
// System.out.println(rows+" "+nxt);
if(cnt==(n*m)) {
ans.append(0+"\n");
continue;
}
int fin=0;
fin+=st_total.sum(0, 0, n-1, rows+1, n-1);
fin+=st[rows].sum(0, 0, m-1, nxt, m-1);
ans.append(fin+"\n");
}
System.out.print(ans);
}
public static int[][] tp(int n,int m,int arr[][]) {
int brr[][]=new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
brr[i][j] = arr[j][i];
}
}
return brr;
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 11 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 2361fbc58c043009a7e382977a93d26c | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main{
public static void main(String[]args){
long s = System.currentTimeMillis();
new Solver().run();
System.err.println(System.currentTimeMillis()-s+"ms");
}
}
class Solver{
final long mod = (long)1e9+7l;
final boolean DEBUG = true, MULTIPLE_TC = false;
FastReader sc;
PrintWriter out;
int N, M, Q, totalIcons;
SegTree segTree, segTreeCol[];
void init(){
N = ni();
M = ni();
Q = ni();
totalIcons = 0;
segTree = new SegTree(M);
segTreeCol = new SegTree[M + 1];
for(int i = 1; i <= M; i++){
segTreeCol[i] = new SegTree(N);
}
for(int i = 1; i <= N; i++){
char ch[] = (" " + nln()).toCharArray();
for(int j = 1; j <= M; j++){
int x = (ch[j] == '.') ? 0 : 1;
if(x == 1){
totalIcons += 1;
segTree.update(j, 1);
segTreeCol[j].update(i, 1);
}
}
}
}
void process(int testNumber){
init();
for(int query = 1; query <= Q; query++){
int row = ni(), col = ni();
int pointUpdateVal = (segTreeCol[col].query(row, row) == 0)? 1 : -1;
segTreeCol[col].update(row, pointUpdateVal);
segTree.update(col, pointUpdateVal);
totalIcons += pointUpdateVal;
int res = 0, fullyOccupiedCols = totalIcons / N;
res += (fullyOccupiedCols * N) - (segTree.query(1, fullyOccupiedCols));
if((totalIcons % N) != 0){
int rem = totalIcons % N;
res += (rem - segTreeCol[(fullyOccupiedCols + 1)].query(1, rem));
}
pn(res);
}
}
void run(){
sc = new FastReader();
out = new PrintWriter(System.out);
int t = MULTIPLE_TC ? ni() : 1;
for(int test = 1; test <= t; test++){
process(test);
}
out.flush();
}
void trace(Object... o){ if(!DEBUG) return; System.err.println(Arrays.deepToString(o)); };
void pn(Object o){ out.println(o); }
void p(Object o){ out.print(o); }
int ni(){ return Integer.parseInt(sc.next()); }
long nl(){ return Long.parseLong(sc.next()); }
double nd(){ return Double.parseDouble(sc.next()); }
String nln(){ return sc.nextLine(); }
long gcd(long a, long b){ return (b==0)?a:gcd(b,a%b);}
int gcd(int a, int b){ return (b==0)?a:gcd(b,a%b); }
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();
}
String nextLine(){
String str = "";
try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); }
return str;
}
}
}
class pair implements Comparable<pair> {
int first, second;
public pair(int first, int second){
this.first = first;
this.second = second;
}
@Override
public int compareTo(pair ob){
if(this.first != ob.first)
return this.first - ob.first;
return this.second - ob.second;
}
@Override
public String toString(){
return this.first + " " + this.second;
}
static public pair from(int f, int s){
return new pair(f, s);
}
}
class SegTree{
int N, tree[];
public SegTree(int N){
this.N = N;
tree = new int[4 * N + 4];
}
void update(int pos, int val, int s, int e, int treeIdx){
if(pos < s || pos > e){
return;
}
if(s == e){
tree[treeIdx] += val;
return;
}
int mid = s + (e - s) / 2;
update(pos, val, s, mid, 2 * treeIdx);
update(pos, val, mid + 1, e, 2 * treeIdx + 1);
tree[treeIdx] = tree[2 * treeIdx] + tree[2 * treeIdx + 1];
}
void update(int pos, int val){
update(pos, val, 1, N, 1);
}
int query(int qs, int qe, int s, int e, int treeIdx){
if(qs <= s && qe >= e){
return tree[treeIdx];
}
if(qs > e || qe < s){
return 0;
}
int mid = s + (e - s) / 2;
int subQuery1 = query(qs, qe, s, mid, 2 * treeIdx),
subQuery2 = query(qs, qe, mid + 1, e, 2 * treeIdx + 1);
int res = subQuery1 + subQuery2;
return res;
}
int query(int l, int r){
return query(l, r, 1, N, 1);
}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 11 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 375b7e303363a7e492a277affaebe43b | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.util.*;
import java.io.*;
// you can compare with output.txt and expected out
public class Round786F {
MyPrintWriter out;
MyScanner in;
final static String IMPOSSIBLE = "IMPOSSIBLE";
final static String POSSIBLE = "POSSIBLE";
final static String YES = "YES";
final static String NO = "NO";
private void preferFileIO(boolean isFileIO) {
if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) {
try{
in = new MyScanner(new FileInputStream("input.txt"));
out = new MyPrintWriter(new FileOutputStream("output.txt"));
}
catch(FileNotFoundException e){
e.printStackTrace();
}
}
else{
in = new MyScanner(System.in);
out = new MyPrintWriter(new BufferedOutputStream(System.out));
}
}
public static void main(String[] args){
// Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
Round786F sol = new Round786F();
sol.run();
}
private void run() {
boolean isDebug = false;
boolean isFileIO = true;
preferFileIO(isFileIO);
int n = in.nextInt();
int m = in.nextInt();
int q = in.nextInt();
String[] ss = new String[n];
for(int j=0; j<n; j++)
ss[j] = in.next();
int[][] qq = new int[q][];
for(int j=0; j<q; j++)
qq[j] = new int[] {in.nextInt()-1, in.nextInt()-1};
int[] ans = solve2(ss, qq);
out.println(ans);
in.close();
out.close();
}
private int[] solve2(String[] ss, int[][] qq) {
int n = ss.length;
int m = ss[0].length();
int q = qq.length;
boolean[][] state = new boolean[n][m];
BinaryIndexedTree T = new BinaryIndexedTree(n*m);
for(int i=0; i<n; i++){
for(int j=0; j<m; j++) {
state[i][j] = ss[i].charAt(j)=='*';
if(state[i][j])
T.update(j*n+i, 1);
}
}
int[] ans = new int[q];
for(int i=0; i<q; i++) {
int r = qq[i][0];
int c = qq[i][1];
if(state[r][c]) { // delete
T.update(c*n+r, -1);
}
else { // add
T.update(c*n+r, 1);
}
state[r][c] = !state[r][c];
int num = T.query(n*m);
ans[i] = num - T.query(num-1);
}
return ans;
}
private int[] solve(String[] ss, int[][] qq) {
int n = ss.length;
int m = ss[0].length();
int q = qq.length;
boolean[][] state = new boolean[n][m];
int num = 0;
for(int i=0; i<n; i++){
for(int j=0; j<m; j++) {
state[i][j] = ss[i].charAt(j)=='*';
if(state[i][j])
num++;
}
}
int numInside = 0;
INIT:
for(int j=0; j<m; j++) {
for(int i=0; i<n; i++) {
if(j*m+i+1 > num)
break INIT;
if(state[i][j])
numInside++;
}
}
int[] ans = new int[q];
for(int i=0; i<q; i++) {
int r = qq[i][0];
int c = qq[i][1];
if(state[r][c]) { // delete
if(c*m+r+1 <= num)
numInside--;
num--;
}
else { // add
num++;
if(c*m+r+1 <= num)
numInside++;
}
state[r][c] = !state[r][c];
ans[i] = num - numInside;
}
return ans;
}
public class BinaryIndexedTree {
int[] a;
final int numBits;
final int max;
int size;
public BinaryIndexedTree(int max){
max++;
size = 0;
int i = 0;
while(max > 0){
i++;
max >>= 1;
}
numBits = i;
this.max = 1<<numBits;
a = new int[this.max];
}
// when we insert x = 0b001_011_001
// we add 1 to 001_011_001, 001_011_010, 001_011_100, 001_100_000, 010_000_000
public void update(int x, int val){
x++; // 1-indexed
while(x < max){
a[x] += val;
// add lowest bit
x += x & (-x);
}
}
// to return # of elems < x
// just query(x-1) ...
// but be careful for the case: x = 0
// returns # of elems <= x
// when we query x = 0b001_011_001
// we look up 001_011_001, 001_011_000, 001_010_000, 001_000_000, 000_000_000
public int query(int x){
x++; // 1-indexed
int sum = 0;
while(x > 0){
sum += a[x];
x -= x & (-x);
}
return sum;
}
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
// 32768?
public MyScanner(InputStream is, int bufferSize) {
br = new BufferedReader(new InputStreamReader(is), bufferSize);
}
public MyScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
// br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
}
public void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
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;
}
int[][] nextGraphEdges(){
return nextGraphEdges(0);
}
int[][] nextGraphEdges(int offset) {
int m = nextInt();
int[][] e = new int[m][2];
for(int i=0; i<m; i++){
e[i][0] = nextInt()+offset;
e[i][1] = nextInt()+offset;
}
return e;
}
int[] nextIntArray(int len) {
return nextIntArray(len, 0);
}
int[] nextIntArray(int len, int offset){
int[] a = new int[len];
for(int j=0; j<len; j++)
a[j] = nextInt()+offset;
return a;
}
long[] nextLongArray(int len) {
return nextLongArray(len, 0);
}
long[] nextLongArray(int len, int offset){
long[] a = new long[len];
for(int j=0; j<len; j++)
a[j] = nextLong()+offset;
return a;
}
}
public static class MyPrintWriter extends PrintWriter{
public MyPrintWriter(OutputStream os) {
super(os);
}
public void print(long[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void println(long[] arr){
print(arr);
println();
}
public void print(int[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void println(int[] arr){
print(arr);
println();
}
public <T> void print(ArrayList<T> arr){
if(arr != null && arr.size() > 0){
print(arr.get(0));
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i));
}
}
}
public <T> void println(ArrayList<T> arr){
print(arr);
println();
}
public void println(int[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public <T> void println(ArrayList<T> arr, int split){
if(arr != null && !arr.isEmpty()){
for(int i=0; i<arr.size(); i+=split){
print(arr.get(i));
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr.get(j));
}
println();
}
}
}
}
static private int[][] constructChildren(int n, int[] parent, int parentRoot){
int[][] childrens = new int[n][];
int[] numChildren = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
numChildren[parent[i]]++;
}
for(int i=0; i<n; i++) {
childrens[i] = new int[numChildren[i]];
}
int[] idx = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
childrens[parent[i]][idx[parent[i]]++] = i;
}
return childrens;
}
static private int[][] constructNeighborhood(int n, int[][] e) {
int[] degree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
degree[u]++;
degree[v]++;
}
int[][] neighbors = new int[n][];
for(int i=0; i<n; i++)
neighbors[i] = new int[degree[i]];
int[] idx = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
neighbors[u][idx[u]++] = v;
neighbors[v][idx[v]++] = u;
}
return neighbors;
}
static private void makeDotUndirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict graph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "--" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
static private void makeDotDirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict digraph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "->" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 11 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 9de001e9eb22363776a14dade0b89caf | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.lang.*;
import java.util.*;
import java.io.*;
import java.awt.Point;
public class A
{
static class SegTree {
int size = 1;
long[] tree;
SegTree(int n) {
while(size < n) size *= 2;
tree = new long[size * 2 - 1];
}
void upd(int i, int v) {
upd(i, v, 0, 0, size);
}
void rev(int i) {
if(sum(i, i + 1) == 1) upd(i, 0); else upd(i, 1);
}
void upd(int i, int v, int x, int lx, int rx) {
if(rx - lx == 1) {
tree[x] = v;
} else {
int m = (rx + lx) / 2;
if(i < m) {
upd(i, v, 2*x + 1, lx, m);
} else {
upd(i, v, 2*x + 2, m, rx);
}
tree[x] = tree[x * 2 + 1] + tree[x * 2 + 2];
}
}
long sum(int l, int r) {
return sum(l, r, 0, 0, size);
}
long sum(int l, int r, int x, int lx, int rx) {
if(lx >= r || rx <= l) return 0;
if(l <= lx && rx <= r) return tree[x];
int m = (rx + lx) / 2;
return sum(l, r, 2*x + 1, lx, m) + sum(l, r, 2*x + 2, m, rx);
}
}
void solve() {
int n = ri(), m = ri(), q = ri();
int[] bit = new int[n * m];
int cnt = 0;
char[][] table = new char[n][m];
int[][] indexes = new int[n][m];
for(int i = 0; i < n; i++) table[i] = rs().toCharArray();
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
indexes[j][i] = cnt;
if(table[j][i] == '*') bit[cnt] = 1;
cnt++;
}
}
SegTree st = new SegTree(n * m);
for(int i = 0; i < n * m; i++) st.upd(i, bit[i]);
int lastIndex;
while(q-- > 0) {
int x = ri(), y = ri();
int pos = indexes[x - 1][y - 1];
bit[pos] = 1 - bit[pos];
st.rev(pos);
lastIndex = (int) st.sum(0, n*m + 1);
out.println(lastIndex - st.sum(0, lastIndex));
}
}
int gcd(int a, int b) {
return a == 0 ? b : gcd(b % a, a);
}
public static void main(String... args) {
new A().run();
}
void run() {
try {
solve();
out.close();
} catch(Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
String readLine() {
try {
return in.readLine();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
String rs() {
while(!tok.hasMoreTokens()) {
tok = new StringTokenizer(readLine());
}
return tok.nextToken();
}
int ri() {
return Integer.parseInt(rs());
}
long rl() {
return Long.parseLong(rs());
}
int[] ria(int n) {
int[] a = new int[n];
for(int i = 0; i < n; i++) a[i] = ri();
return a;
}
double rd() {
return Double.parseDouble(rs());
}
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
StringTokenizer tok = new StringTokenizer("");
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 11 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 537ead117f3c83d027ea324ede66f138 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.math.*;
/**
_ _
( _) ( _)
/ / \\ / /\_\_
/ / \\ / / | \ \
/ / \\ / / |\ \ \
/ / , \ , / / /| \ \
/ / |\_ /| / / / \ \_\
/ / |\/ _ '_| \ / / / \ \\
| / |/ 0 \0\ / | | \ \\
| |\| \_\_ / / | \ \\
| | |/ \.\ o\o) / \ | \\
\ | /\\`v-v / | | \\
| \/ /_| \\_| / | | \ \\
| | /__/_ - / ___ | | \ \\
\| [__] \_/ |_________ \ | \ ()
/ [___] ( \ \ |\ | | //
| [___] |\| \| / |/
/| [____] \ |/\ / / ||
( \ [____ / ) _\ \ \ \| | ||
\ \ [_____| / / __/ \ / / //
| \ [_____/ / / \ | \/ //
| / '----| /=\____ _/ | / //
__ / / | / ___/ _/\ \ | ||
(/-(/-\) / \ (/\/\)/ | / | /
(/\/\) / / //
_________/ / /
\____________/ (
@author NTUDragons-Reborn
*/
public class C{
public static void main(String[] args) throws Exception {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(in, out);
out.close();
}
// main solver
static class Task{
double eps= 0.00000001;
static final int MAXN = 100005;
static final int MOD= 1000000007;
// stores smallest prime factor for every number
static int spf[] = new int[MAXN];
static boolean[] prime;
Map<Integer,Set<Integer>> dp= new HashMap<>();
// Calculating SPF (Smallest Prime Factor) for every
// number till MAXN.
// Time Complexity : O(nloglogn)
public void sieve()
{
spf[1] = 1;
for (int i=2; i<MAXN; i++)
// marking smallest prime factor for every
// number to be itself.
spf[i] = i;
// separately marking spf for every even
// number as 2
for (int i=4; i<MAXN; i+=2)
spf[i] = 2;
for (int i=3; i*i<MAXN; i++)
{
// checking if i is prime
if (spf[i] == i)
{
// marking SPF for all numbers divisible by i
for (int j=i*i; j<MAXN; j+=i)
// marking spf[j] if it is not
// previously marked
if (spf[j]==j)
spf[j] = i;
}
}
}
void sieveOfEratosthenes(int n)
{
// Create a boolean array
// "prime[0..n]" and
// initialize all entries
// it as true. A value in
// prime[i] will finally be
// false if i is Not a
// prime, else true.
prime= new boolean[n + 1];
for (int i = 0; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++)
{
// If prime[p] is not changed, then it is a
// prime
if (prime[p] == true)
{
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
}
// A O(log n) function returning primefactorization
// by dividing by smallest prime factor at every step
public Set<Integer> getFactorization(int x)
{
if(dp.containsKey(x)) return dp.get(x);
Set<Integer> ret = new HashSet<>();
while (x != 1)
{
if(spf[x]!=2) ret.add(spf[x]);
x = x / spf[x];
}
dp.put(x,ret);
return ret;
}
public Map<Integer,Integer> getFactorizationPower(int x){
Map<Integer,Integer> map= new HashMap<>();
while(x!=1){
map.put(spf[x], map.getOrDefault(spf[x], 0)+1);
x/= spf[x];
}
return map;
}
// function to find first index >= x
public int lowerIndex(List<Integer> arr, int n, int x)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr.get(mid) >= x)
h = mid - 1;
else
l = mid + 1;
}
return l;
}
public int lowerIndex(int[] arr, int n, int x)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr[mid] >= x)
h = mid - 1;
else
l = mid + 1;
}
return l;
}
// function to find last index <= y
public int upperIndex(List<Integer> arr, int n, int y)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr.get(mid) <= y)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
public int upperIndex(int[] arr, int n, int y)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr[mid] <= y)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
// function to count elements within given range
public int countInRange(List<Integer> arr, int n, int x, int y)
{
// initialize result
int count = 0;
count = upperIndex(arr, n, y) -
lowerIndex(arr, n, x) + 1;
return count;
}
public int add(int a, int b){
a+=b;
while(a>=MOD) a-=MOD;
while(a<0) a+=MOD;
return a;
}
public int mul(int a, int b){
long res= (long)a*(long)b;
return (int)(res%MOD);
}
public int power(int a, int b) {
int ans=1;
while(b>0){
if((b&1)!=0) ans= mul(ans,a);
b>>=1;
a= mul(a,a);
}
return ans;
}
int[] fact= new int[MAXN];
int[] inv= new int[MAXN];
public int Ckn(int n, int k){
if(k<0 || n<0) return 0;
if(n<k) return 0;
return mul(mul(fact[n],inv[k]),inv[n-k]);
}
public int inverse(int a){
return power(a,MOD-2);
}
public void preprocess() {
fact[0]=1;
for(int i=1;i<MAXN;i++) fact[i]= mul(fact[i-1],i);
inv[MAXN-1]= inverse(fact[MAXN-1]);
for(int i=MAXN-2;i>=0;i--){
inv[i]= mul(inv[i+1],i+1);
}
}
/**
* return VALUE of lower bound for unsorted array
*/
public int lowerBoundNormalArray(int[] arr, int x){
TreeSet<Integer> set= new TreeSet<>();
for(int num: arr) set.add(num);
return set.lower(x);
}
/**
* return VALUE of upper bound for unsorted array
*/
public int upperBoundNormalArray(int[] arr, int x){
TreeSet<Integer> set= new TreeSet<>();
for(int num: arr) set.add(num);
return set.higher(x);
}
public void debugArr(int[] arr){
for(int i: arr) out.print(i+" ");
out.println();
}
public int rand(){
int min=0, max= MAXN;
int random_int = (int)Math.floor(Math.random()*(max-min+1)+min);
return random_int;
}
public void suffleSort(int[] arr){
shuffleArray(arr);
Arrays.sort(arr);
}
public void shuffleArray(int[] ar)
{
// If running on Java 6 or older, use new Random() on RHS here
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
InputReader in; PrintWriter out;
Scanner sc= new Scanner(System.in);
CustomFileReader cin;
int[] xor= new int[3*100000+5];
int[] pow2= new int[1000000+1];
public void solve(InputReader in, PrintWriter out) throws Exception {
this.in=in; this.out=out;
// sieve();
// pow2[0]=1;
// for(int i=1;i<pow2.length;i++){
// pow2[i]= mul(pow2[i-1],2);
// }
int t=1;
// preprocess();
// int t=in.nextInt();
// int t= cin.nextIntArrLine()[0];
for(int i=1;i<=t;i++) solveF(i);
}
final double pi= Math.acos(-1);
int n,m;
void solveF(int test){
n= in.nextInt(); m= in.nextInt();
int q= in.nextInt();
char[][] a= new char[n][m];
int stars= 0;
for(int i=0;i<n;i++){
String line= in.nextToken();
for(int j=0;j<m;j++){
a[i][j]= line.charAt(j);
if(a[i][j]=='*') {
stars++;
}
}
}
Set<String> outside= new HashSet<>();
int row= getRow(stars), col= getCol(stars);
for(int i=0;i<n;i++){for(int j=0;j<m;j++){
if(a[i][j]=='*' && !inside(i,j,row,col)) {
outside.add(i+"-"+j);
}
}}
while(q-->0){
execute: {
int i= in.nextInt()-1, j= in.nextInt()-1;
if(a[i][j]=='*'){
// * -> .
row= getRow(stars); col= getCol(stars);
stars--;
a[i][j]='.';
if(i==row && j==col) break execute;
if(a[row][col]=='*'){
outside.add(row+"-"+col);
}
if(outside.contains(i+"-"+j)) outside.remove(i+"-"+j);
}
else{
// . -> *
stars++;
a[i][j]='*';
row= getRow(stars); col= getCol(stars);
if(i==row && j==col) break execute;
if(a[row][col]=='*'){
outside.remove(row+"-"+col);
}
if(!inside(i, j, row, col)) outside.add(i+"-"+j);
}
}
out.println(outside.size());
}
}
int getCol(int stars){
int col= stars/n;
if(stars%n==0) col--;
return col;
}
int getRow(int stars) {
int row= stars%n -1;
return row==-1?n-1:row;
}
boolean inside(int i, int j, int row, int col){
return j<col || (j==col && i<=row);
}
static class ListNode{
int idx=-1;
ListNode next= null;
public ListNode(int idx){
this.idx= idx;
}
}
public long _gcd(long a, long b)
{
if(b == 0) {
return a;
}
else {
return _gcd(b, a % b);
}
}
public long _lcm(long a, long b){
return (a*b)/_gcd(a,b);
}
}
// static class SEG {
// Pair[] segtree;
// public SEG(int n){
// segtree= new Pair[4*n];
// Arrays.fill(segtree, new Pair(-1,Long.MAX_VALUE));
// }
// // void buildTree(int l, int r, int index) {
// // if (l == r) {
// // segtree[index].y = a[l];
// // return;
// // }
// // int mid = (l + r) / 2;
// // buildTree(l, mid, 2 * index + 1);
// // buildTree(mid + 1, r, 2 * index + 2);
// // segtree[index].y = Math.min(segtree[2 * index + 1].y, segtree[2 * index + 2].y);
// // }
// void update(int l, int r, int index, int pos, Pair val) {
// if (l == r) {
// segtree[index] = val;
// return;
// }
// int mid = (l + r) / 2;
// if (pos <= mid) update(l, mid, 2 * index + 1, pos, val);
// else update(mid + 1, r, 2 * index + 2, pos, val);
// if(segtree[2 * index + 1].y < segtree[2 * index + 2].y){
// segtree[index]= segtree[2 * index + 1];
// }
// else {
// segtree[index]= segtree[2 * index + 2];
// }
// }
// // Pair query(int l, int r, int from, int to, int index) {
// // if (from <= l && r <= to)
// // return segtree[index];
// // if (r < from | to < l)
// // return 0;
// // int mid = (l + r) / 2;
// // Pair left= query(l, mid, from, to, 2 * index + 1);
// // Pair right= query(mid + 1, r, from, to, 2 * index + 2);
// // if(left.y < right.y) return left;
// // else return right;
// // }
// }
static class Venice{
public Map<Long,Long> m= new HashMap<>();
public long base=0;
public long totalValue=0;
private int M= 1000000007;
private long addMod(long a, long b){
a+=b;
if(a>=M) a-=M;
return a;
}
public void reset(){
m= new HashMap<>();
base=0;
totalValue=0;
}
public void update(long add){
base= base+ add;
}
public void add(long key, long val){
long newKey= key-base;
m.put(newKey, addMod(m.getOrDefault(newKey,(long)0),val));
}
}
static class Tuple implements Comparable<Tuple>{
int x, y, z;
public Tuple(int x, int y, int z){
this.x= x;
this.y= y;
this.z=z;
}
@Override
public int compareTo(Tuple o){
return this.z-o.z;
}
}
static class Point implements Comparable<Point>{
public double x;
public long y;
public Point(double x, long y){
this.x= x;
this.y= y;
}
@Override
public int compareTo(Point o) {
if(this.y!=o.y) return (int)(this.y-o.y);
return (int)(this.x-o.x);
}
}
// static class Vector {
// public long x;
// public long y;
// // p1 -> p2
// public Vector(Point p1, Point p2){
// this.x= p2.x-p1.x;
// this.y= p2.y-p1.y;
// }
// }
static class Pair implements Comparable<Pair>{
public int x;
public int y;
public Pair(int x, int y){
this.x= x;
this.y= y;
}
@Override
public int compareTo(Pair o) {
if(this.x!=o.x) return (int)(this.x-o.x);
return (int)(this.y-o.y);
}
}
// public static class compareL implements Comparator<Tuple>{
// @Override
// public int compare(Tuple t1, Tuple t2) {
// return t2.l - t1.l;
// }
// }
// fast input reader class;
static class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream));
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public double nextDouble(){
return Double.parseDouble(nextToken());
}
public long nextLong(){
return Long.parseLong(nextToken());
}
public int[] nextIntArr(int n){
int[] arr= new int[n];
for(int i=0;i<n;i++) arr[i]= nextInt();
return arr;
}
public long[] nextLongArr(int n){
long[] arr= new long[n];
for(int i=0;i<n;i++) arr[i]= nextLong();
return arr;
}
public List<Integer> nextIntList(int n){
List<Integer> arr= new ArrayList<>();
for(int i=0;i<n;i++) arr.add(nextInt());
return arr;
}
public int[][] nextIntMatArr(int n, int m){
int[][] mat= new int[n][m];
for(int i=0;i<n;i++) for(int j=0;j<m;j++) mat[i][j]= nextInt();
return mat;
}
public List<List<Integer>> nextIntMatList(int n, int m){
List<List<Integer>> mat= new ArrayList<>();
for(int i=0;i<n;i++){
List<Integer> temp= new ArrayList<>();
for(int j=0;j<m;j++) temp.add(nextInt());
mat.add(temp);
}
return mat;
}
public char[] nextStringCharArr(){
return nextToken().toCharArray();
}
}
static class CustomFileReader{
String path="";
Scanner sc;
public CustomFileReader(String path){
this.path=path;
try{
sc= new Scanner(new File(path));
}
catch(Exception e){}
}
public String nextLine(){
return sc.nextLine();
}
public int[] nextIntArrLine(){
String line= sc.nextLine();
String[] part= line.split("[\\s+]");
int[] res= new int[part.length];
for(int i=0;i<res.length;i++) res[i]= Integer.parseInt(part[i]);
return res;
}
}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 11 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 8a2bd5c8bc16a7f356d054de94ebc87e | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.security.cert.X509CRL;
import java.util.*;
import java.lang.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;
@SuppressWarnings("unused")
public class Main {
static InputStream is;
static PrintWriter out;
static String INPUT = "";
static String OUTPUT = "";
//global
//private final static long BASE = 998244353L;
private final static int ALPHABET = (int)('z') - (int)('a') + 1;
private final static int BASE = 1000000007;
private final static int INF_I = (1<<31)-1;
private final static long INF_L = (1l<<63)-1;
private final static int MAXN = 100100;
private final static int MAXK = 31;
private static int[] T;
private static void update(int i, int k) {
while (i<T.length) {
T[i] += k;
i = i + (i&(-i));
}
}
private static int query(int i) {
int tmp = 0;
while (i>0) {
tmp += T[i];
i = i - (i&(-i));
}
return tmp;
}
private static int translate(int i, int j, int N, int M) {
return i + j*N;
}
static void solve() {
int ntest = 1;
for (int test=0;test<ntest;test++) {
int N = readInt(), M = readInt(), Q = readInt();
int[][] A = new int[N][M];
T = new int[N*M+1];
int icons = 0;
for (int i=0;i<N;i++) {
char[] s = readString().toCharArray();
for (int j=0;j<M;j++)
if (s[j]=='*') {
A[i][j] = 1;
int pos = translate(i,j,N,M) + 1;
update(pos, 1);
icons++;
}
}
for (int q=0;q<Q;q++) {
int i = readInt() - 1;
int j = readInt() - 1;
int pos = translate(i, j, N, M) + 1;
if (A[i][j] == 0) {
icons += 1;
A[i][j] = 1;
update(pos, 1);
} else {
icons -= 1;
A[i][j] = 0;
update(pos, -1);
}
out.println(icons - query(icons));
}
}
}
public static void main(String[] args) throws Exception
{
long S = System.currentTimeMillis();
if (INPUT=="") {
is = System.in;
} else {
File file = new File(INPUT);
is = new FileInputStream(file);
}
if (OUTPUT == "") out = new PrintWriter(System.out);
else out = new PrintWriter(OUTPUT);
solve();
out.flush();
long G = System.currentTimeMillis();
}
private static class Point<T extends Number & Comparable<T>> implements Comparable<Point<T>> {
private T x;
private T y;
public Point(T x, T y) {
this.x = x;
this.y = y;
}
public T getX() {return x;}
public T getY() {return y;}
@Override
public int compareTo(Point<T> o) {
int cmp = x.compareTo(o.getX());
if (cmp==0) return y.compareTo(o.getY());
return cmp;
}
}
private static class ClassComparator<T extends Comparable<T>> implements Comparator<T> {
public ClassComparator() {}
@Override
public int compare(T a, T b) {
return a.compareTo(b);
}
}
private static class ListComparator<T extends Comparable<T>> implements Comparator<List<T>> {
public ListComparator() {}
@Override
public int compare(List<T> o1, List<T> o2) {
for (int i = 0; i < Math.min(o1.size(), o2.size()); i++) {
int c = o1.get(i).compareTo(o2.get(i));
if (c != 0) {
return c;
}
}
return Integer.compare(o1.size(), o2.size());
}
}
private static boolean eof()
{
if(lenbuf == -1)return true;
int lptr = ptrbuf;
while(lptr < lenbuf)if(!isSpaceChar(inbuf[lptr++]))return false;
try {
is.mark(1000);
while(true){
int b = is.read();
if(b == -1){
is.reset();
return true;
}else if(!isSpaceChar(b)){
is.reset();
return false;
}
}
} catch (IOException e) {
return true;
}
}
private static byte[] inbuf = new byte[1024];
static int lenbuf = 0, ptrbuf = 0;
private static 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 static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
// private static boolean isSpaceChar(int c) { return !(c >= 32 && c <= 126); }
private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private static double readDouble() { return Double.parseDouble(readString()); }
private static char readChar() { return (char)skip(); }
private static String readString()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private static char[] readChar(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 static char[][] readTable(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = readChar(m);
return map;
}
private static int[] readIntArray(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = readInt();
return a;
}
private static long[] readLongArray(int n) {
long[] a = new long[n];
for (int i=0;i<n;i++) a[i] = readLong();
return a;
}
private static int readInt()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private static long readLong()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private static void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); }
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 11 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | eb14604457ad283b208fc5282b320316 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.io.*;
import java.util.*;
public class CF1674F extends PrintWriter {
CF1674F() { super(System.out); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1674F o = new CF1674F(); o.main(); o.flush();
}
int[] ft;
void update(int i, int n, int x) {
while (i < n) {
ft[i] += x;
i |= i + 1;
}
}
int query(int i) {
int x = 0;
while (i >= 0) {
x += ft[i];
i &= i + 1; i--;
}
return x;
}
void main() {
int n = sc.nextInt();
int m = sc.nextInt();
int q = sc.nextInt();
byte[][] cc = new byte[n][];
for (int i = 0; i < n; i++) {
cc[i] = sc.next().getBytes();
for (int j = 0; j < m; j++)
cc[i][j] = (byte) (cc[i][j] == '.' ? 0 : 1);
}
ft = new int[n * m];
int k = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (cc[i][j] == 1) {
update(j * n + i, n * m, 1);
k++;
}
while (q-- > 0) {
int i = sc.nextInt() - 1;
int j = sc.nextInt() - 1;
int x = cc[i][j] == 0 ? 1 : -1;
cc[i][j] ^= 1;
update(j * n + i, n * m, x);
k += x;
println(k - query(k - 1));
}
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 11 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 3349e11d187bf1ed141bf16d0c7dacae | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | //Utilities
import java.io.*;
import java.util.*;
public class a {
static int n, m, q;
static char[][] a;
static int cnt = 0;
static int[][] BIT;
static int r, c;
public static void main(String[] args) throws IOException {
n = in.iscan(); m = in.iscan(); q = in.iscan();
a = new char[n][m]; BIT = new int[n+1][m+1];
for (int i = 0; i < n; i++) {
a[i] = in.sscan().toCharArray();
for (int j = 0; j < m; j++) {
if (a[i][j] == '*') {
update(i+1, j+1, 1);
cnt++;
}
}
}
//out.println("TOT: " + query(n, m));
//out.println("TOT2: " + query(n-1, m));
//out.println("TOT3: " + query(n, m-1));
while (q-- > 0) {
r = in.iscan(); c = in.iscan();
if (a[r-1][c-1] == '*') {
update(r, c, -1);
a[r-1][c-1] = '.';
cnt--;
}
else {
update(r, c, 1);
a[r-1][c-1] = '*';
cnt++;
}
int qc = cnt / n;
int leftOver = cnt - (n * (cnt / n));
int qr = leftOver;
if (qc == 0) {
out.println(cnt - query(qr, 1));
}
else {
if (qr != 0) {
out.println(cnt - (query(n, qc) + query(qr, qc+1) - query(qr, qc)));
}
else {
out.println(cnt - query(n, qc));
}
}
}
out.close();
}
static void update(int r, int c, int v) {
for (int x = r; x <= n; x += x&-x) {
for (int y = c; y <= m; y += y&-y) {
BIT[x][y] += v;
}
}
}
static int query(int r, int c) {
int ret = 0;
for (int x = r; x > 0; x -= x&-x) {
for (int y = c; y > 0; y -= y&-y) {
ret += BIT[x][y];
}
}
return ret;
}
static INPUT in = new INPUT(System.in);
static PrintWriter out = new PrintWriter(System.out);
private static class INPUT {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public INPUT (InputStream stream) {
this.stream = stream;
}
public INPUT (String file) throws IOException {
this.stream = new FileInputStream (file);
}
public int cscan () throws IOException {
if (curChar >= numChars) {
curChar = 0;
numChars = stream.read (buf);
}
if (numChars == -1)
return numChars;
return buf[curChar++];
}
public int iscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c))
c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
int res = 0;
do {
res = (res << 1) + (res << 3);
res += c - '0';
c = cscan ();
}
while (!space (c));
return res * sgn;
}
public String sscan () throws IOException {
int c = cscan ();
while (space (c))
c = cscan ();
StringBuilder res = new StringBuilder ();
do {
res.appendCodePoint (c);
c = cscan ();
}
while (!space (c));
return res.toString ();
}
public double dscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c))
c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
double res = 0;
while (!space (c) && c != '.') {
if (c == 'e' || c == 'E')
return res * UTILITIES.fast_pow (10, iscan ());
res *= 10;
res += c - '0';
c = cscan ();
}
if (c == '.') {
c = cscan ();
double m = 1;
while (!space (c)) {
if (c == 'e' || c == 'E')
return res * UTILITIES.fast_pow (10, iscan ());
m /= 10;
res += (c - '0') * m;
c = cscan ();
}
}
return res * sgn;
}
public long lscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c))
c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
long res = 0;
do {
res = (res << 1) + (res << 3);
res += c - '0';
c = cscan ();
}
while (!space (c));
return res * sgn;
}
public boolean space (int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
public static class UTILITIES {
static final double EPS = 10e-6;
public static void sort(int[] a, boolean increasing) {
ArrayList<Integer> arr = new ArrayList<Integer>();
int n = a.length;
for (int i = 0; i < n; i++) {
arr.add(a[i]);
}
Collections.sort(arr);
for (int i = 0; i < n; i++) {
if (increasing) {
a[i] = arr.get(i);
}
else {
a[i] = arr.get(n-1-i);
}
}
}
public static void sort(long[] a, boolean increasing) {
ArrayList<Long> arr = new ArrayList<Long>();
int n = a.length;
for (int i = 0; i < n; i++) {
arr.add(a[i]);
}
Collections.sort(arr);
for (int i = 0; i < n; i++) {
if (increasing) {
a[i] = arr.get(i);
}
else {
a[i] = arr.get(n-1-i);
}
}
}
public static void sort(double[] a, boolean increasing) {
ArrayList<Double> arr = new ArrayList<Double>();
int n = a.length;
for (int i = 0; i < n; i++) {
arr.add(a[i]);
}
Collections.sort(arr);
for (int i = 0; i < n; i++) {
if (increasing) {
a[i] = arr.get(i);
}
else {
a[i] = arr.get(n-1-i);
}
}
}
public static int lower_bound (int[] arr, int x) {
int low = 0, high = arr.length, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] >= x)
high = mid;
else
low = mid + 1;
}
return low;
}
public static int upper_bound (int[] arr, int x) {
int low = 0, high = arr.length, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] > x)
high = mid;
else
low = mid + 1;
}
return low;
}
public static void updateMap(HashMap<Integer, Integer> map, int key, int v) {
if (!map.containsKey(key)) {
map.put(key, v);
}
else {
map.put(key, map.get(key) + v);
}
if (map.get(key) == 0) {
map.remove(key);
}
}
public static long gcd (long a, long b) {
return b == 0 ? a : gcd (b, a % b);
}
public static long lcm (long a, long b) {
return a * b / gcd (a, b);
}
public static long fast_pow_mod (long b, long x, int mod) {
if (x == 0) return 1;
if (x == 1) return b;
if (x % 2 == 0) return fast_pow_mod (b * b % mod, x / 2, mod) % mod;
return b * fast_pow_mod (b * b % mod, x / 2, mod) % mod;
}
public static long fast_pow (long b, long x) {
if (x == 0) return 1;
if (x == 1) return b;
if (x % 2 == 0) return fast_pow (b * b, x / 2);
return b * fast_pow (b * b, x / 2);
}
public static long choose (long n, long k) {
k = Math.min (k, n - k);
long val = 1;
for (int i = 0; i < k; ++i)
val = val * (n - i) / (i + 1);
return val;
}
public static long permute (int n, int k) {
if (n < k) return 0;
long val = 1;
for (int i = 0; i < k; ++i)
val = (val * (n - i));
return val;
}
// start of permutation and lower/upper bound template
public static void nextPermutation(int[] nums) {
//find first decreasing digit
int mark = -1;
for (int i = nums.length - 1; i > 0; i--) {
if (nums[i] > nums[i - 1]) {
mark = i - 1;
break;
}
}
if (mark == -1) {
reverse(nums, 0, nums.length - 1);
return;
}
int idx = nums.length-1;
for (int i = nums.length-1; i >= mark+1; i--) {
if (nums[i] > nums[mark]) {
idx = i;
break;
}
}
swap(nums, mark, idx);
reverse(nums, mark + 1, nums.length - 1);
}
public static void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
public static void reverse(int[] nums, int i, int j) {
while (i < j) {
swap(nums, i, j);
i++;
j--;
}
}
static int lower_bound (int[] arr, int hi, int cmp) {
int low = 0, high = hi, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] >= cmp) high = mid;
else low = mid + 1;
}
return low;
}
static int upper_bound (int[] arr, int hi, int cmp) {
int low = 0, high = hi, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] > cmp) high = mid;
else low = mid + 1;
}
return low;
}
// end of permutation and lower/upper bound template
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 11 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | ca5938b3a8b9477f745aab6991b718af | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.util.*;
import java.io.*;
public class codeforce {
static boolean multipleTC = false;
final static int Mod = 1000000007;
final static int Mod2 = 998244353;
final double PI = 3.14159265358979323846;
int MAX = 1000000007;
void pre() throws Exception {
}
void solve(int t) throws Exception {
int n = ni();
int m = ni();
int q = ni();
char arr[][] = new char[n+1][m+1];
int cnt = 0, emptyhol = 0;
for(int i=1;i<=n;i++) {
char temp[] = n().toCharArray();
for(int j=1;j<=m;j++) {
arr[i][j] = temp[j-1];
if(arr[i][j] == '*')
cnt++;
}
}
int row = (cnt%n);
int col = (cnt/n);
if(row != 0)
col += 1;
else
row = n;
boolean check = false;
for(int i=1;i<=col;i++) {
for(int j=1;j<=n;j++) {
if((j != row) || (i != col)) {
if(arr[j][i] == '.')
emptyhol++;
}
else {
if(arr[j][i] == '.')
emptyhol++;
check = true;
break;
}
}
if(check)
break;
}
// pn(row + " " + col + " " + cnt + " " + emptyhol);
while(q-- > 0) {
int x = ni();
int y = ni();
if(arr[x][y] == '.') {
cnt++;
if(row == n) {
col += 1;
row = 1;
}
else {
row += 1;
}
if(arr[row][col] == '.')
emptyhol++;
if(y <= col) {
if(y == col) {
if(x <= row)
emptyhol--;
}
else
emptyhol--;
}
arr[x][y] = '*';
}
else {
cnt--;
if(arr[row][col] == '.')
emptyhol--;
if(row == 1) {
col -= 1;
row = n;
}
else {
row -= 1;
}
if(y <= col) {
if(y == col) {
if(x <= row)
emptyhol++;
}
else
emptyhol++;
}
arr[x][y] = '.';
}
pn(emptyhol);
}
}
double dist(int x1, int y1, int x2, int y2) {
double a = x1 - x2, b = y1 - y2;
return Math.sqrt((a * a) + (b * b));
}
int[] readArr(int n) throws Exception {
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = ni();
}
return arr;
}
void sort(int arr[], int left, int right) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = left; i <= right; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = left; i <= right; i++)
arr[i] = list.get(i - left);
}
void sort(int arr[]) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < arr.length; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < arr.length; i++)
arr[i] = list.get(i);
}
// Manual Function Implementation
public int binarySearch(long dp[], int lo, int hi, long x, int succ) {
while(lo<=hi) {
int mid = lo + (hi-lo)/2;
if(dp[mid] <= x)
return binarySearch(dp, (mid+1), hi, x, succ);
else {
succ = mid;
return binarySearch(dp, lo, (mid-1), x , succ);
}
}
return succ;
}
public boolean checkPrime(long n) {
if (n <= 1)
return true;
else if (n == 2)
return true;
else if (n % 2 == 0)
return false;
for (long i = 3; i <= Math.sqrt(n); i += 2){
if (n % i == 0)
return false;
}
return true;
}
public long max(long... arr) {
long max = arr[0];
for (long itr : arr)
max = Math.max(max, itr);
return max;
}
public int max(int... arr) {
int max = arr[0];
for (int itr : arr)
max = Math.max(max, itr);
return max;
}
public long min(long... arr) {
long min = arr[0];
for (long itr : arr)
min = Math.min(min, itr);
return min;
}
public int min(int... arr) {
int min = arr[0];
for (int itr : arr)
min = Math.min(min, itr);
return min;
}
public long sum(long... arr) {
long sum = 0;
for (long itr : arr)
sum += itr;
return sum;
}
public long sum(int... arr) {
long sum = 0;
for (int itr : arr)
sum += itr;
return sum;
}
String bin(long n) {
return Long.toBinaryString(n);
}
String bin(int n) {
return Integer.toBinaryString(n);
}
static int bitCount(int x) {
return x == 0 ? 0 : (1 + bitCount(x & (x - 1)));
}
static void dbg(Object... o) {
System.err.println(Arrays.deepToString(o));
}
int bit(long n) {
return (n == 0) ? 0 : (1 + bit(n & (n - 1)));
}
int abs(int a) {
return (a < 0) ? -a : a;
}
long abs(long a) {
return (a < 0) ? -a : a;
}
void p(Object o) {
out.print(o);
}
void pn(Object o) {
out.println(o);
}
void pni(Object o) {
out.println(o);
out.flush();
}
void pn(int[] arr) {
int n = arr.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(arr[i] + " ");
}
pn(sb);
}
void pn(long[] arr) {
int n = arr.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(arr[i] + " ");
}
pn(sb);
}
String n() throws Exception {
return in.next();
}
String nln() throws Exception {
return in.nextLine();
}
int ni() throws Exception {
return Integer.parseInt(in.next());
}
long nl() throws Exception {
return Long.parseLong(in.next());
}
double nd() throws Exception {
return Double.parseDouble(in.next());
}
public static void main(String[] args) throws Exception {
new codeforce().run();
}
FastReader in;
PrintWriter out;
void run() throws Exception {
in = new FastReader();
out = new PrintWriter(System.out);
int T = (multipleTC) ? ni() : 1;
pre();
for (int t = 1; t <= T; t++)
solve(t);
out.flush();
out.close();
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception {
br = new BufferedReader(new FileReader(s));
}
String next() throws Exception {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new Exception(e.toString());
}
}
return st.nextToken();
}
String nextLine() throws Exception {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
throw new Exception(e.toString());
}
return str;
}
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 11 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | b76eb05f6e813dccbf28584877726187 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
public class Solution {
public static void main(String[] args) {
PrintWriter out = new PrintWriter(System.out);
FastScanner fs = new FastScanner();
DecimalFormat formatter = new DecimalFormat("#0.000000");
int ti = 1;
outer: while (ti-- > 0) {
int n = fs.nextInt();
int m = fs.nextInt();
int q = fs.nextInt();
char[] a = new char[n * m + 1];
int cnt = 0;
for (int i = 1; i <= n; i++) {
char[] c = fs.next().toCharArray();
for (int j = 1; j <= m; j++) {
a[(j - 1) * n + i] = c[j - 1];
if (c[j - 1] == '*')
cnt++;
}
}
int cur = 0;
for (int i = cnt + 1; i <= n * m; i++) {
if (a[i] == '*')
cur++;
}
while (q-- > 0) {
int x = fs.nextInt();
int y = fs.nextInt();
x = (y - 1) * n + x;
if (a[x] == '*') {
a[x] = '.';
cnt--;
if (a[cnt + 1] == '*')
cur++;
if (x > (cnt + 1))
cur--;
} else {
a[x] = '*';
if (x > cnt)
cur++;
cnt++;
if (a[cnt] == '*')
cur--;
}
out.println(cur);
}
}
out.close();
}
private static int two(int a, int b) {
int x = Math.min(a, b);
int y = Math.max(a, b);
if (y >= 2 * x)
return (y + 1) / 2;
else
return (x + y + 2) / 3;
}
private static int the(int a, int b) {
if (b < a)
return the(b, a);
return a + (b - a + 1) / 2;
}
static final int mod = 1_000_000_007;
static void sort(long[] a) {
Random random = new Random();
int n = a.length;
for (int i = 0; i < n; i++) {
int oi = random.nextInt(n);
long temp = a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
static void sort(int[] a) {
Random random = new Random();
int n = a.length;
for (int i = 0; i < n; i++) {
int oi = random.nextInt(n), temp = a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
float nextFloat() {
return Float.parseFloat(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
static class Pair {
int a;
int b;
public Pair(int a, int b) {
this.a = a;
this.b = b;
}
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 11 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 222ad813bbdd0e7417f190bacc778024 | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution {
static int M = 1_000_000_007;
static Random rng = new Random();
private static int[] testCase(int n, int m, int q, char[][] desktop, int[][] rc) {
int[] ans = new int[q], arr = new int[n * m], segmentTree;
int idx, numIcons = 0;
for (int j = 0; j < m; j++) {
for (int i = 0; i < n; i++) {
if (desktop[i][j] == '*') {
numIcons++;
arr[j * n + i] = 1;
}
}
}
segmentTree = buildTree(arr);
for (int i = 0; i < q; i++) {
idx = getIndex(n, rc[i]);
// System.out.println(Arrays.toString(arr));
// System.out.println(Arrays.toString(segmentTree));
if (arr[idx] == 0) {
numIcons++;
arr[idx] = 1;
update(segmentTree, idx, 1);
} else {
numIcons--;
arr[idx] = 0;
update(segmentTree, idx, 0);
new PriorityQueue<>();
}
ans[i] = numIcons - sumRange(segmentTree, 0, numIcons - 1);
}
return ans;
}
private static int getIndex(int n, int[] rci) {
return (rci[1] - 1) * n + rci[0] - 1;
}
private static int[] buildTree(int[] nums) {
int n = nums.length;
int[] tree = new int[n << 1];
for (int i = n, j = 0; i < 2 * n; i++, j++)
tree[i] = nums[j];
for (int i = n - 1; i > 0; --i)
tree[i] = tree[i * 2] + tree[i * 2 + 1];
return tree;
}
private static void update(int[] tree, int pos, int val) {
int n = tree.length >> 1;
pos += n;
tree[pos] = val;
while (pos > 0) {
int left = pos;
int right = pos;
if (pos % 2 == 0) {
right = pos + 1;
} else {
left = pos - 1;
}
// parent is updated after child is updated
tree[pos / 2] = tree[left] + tree[right];
pos /= 2;
}
}
public static int sumRange(int[] tree, int l, int r) {
int n = tree.length >> 1;
// get leaf with value 'l'
l += n;
// get leaf with value 'r'
r += n;
int sum = 0;
while (l <= r) {
if ((l % 2) == 1) {
sum += tree[l];
l++;
}
if ((r % 2) == 0) {
sum += tree[r];
r--;
}
l /= 2;
r /= 2;
}
return sum;
}
public static void main(String[] args) {
FastScanner in = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int t = 1; // Scanner has functions to read ints, longs, strings, chars, etc.
//in.nextLine();
for (int tt = 1; tt <= t; ++tt) {
int n = in.nextInt(), m = in.nextInt(), q = in.nextInt();
char[][] desktop = new char[n][m];
int[][] rc = new int[q][2];
for (int i = 0; i < n; i++) {
desktop[i] = in.next().toCharArray();
}
for (int i = 0; i < q; i++) {
rc[i] = in.readArray(2);
}
for (int an : testCase(n, m, q, desktop, rc)) {
out.println(an);
}
}
out.close();
}
private static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
boolean hasNext() {
return st.hasMoreTokens();
}
char[] readCharArray(int n) {
char[] arr = new char[n];
try {
br.read(arr);
br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return arr;
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
long[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
private static void sort(int[] arr) {
int temp, idx;
for (int i = arr.length - 1; i > 0; i--) {
idx = rng.nextInt(i + 1);
temp = arr[i];
arr[i] = arr[idx];
arr[idx] = temp;
}
Arrays.sort(arr);
}
private static void sort(long[] arr) {
long temp;
int idx;
for (int i = arr.length - 1; i > 0; i--) {
idx = rng.nextInt(i + 1);
temp = arr[i];
arr[i] = arr[idx];
arr[idx] = temp;
}
Arrays.sort(arr);
}
private static <T> void sort(T[] arr) {
T temp;
int idx;
for (int i = arr.length - 1; i > 0; i--) {
idx = rng.nextInt(i + 1);
temp = arr[i];
arr[i] = arr[idx];
arr[idx] = temp;
}
Arrays.sort(arr);
}
private static <T> void sort(T[] arr, Comparator<? super T> cmp) {
T temp;
int idx;
for (int i = arr.length - 1; i > 0; i--) {
idx = rng.nextInt(i + 1);
temp = arr[i];
arr[i] = arr[idx];
arr[idx] = temp;
}
Arrays.sort(arr, cmp);
}
private static <T extends Comparable<? super T>> void sort(List<T> list) {
T temp;
int idx;
for (int i = list.size() - 1; i > 0; i--) {
idx = rng.nextInt(i + 1);
temp = list.get(i);
list.set(i, list.get(idx));
list.set(idx, temp);
}
Collections.sort(list);
}
private static <T> void sort(List<T> list, Comparator<? super T> cmp) {
T temp;
int idx;
for (int i = list.size() - 1; i > 0; i--) {
idx = rng.nextInt(i + 1);
temp = list.get(i);
list.set(i, list.get(idx));
list.set(idx, temp);
}
Collections.sort(list, cmp);
}
static class DSU {
int[] parent, rank;
public DSU(int n) {
parent = new int[n];
rank = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
public int find(int i) {
if (parent[i] == i) {
return i;
} else {
int res = find(parent[i]);
parent[i] = res;
return res;
}
}
public boolean isSameSet(int i, int j) {
return find(i) == find(j);
}
public void union(int i, int j) {
int iParent = find(i), jParent = find(j);
if (iParent != jParent) {
if (rank[iParent] > rank[jParent]) {
parent[jParent] = iParent;
} else {
parent[iParent] = jParent;
if (rank[iParent] == rank[jParent]) {
rank[jParent]++;
}
}
}
}
}
}
| Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 11 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output | |
PASSED | 374c43a173889fd6673c783250c1338d | train_107.jsonl | 1651502100 | Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop. | 256 megabytes | import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Vector;
public class JavaTest {
private static final PrintWriter out = new PrintWriter(System.out);
private static Scanner sc;
public static void main(String[] args) throws Exception {
InputStream is = JavaTest.class.getResourceAsStream("in.txt");
boolean testMode = is != null;
sc = new Scanner(testMode ? is : System.in);
long start = System.currentTimeMillis();
main();
if (testMode) {
out.println();
out.print(System.currentTimeMillis() - start + " ms");
}
out.close();
}
private static void main() throws Exception {
int n = sc.nextInt();
int m = sc.nextInt();
int q = sc.nextInt();
Vector<String> tmp = new Vector<>(n);
StringBuilder s = new StringBuilder();
int sum = 0;
for (int i = 0; i < n; i++) {
String st = sc.next();
tmp.add(i, st);
sum += count(st, '*');
}
for (int j = 0; j < m; j++) {
for (int i = 0; i < n; i++) {
s.append(tmp.get(i).charAt(j));
}
}
int res = count(s.substring(0, sum), '.');
int pos = sum;
for (int i = 0; i < q; i++) {
int x, y;
x = sc.nextInt();
y = sc.nextInt();
x--;
y--;
int p = y * n + x;
if (p < pos) {
if (s.charAt(p) == '.') {
--res;
} else {
++res;
}
}
s.setCharAt(p, s.charAt(p) == '.' ? '*' : '.');
if(s.charAt(p) == '*') {
if(s.charAt(pos) == '.') {
res++;
}
pos++;
} else {
if(s.charAt(pos - 1) == '.') {
--res;
}
pos--;
}
System.out.println(res);
}
}
private static int count(String st, char c) {
int cnt = 0;
for (int i = 0; i < st.length(); i++) {
if (st.charAt(i) == c) {
cnt++;
}
}
return cnt;
}
} | Java | ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"] | 3 seconds | ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"] | null | Java 11 | standard input | [
"data structures",
"greedy",
"implementation"
] | 9afb205f542c0d8ba4f7fa03faa617ae | The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell). | 1,800 | Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.