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
f46ceae166efec70b8fd25ffdba6e810
train_004.jsonl
1557930900
In some social network, there are $$$n$$$ users communicating with each other in $$$m$$$ groups of friends. Let's analyze the process of distributing some news between users.Initially, some user $$$x$$$ receives the news from some source. Then he or she sends the news to his or her friends (two users are friends if there is at least one group such that both of them belong to this group). Friends continue sending the news to their friends, and so on. The process ends when there is no pair of friends such that one of them knows the news, and another one doesn't know.For each user $$$x$$$ you have to determine what is the number of users that will know the news if initially only user $$$x$$$ starts distributing it.
256 megabytes
import java.io.*; import java.util.InputMismatchException; /** * Built using CHelper plug-in * Actual solution is at the top * * @author el-Bishoy */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); C1167 solver = new C1167(); solver.solve(1, in, out); out.close(); } static class C1167 { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(), m = in.nextInt(); UnionFind uf = new UnionFind(n); while (m-- > 0) { int k = in.nextInt(); if (k == 0) continue; int u = in.nextInt() - 1; for (int i = 1; i < k; i++) { uf.union(u, in.nextInt() - 1); } } StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { sb.append(uf.sizes[uf.find(i)]).append(" "); } out.println(sb); } class UnionFind { int N; int numNodes; int sizes[]; int ids[]; public UnionFind(int numNodes) { N = numNodes; this.numNodes = numNodes; ids = new int[numNodes]; sizes = new int[numNodes]; for (int i = 0; i < numNodes; i++) { ids[i] = i; sizes[i] = 1; } } public int find(int p) { int root = p; while (root != ids[root]) root = ids[root]; while (p != root) { int newp = ids[p]; ids[p] = root; p = newp; } return root; } void union(int q, int v) { int qRoot = find(q); int vRoot = find(v); if (qRoot == vRoot) return; if (sizes[qRoot] > sizes[vRoot]) { ids[vRoot] = qRoot; sizes[qRoot] += sizes[vRoot]; } else { ids[qRoot] = vRoot; sizes[vRoot] += sizes[qRoot]; } N--; } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } }
Java
["7 5\n3 2 5 4\n0\n2 1 2\n1 1\n2 6 7"]
2 seconds
["4 4 1 4 4 2 2"]
null
Java 8
standard input
[ "dsu", "dfs and similar", "graphs" ]
a7e75ff150d300b2a8494dca076a3075
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 5 \cdot 10^5$$$) β€” the number of users and the number of groups of friends, respectively. Then $$$m$$$ lines follow, each describing a group of friends. The $$$i$$$-th line begins with integer $$$k_i$$$ ($$$0 \le k_i \le n$$$) β€” the number of users in the $$$i$$$-th group. Then $$$k_i$$$ distinct integers follow, denoting the users belonging to the $$$i$$$-th group. It is guaranteed that $$$\sum \limits_{i = 1}^{m} k_i \le 5 \cdot 10^5$$$.
1,400
Print $$$n$$$ integers. The $$$i$$$-th integer should be equal to the number of users that will know the news if user $$$i$$$ starts distributing it.
standard output
PASSED
1293d658e6b3bd020701b314842a79ca
train_004.jsonl
1557930900
In some social network, there are $$$n$$$ users communicating with each other in $$$m$$$ groups of friends. Let's analyze the process of distributing some news between users.Initially, some user $$$x$$$ receives the news from some source. Then he or she sends the news to his or her friends (two users are friends if there is at least one group such that both of them belong to this group). Friends continue sending the news to their friends, and so on. The process ends when there is no pair of friends such that one of them knows the news, and another one doesn't know.For each user $$$x$$$ you have to determine what is the number of users that will know the news if initially only user $$$x$$$ starts distributing it.
256 megabytes
import java.io.*; import java.util.InputMismatchException; /** * Built using CHelper plug-in * Actual solution is at the top * * @author el-Bishoy */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); C1167 solver = new C1167(); solver.solve(1, in, out); out.close(); } static class C1167 { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(), m = in.nextInt(); UnionFind uf = new UnionFind(n); while (m-- > 0) { int k = in.nextInt(); if (k == 0) continue; int u = in.nextInt() - 1; for (int i = 1; i < k; i++) { uf.union(u, in.nextInt() - 1); } } StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { sb.append(uf.sizes[uf.find(i)]).append(" "); } out.println(sb); } class UnionFind { int N; int numNodes; int sizes[]; int ids[]; public UnionFind(int numNodes) { N = numNodes; this.numNodes = numNodes; ids = new int[numNodes]; sizes = new int[numNodes]; for (int i = 0; i < numNodes; i++) { ids[i] = i; sizes[i] = 1; } } int find(int q) { while (q != ids[q]) { ids[q] = ids[ids[q]]; q = ids[q]; } return q; } void union(int q, int v) { int qRoot = find(q); int vRoot = find(v); if (qRoot == vRoot) return; if (sizes[qRoot] > sizes[vRoot]) { ids[vRoot] = qRoot; sizes[qRoot] += sizes[vRoot]; } else { ids[qRoot] = vRoot; sizes[vRoot] += sizes[qRoot]; } N--; } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } }
Java
["7 5\n3 2 5 4\n0\n2 1 2\n1 1\n2 6 7"]
2 seconds
["4 4 1 4 4 2 2"]
null
Java 8
standard input
[ "dsu", "dfs and similar", "graphs" ]
a7e75ff150d300b2a8494dca076a3075
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 5 \cdot 10^5$$$) β€” the number of users and the number of groups of friends, respectively. Then $$$m$$$ lines follow, each describing a group of friends. The $$$i$$$-th line begins with integer $$$k_i$$$ ($$$0 \le k_i \le n$$$) β€” the number of users in the $$$i$$$-th group. Then $$$k_i$$$ distinct integers follow, denoting the users belonging to the $$$i$$$-th group. It is guaranteed that $$$\sum \limits_{i = 1}^{m} k_i \le 5 \cdot 10^5$$$.
1,400
Print $$$n$$$ integers. The $$$i$$$-th integer should be equal to the number of users that will know the news if user $$$i$$$ starts distributing it.
standard output
PASSED
22fad058feb8947a588f6a0590f75c8c
train_004.jsonl
1557930900
In some social network, there are $$$n$$$ users communicating with each other in $$$m$$$ groups of friends. Let's analyze the process of distributing some news between users.Initially, some user $$$x$$$ receives the news from some source. Then he or she sends the news to his or her friends (two users are friends if there is at least one group such that both of them belong to this group). Friends continue sending the news to their friends, and so on. The process ends when there is no pair of friends such that one of them knows the news, and another one doesn't know.For each user $$$x$$$ you have to determine what is the number of users that will know the news if initially only user $$$x$$$ starts distributing it.
256 megabytes
import java.io.*; import java.util.InputMismatchException; /** * Built using CHelper plug-in * Actual solution is at the top * * @author el-Bishoy */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); C1167 solver = new C1167(); solver.solve(1, in, out); out.close(); } static class C1167 { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(), m = in.nextInt(); UnionFind uf = new UnionFind(n); while (m-- > 0) { int k = in.nextInt(); if (k == 0) continue; int u = in.nextInt() - 1; for (int i = 1; i < k; i++) { uf.union(u, in.nextInt() - 1); } } StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { sb.append(uf.sizes[uf.find(i)]).append(" "); } out.println(sb); } class UnionFind { int N; int numNodes; int sizes[]; int ids[]; public UnionFind(int numNodes) { N = numNodes; this.numNodes = numNodes; ids = new int[numNodes]; sizes = new int[numNodes]; for (int i = 0; i < numNodes; i++) { ids[i] = i; sizes[i] = 1; } } int find(int q) { while (q != ids[q]) { // ids[q] = ids[ids[q]]; q = ids[q]; } return q; } void union(int q, int v) { int qRoot = find(q); int vRoot = find(v); if (qRoot == vRoot) return; if (sizes[qRoot] > sizes[vRoot]) { ids[vRoot] = qRoot; sizes[qRoot] += sizes[vRoot]; } else { ids[qRoot] = vRoot; sizes[vRoot] += sizes[qRoot]; } N--; } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } }
Java
["7 5\n3 2 5 4\n0\n2 1 2\n1 1\n2 6 7"]
2 seconds
["4 4 1 4 4 2 2"]
null
Java 8
standard input
[ "dsu", "dfs and similar", "graphs" ]
a7e75ff150d300b2a8494dca076a3075
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 5 \cdot 10^5$$$) β€” the number of users and the number of groups of friends, respectively. Then $$$m$$$ lines follow, each describing a group of friends. The $$$i$$$-th line begins with integer $$$k_i$$$ ($$$0 \le k_i \le n$$$) β€” the number of users in the $$$i$$$-th group. Then $$$k_i$$$ distinct integers follow, denoting the users belonging to the $$$i$$$-th group. It is guaranteed that $$$\sum \limits_{i = 1}^{m} k_i \le 5 \cdot 10^5$$$.
1,400
Print $$$n$$$ integers. The $$$i$$$-th integer should be equal to the number of users that will know the news if user $$$i$$$ starts distributing it.
standard output
PASSED
8b0456df5c1e180d7806ba9141f27dc9
train_004.jsonl
1557930900
In some social network, there are $$$n$$$ users communicating with each other in $$$m$$$ groups of friends. Let's analyze the process of distributing some news between users.Initially, some user $$$x$$$ receives the news from some source. Then he or she sends the news to his or her friends (two users are friends if there is at least one group such that both of them belong to this group). Friends continue sending the news to their friends, and so on. The process ends when there is no pair of friends such that one of them knows the news, and another one doesn't know.For each user $$$x$$$ you have to determine what is the number of users that will know the news if initially only user $$$x$$$ starts distributing it.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class NewsDistribution { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] input = br.readLine().split(" "); int N = Integer.valueOf(input[0]); p = new int[N+1]; rank = new int[N+1]; amount = new int[N+1]; for(int i = 1; i < N+1; i++){ p[i] = i; amount[i] = 1; } int M = Integer.valueOf(input[1]); for(int i = 0; i < M; i++){ input = br.readLine().split(" "); int k = Integer.valueOf(input[0]); if(k > 0) { int a = Integer.valueOf(input[1]); for (int j = 2; j < k+1; j++) { union(a, Integer.valueOf(input[j])); } } } StringBuilder out = new StringBuilder(); for(int i = 1; i < N+1; i++){ out.append(amount[findSet(i)]); out.append(" "); } System.out.println(out.toString()); } static int[] p; static int[] rank; static int[] amount; static int findSet(int i){ if(p[i] == i){ return i; } else{ p[i] = findSet(p[i]); return p[i]; } } static void union(int a, int b){ int A = findSet(a); int B = findSet(b); if(A != B){ if(rank[A] > rank[B]){ p[B] = A; p[A] = A; amount[A] += amount[B]; }else{ p[A] = B; p[B] = B; amount[B] += amount[A]; if(rank[A] == rank[B]){ rank[B]++; } } } } }
Java
["7 5\n3 2 5 4\n0\n2 1 2\n1 1\n2 6 7"]
2 seconds
["4 4 1 4 4 2 2"]
null
Java 8
standard input
[ "dsu", "dfs and similar", "graphs" ]
a7e75ff150d300b2a8494dca076a3075
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 5 \cdot 10^5$$$) β€” the number of users and the number of groups of friends, respectively. Then $$$m$$$ lines follow, each describing a group of friends. The $$$i$$$-th line begins with integer $$$k_i$$$ ($$$0 \le k_i \le n$$$) β€” the number of users in the $$$i$$$-th group. Then $$$k_i$$$ distinct integers follow, denoting the users belonging to the $$$i$$$-th group. It is guaranteed that $$$\sum \limits_{i = 1}^{m} k_i \le 5 \cdot 10^5$$$.
1,400
Print $$$n$$$ integers. The $$$i$$$-th integer should be equal to the number of users that will know the news if user $$$i$$$ starts distributing it.
standard output
PASSED
67137c14cfa992b497e544dfae1ae74e
train_004.jsonl
1557930900
In some social network, there are $$$n$$$ users communicating with each other in $$$m$$$ groups of friends. Let's analyze the process of distributing some news between users.Initially, some user $$$x$$$ receives the news from some source. Then he or she sends the news to his or her friends (two users are friends if there is at least one group such that both of them belong to this group). Friends continue sending the news to their friends, and so on. The process ends when there is no pair of friends such that one of them knows the news, and another one doesn't know.For each user $$$x$$$ you have to determine what is the number of users that will know the news if initially only user $$$x$$$ starts distributing it.
256 megabytes
import java.io.*; import java.util.*; /******************************\ * The solution is at the top * * * * Created by : azhar556 * \******************************/ public class Solution { static int thisRootGr (int a) { return rootGr[a] == a ? a : (rootGr[a] = thisRootGr(rootGr[a])); } static int[] rootGr; static void solve() { int n = ni(); int m = ni(); rootGr = new int[n + 1]; int[] valInt = new int[n + 1]; Arrays.fill(valInt, 1); for (int i = 0; i <= n; i++) { rootGr[i] = i; } while (m-- > 0) { int numGr = ni(); int thisHeadGr = -1; for (int j = 0; j < numGr; j++) { int masukInt = ni(); if (j == 0) { thisHeadGr = masukInt; } int rootThisHeadGr = thisRootGr(thisHeadGr); int rootMasukInt = thisRootGr(masukInt); if (rootMasukInt == rootThisHeadGr) continue; rootGr[rootMasukInt] = rootThisHeadGr; valInt[rootThisHeadGr] += valInt[rootMasukInt]; } } for (int i = 1; i <= n; i++) { out.print(valInt[thisRootGr(i)] + " "); } /*int[] valHead = new int[n + 1]; int[] finalHead = new int[n + 1]; for (int i = 1; i <= n; i++) { int thisFinalHead = thisRootGr(i); valHead[thisFinalHead]++; finalHead[i] = thisFinalHead; } for (int i = 1; i <= n; i++) { out.print(valHead[finalHead[i]] + " "); }*/ } public static void main(String[] args) { long time = System.currentTimeMillis(); int t;// = ni(); t = 1; while (t-- > 0) solve(); err.println("Time elapsed : " + (System.currentTimeMillis() - time) / 1000F + " s."); err.close(); out.close(); } static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); static PrintWriter err = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.err))); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer token; static String ns() { while (token == null || !token.hasMoreTokens()) { try { token = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return token.nextToken(); } static char nc() { return Character.valueOf(ns().charAt(0)); } static int ni() { return Integer.parseInt(ns()); } static double nd() { return Double.parseDouble(ns()); } static long nl() { return Long.parseLong(ns()); } } // Collections Arrays Math // Vector HashSet TreeSet HashMap TreeMap ArrayDeque
Java
["7 5\n3 2 5 4\n0\n2 1 2\n1 1\n2 6 7"]
2 seconds
["4 4 1 4 4 2 2"]
null
Java 8
standard input
[ "dsu", "dfs and similar", "graphs" ]
a7e75ff150d300b2a8494dca076a3075
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 5 \cdot 10^5$$$) β€” the number of users and the number of groups of friends, respectively. Then $$$m$$$ lines follow, each describing a group of friends. The $$$i$$$-th line begins with integer $$$k_i$$$ ($$$0 \le k_i \le n$$$) β€” the number of users in the $$$i$$$-th group. Then $$$k_i$$$ distinct integers follow, denoting the users belonging to the $$$i$$$-th group. It is guaranteed that $$$\sum \limits_{i = 1}^{m} k_i \le 5 \cdot 10^5$$$.
1,400
Print $$$n$$$ integers. The $$$i$$$-th integer should be equal to the number of users that will know the news if user $$$i$$$ starts distributing it.
standard output
PASSED
49d5233dc2311c145a66766242e4e426
train_004.jsonl
1557930900
In some social network, there are $$$n$$$ users communicating with each other in $$$m$$$ groups of friends. Let's analyze the process of distributing some news between users.Initially, some user $$$x$$$ receives the news from some source. Then he or she sends the news to his or her friends (two users are friends if there is at least one group such that both of them belong to this group). Friends continue sending the news to their friends, and so on. The process ends when there is no pair of friends such that one of them knows the news, and another one doesn't know.For each user $$$x$$$ you have to determine what is the number of users that will know the news if initially only user $$$x$$$ starts distributing it.
256 megabytes
import java.io.*; import java.util.*; /******************************\ * The solution is at the top * * * * Created by : azhar556 * \******************************/ public class Solution { static int thisRootGr (int a) { return rootGr[a] == a ? a : (rootGr[a] = thisRootGr(rootGr[a])); } static int[] rootGr; static void solve() { int n = ni(); int m = ni(); rootGr = new int[n + 1]; //int[] valInt = new int[n + 1]; //Arrays.fill(valInt, 1); for (int ii = 0; ii <= n; ii++) { rootGr[ii] = ii; } while (m-- > 0) { int numGr = ni(); int thisHeadGr = -1; for (int j = 0; j < numGr; j++) { int masukInt = ni(); if (j == 0) { thisHeadGr = masukInt; } int rootThisHeadGr = thisRootGr(thisHeadGr); int rootMasukInt = thisRootGr(masukInt); //if (rootMasukInt == rootThisHeadGr) continue; rootGr[rootMasukInt] = rootThisHeadGr; //valInt[rootThisHeadGr] += valInt[rootMasukInt]; } } /*for (int i = 1; i <= n; i++) { out.print(valInt[thisRootGr(i)] + " "); }*/ int[] valHead = new int[n + 1]; int[] finalHead = new int[n + 1]; for (int i = 1; i <= n; i++) { int thisFinalHead = thisRootGr(i); valHead[thisFinalHead]++; finalHead[i] = thisFinalHead; } for (int i = 1; i <= n; i++) { out.print(valHead[finalHead[i]] + " "); } } public static void main(String[] args) { long time = System.currentTimeMillis(); int t;// = ni(); t = 1; while (t-- > 0) solve(); err.println("Time elapsed : " + (System.currentTimeMillis() - time) / 1000F + " s."); err.close(); out.close(); } static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); static PrintWriter err = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.err))); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer token; static String ns() { while (token == null || !token.hasMoreTokens()) { try { token = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return token.nextToken(); } static char nc() { return Character.valueOf(ns().charAt(0)); } static int ni() { return Integer.parseInt(ns()); } static double nd() { return Double.parseDouble(ns()); } static long nl() { return Long.parseLong(ns()); } } // Collections Arrays Math // Vector HashSet TreeSet HashMap TreeMap ArrayDeque
Java
["7 5\n3 2 5 4\n0\n2 1 2\n1 1\n2 6 7"]
2 seconds
["4 4 1 4 4 2 2"]
null
Java 8
standard input
[ "dsu", "dfs and similar", "graphs" ]
a7e75ff150d300b2a8494dca076a3075
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 5 \cdot 10^5$$$) β€” the number of users and the number of groups of friends, respectively. Then $$$m$$$ lines follow, each describing a group of friends. The $$$i$$$-th line begins with integer $$$k_i$$$ ($$$0 \le k_i \le n$$$) β€” the number of users in the $$$i$$$-th group. Then $$$k_i$$$ distinct integers follow, denoting the users belonging to the $$$i$$$-th group. It is guaranteed that $$$\sum \limits_{i = 1}^{m} k_i \le 5 \cdot 10^5$$$.
1,400
Print $$$n$$$ integers. The $$$i$$$-th integer should be equal to the number of users that will know the news if user $$$i$$$ starts distributing it.
standard output
PASSED
7633fb632a4556ae6902c7aefa81ad47
train_004.jsonl
1557930900
In some social network, there are $$$n$$$ users communicating with each other in $$$m$$$ groups of friends. Let's analyze the process of distributing some news between users.Initially, some user $$$x$$$ receives the news from some source. Then he or she sends the news to his or her friends (two users are friends if there is at least one group such that both of them belong to this group). Friends continue sending the news to their friends, and so on. The process ends when there is no pair of friends such that one of them knows the news, and another one doesn't know.For each user $$$x$$$ you have to determine what is the number of users that will know the news if initially only user $$$x$$$ starts distributing it.
256 megabytes
import java.io.*; import java.util.*; /******************************\ * The solution is at the top * * * * Created by : azhar556 * \******************************/ public class Solution { static int thisRootGr (int a) { return rootGr[a] == a ? a : (rootGr[a] = thisRootGr(rootGr[a])); } static int[] rootGr; static void solve() { int n = ni(); int m = ni(); rootGr = new int[n + 1]; //int[] valInt = new int[n + 1]; //Arrays.fill(valInt, 1); for (int i = 0; i <= n; i++) { rootGr[i] = i; } while (m-- > 0) { int numGr = ni(); int thisHeadGr = -1; for (int j = 0; j < numGr; j++) { int masukInt = ni(); if (j == 0) { thisHeadGr = masukInt; } int rootThisHeadGr = thisRootGr(thisHeadGr); int rootMasukInt = thisRootGr(masukInt); //if (rootMasukInt == rootThisHeadGr) continue; rootGr[rootMasukInt] = rootThisHeadGr; //valInt[rootThisHeadGr] += valInt[rootMasukInt]; } } /*for (int i = 1; i <= n; i++) { out.print(valInt[thisRootGr(i)] + " "); }*/ int[] valHead = new int[n + 1]; int[] finalHead = new int[n + 1]; for (int i = 1; i <= n; i++) { int thisFinalHead = thisRootGr(i); valHead[thisFinalHead]++; finalHead[i] = thisFinalHead; } for (int i = 1; i <= n; i++) { out.print(valHead[finalHead[i]] + " "); } } public static void main(String[] args) { long time = System.currentTimeMillis(); int t;// = ni(); t = 1; while (t-- > 0) solve(); err.println("Time elapsed : " + (System.currentTimeMillis() - time) / 1000F + " s."); err.close(); out.close(); } static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); static PrintWriter err = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.err))); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer token; static String ns() { while (token == null || !token.hasMoreTokens()) { try { token = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return token.nextToken(); } static char nc() { return Character.valueOf(ns().charAt(0)); } static int ni() { return Integer.parseInt(ns()); } static double nd() { return Double.parseDouble(ns()); } static long nl() { return Long.parseLong(ns()); } } // Collections Arrays Math // Vector HashSet TreeSet HashMap TreeMap ArrayDeque
Java
["7 5\n3 2 5 4\n0\n2 1 2\n1 1\n2 6 7"]
2 seconds
["4 4 1 4 4 2 2"]
null
Java 8
standard input
[ "dsu", "dfs and similar", "graphs" ]
a7e75ff150d300b2a8494dca076a3075
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 5 \cdot 10^5$$$) β€” the number of users and the number of groups of friends, respectively. Then $$$m$$$ lines follow, each describing a group of friends. The $$$i$$$-th line begins with integer $$$k_i$$$ ($$$0 \le k_i \le n$$$) β€” the number of users in the $$$i$$$-th group. Then $$$k_i$$$ distinct integers follow, denoting the users belonging to the $$$i$$$-th group. It is guaranteed that $$$\sum \limits_{i = 1}^{m} k_i \le 5 \cdot 10^5$$$.
1,400
Print $$$n$$$ integers. The $$$i$$$-th integer should be equal to the number of users that will know the news if user $$$i$$$ starts distributing it.
standard output
PASSED
ef24f51fa15edf3f677bac9db8d442f2
train_004.jsonl
1557930900
In some social network, there are $$$n$$$ users communicating with each other in $$$m$$$ groups of friends. Let's analyze the process of distributing some news between users.Initially, some user $$$x$$$ receives the news from some source. Then he or she sends the news to his or her friends (two users are friends if there is at least one group such that both of them belong to this group). Friends continue sending the news to their friends, and so on. The process ends when there is no pair of friends such that one of them knows the news, and another one doesn't know.For each user $$$x$$$ you have to determine what is the number of users that will know the news if initially only user $$$x$$$ starts distributing it.
256 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; public class NewsDistribution { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } 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; din.close(); } } static int rk[]; static int parent[]; static int parent(int node) { return (node == parent[node]) ? node : (parent[node] = parent(parent[node])); } static void swap(int a, int b) { int temp = a; a = b; b = temp; } static void unite(int a, int b) { a = parent(a); b = parent(b); if (a == b) return; if (rk[a] < rk[b]) swap(a, b); parent[b] = a; rk[a] += rk[b]; } public static void main(String[] args) throws IOException { Reader sc = new Reader(); StringBuilder ans = new StringBuilder(); int n = sc.nextInt(); int m = sc.nextInt(); parent = new int[n]; rk = new int[n]; for (int i = 0; i < n; i++) { rk[i] = 1; parent[i] = i; } while (m-- > 0) { int k = sc.nextInt(); int last = -1; while (k-- > 0) { int temp = sc.nextInt() - 1; if (last != -1) { unite(temp, last); } last = temp; } } sc.close(); for (int i = 0; i < n; i++) { ans.append(rk[parent(i)] + " "); } System.out.print(ans); } }
Java
["7 5\n3 2 5 4\n0\n2 1 2\n1 1\n2 6 7"]
2 seconds
["4 4 1 4 4 2 2"]
null
Java 8
standard input
[ "dsu", "dfs and similar", "graphs" ]
a7e75ff150d300b2a8494dca076a3075
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 5 \cdot 10^5$$$) β€” the number of users and the number of groups of friends, respectively. Then $$$m$$$ lines follow, each describing a group of friends. The $$$i$$$-th line begins with integer $$$k_i$$$ ($$$0 \le k_i \le n$$$) β€” the number of users in the $$$i$$$-th group. Then $$$k_i$$$ distinct integers follow, denoting the users belonging to the $$$i$$$-th group. It is guaranteed that $$$\sum \limits_{i = 1}^{m} k_i \le 5 \cdot 10^5$$$.
1,400
Print $$$n$$$ integers. The $$$i$$$-th integer should be equal to the number of users that will know the news if user $$$i$$$ starts distributing it.
standard output
PASSED
f3c9580815d024bad98cdef2d5ef395f
train_004.jsonl
1557930900
In some social network, there are $$$n$$$ users communicating with each other in $$$m$$$ groups of friends. Let's analyze the process of distributing some news between users.Initially, some user $$$x$$$ receives the news from some source. Then he or she sends the news to his or her friends (two users are friends if there is at least one group such that both of them belong to this group). Friends continue sending the news to their friends, and so on. The process ends when there is no pair of friends such that one of them knows the news, and another one doesn't know.For each user $$$x$$$ you have to determine what is the number of users that will know the news if initially only user $$$x$$$ starts distributing it.
256 megabytes
//package cfed65; import java.io.*; import java.util.*; public class C{ public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); // Start writing your solution here. ------------------------------------- int n=sc.nextInt(),m=sc.nextInt(); int[]parent=new int[n]; for(int i=0;i<n;i++) parent[i]=i; int[]size=new int[n]; for(int i=0;i<n;i++) size[i]=1; for(int i=0;i<m;i++) { int g=sc.nextInt(); int par=-1; HashSet<Integer>temp=new HashSet<Integer>(); for(int j=0;j<g;j++) { int x=sc.nextInt()-1; if(parent[x]!=x||par==-1) par=x; temp.add(x); } for(int j:temp) fillpar(j,par,parent,size); } for(int i=0;i<n;i++) out.print(size[finalpar(i,parent)]+" "); // Stop writing your solution here. ------------------------------------- out.close(); } private static void fillpar(int j,int par,int[]parent,int[]size) { par=finalpar(par,parent); if(finalpar(j,parent)!=par) { if(j!=parent[j]) fillpar(parent[j],par,parent,size); else { size[par]+=size[j]; } parent[j]=par; } } private static int finalpar(int i,int[]parent) { int iinit=i; while(parent[i]!=i) i=parent[i]; parent[iinit]=i; return i; } //-----------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
["7 5\n3 2 5 4\n0\n2 1 2\n1 1\n2 6 7"]
2 seconds
["4 4 1 4 4 2 2"]
null
Java 8
standard input
[ "dsu", "dfs and similar", "graphs" ]
a7e75ff150d300b2a8494dca076a3075
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 5 \cdot 10^5$$$) β€” the number of users and the number of groups of friends, respectively. Then $$$m$$$ lines follow, each describing a group of friends. The $$$i$$$-th line begins with integer $$$k_i$$$ ($$$0 \le k_i \le n$$$) β€” the number of users in the $$$i$$$-th group. Then $$$k_i$$$ distinct integers follow, denoting the users belonging to the $$$i$$$-th group. It is guaranteed that $$$\sum \limits_{i = 1}^{m} k_i \le 5 \cdot 10^5$$$.
1,400
Print $$$n$$$ integers. The $$$i$$$-th integer should be equal to the number of users that will know the news if user $$$i$$$ starts distributing it.
standard output
PASSED
13e15068ab0d4bea310329ef707f1ff2
train_004.jsonl
1557930900
In some social network, there are $$$n$$$ users communicating with each other in $$$m$$$ groups of friends. Let's analyze the process of distributing some news between users.Initially, some user $$$x$$$ receives the news from some source. Then he or she sends the news to his or her friends (two users are friends if there is at least one group such that both of them belong to this group). Friends continue sending the news to their friends, and so on. The process ends when there is no pair of friends such that one of them knows the news, and another one doesn't know.For each user $$$x$$$ you have to determine what is the number of users that will know the news if initially only user $$$x$$$ starts distributing it.
256 megabytes
import javax.print.attribute.HashAttributeSet; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; import java.util.stream.IntStream; public class GTGSTG { InputStream is; PrintWriter out; String INPUT = ""; long mod = (long)(1e9 + 7), inf = (long)(3e18); void solve(){ int n=ni(); int m=ni(); Dj d=new Dj(); for(int i=1;i<=n;i++){ d.makeSet(i); } while(m-->0){ int x=ni(); if(x==0) continue; int a=ni(); for(int i=1;i<x;i++){ d.union(a,ni()); } } for(int i=1;i<=n;i++){ out.print(d.size(i)+" "); } }class Dj { private HashMap<Integer,N> rootNs; public Dj(){ this.rootNs=new HashMap<Integer,N>(); } public int find(int n){ return find(rootNs.get(n)); } private int find(N n){ N currentN=n; while(currentN.getParent()!=null){ currentN=currentN.getParent(); } N rootN=currentN; currentN=n; while(currentN!=rootN){ N temp=currentN.getParent(); currentN.setParent(rootN); currentN=temp; } return rootN.getId(); } public void union(int n1,int n2){ if(!rootNs.containsKey(n1)) makeSet(n1); if(!rootNs.containsKey(n2)) makeSet(n2); union(rootNs.get(n1),rootNs.get(n2)); } public int size(int n){ if(!rootNs.containsKey(n)) makeSet(n); N i1=rootNs.get(find(n)); return i1.getSize(); } private void union(N n1,N n2){ int i1=find(n1); int i2=find(n2); if(i1==i2) return; N root1=rootNs.get(i1); N root2=rootNs.get(i2); if(root1.getRank()<root2.getRank()){ root1.setParent(root2); root2.setSize(root1.getSize()+root2.getSize()); } else if(root1.getRank()>root2.getRank()){ root2.setParent(root1); root1.setSize(root1.getSize()+root2.getSize()); } else{ root2.setParent(root1); root1.setRank(root1.getRank()+1); root1.setSize(root1.getSize()+root2.getSize()); } } private void makeSet(int v){ N n=new N(0,v,null); this.rootNs.put(v,n); } } class N { private int id; private int rank; private N parent; private int size; public N(int rank,int id,N parent){ this.id=id; this.rank=rank; this.parent=parent; this.size=1; } public int getSize(){ return size; } public void setSize(int size){ this.size=size; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getRank() { return rank; } public void setRank(int rank) { this.rank = rank; } public N getParent() { return parent; } public void setParent(N parent) { this.parent = parent; } } void run() throws Exception{ is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms"); } private boolean isPrime(long n) { if(n <= 1) return false; if(n <= 3) return true; if(n%2 == 0 || n%3 == 0) return false; for(long i = 5; i * i <= n; i += 6) { if(n % i == 0 || n % (i + 2) == 0) return false; } return true; } int P[], S[], SZ, NP = 15485900; boolean isP[]; private int log2(int n){ if(n <= 0) throw new IllegalArgumentException(); return 31 - Integer.numberOfLeadingZeros(n); } private int sieve() { int i, j, n = NP; isP = new boolean[n]; S = new int[n]; for(i = 3; i < n; i += 2) { isP[i] = true; S[i-1] = 2; S[i] = i; } isP[2] = true; S[1] = 1; //(UD) for(i = 3; i * i <= n; i += 2) { if( !isP[i] ) continue; for(j = i * i; j < n; j += i) { isP[j] = false; if(S[j] == j) S[j] = i; } } P = new int[n]; P[0] = 2; j = 1; for(i = 3; i < n; i += 2) { if ( isP[i] ) P[j++] = i; } P = Arrays.copyOf(P, j); return j; } private long gcd(long a,long b){ while (a!=0 && b!=0) { if(a>b) a%=b; else b%=a; } return a+b; } private long mp(long b, long e, long mod) { b %= mod; long r = 1; while(e > 0) { if((e & 1) == 1) { r *= b; r %= mod; } b *= b; b %= mod; e >>= 1; } return r; } public static void main(String[] args) throws Exception { new GTGSTG().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!isSpaceChar(b)){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private String nsl() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!isSpaceChar(b) || b==' '){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private long[] nal(int n) { long[] a = new long[n+1]; for(int i = 1;i <= n;i++)a[i] = nl(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); } }
Java
["7 5\n3 2 5 4\n0\n2 1 2\n1 1\n2 6 7"]
2 seconds
["4 4 1 4 4 2 2"]
null
Java 8
standard input
[ "dsu", "dfs and similar", "graphs" ]
a7e75ff150d300b2a8494dca076a3075
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 5 \cdot 10^5$$$) β€” the number of users and the number of groups of friends, respectively. Then $$$m$$$ lines follow, each describing a group of friends. The $$$i$$$-th line begins with integer $$$k_i$$$ ($$$0 \le k_i \le n$$$) β€” the number of users in the $$$i$$$-th group. Then $$$k_i$$$ distinct integers follow, denoting the users belonging to the $$$i$$$-th group. It is guaranteed that $$$\sum \limits_{i = 1}^{m} k_i \le 5 \cdot 10^5$$$.
1,400
Print $$$n$$$ integers. The $$$i$$$-th integer should be equal to the number of users that will know the news if user $$$i$$$ starts distributing it.
standard output
PASSED
5a6b7e2b6fc9494c90ce29760a3d7106
train_004.jsonl
1429029300
Tavas is a cheerleader in the new sports competition named "Pashmaks". This competition consists of two part: swimming and then running. People will immediately start running R meters after they finished swimming exactly S meters. A winner is a such person that nobody else finishes running before him/her (there may be more than one winner).Before the match starts, Tavas knows that there are n competitors registered for the match. Also, he knows that i-th person's swimming speed is si meters per second and his/her running speed is ri meters per second. Unfortunately, he doesn't know the values of R and S, but he knows that they are real numbers greater than 0.As a cheerleader, Tavas wants to know who to cheer up. So, he wants to know all people that might win. We consider a competitor might win if and only if there are some values of R and S such that with these values, (s)he will be a winner.Tavas isn't really familiar with programming, so he asked you to help him.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class C536 { public static void main(String[] args) throws IOException { input.init(System.in); PrintWriter out = new PrintWriter(System.out); int n = input.nextInt(); Point[] data = new Point[n]; for(int i = 0; i<n; i++) data[i] = new Point(input.nextInt(), input.nextInt(), i); ArrayList<Integer> res = new ArrayList<Integer>(); Point[] p = hull(data); for(int i = 0; i<p.length; i++) { res.add(p[i].i); } Collections.sort(res); for(int i = 0; i<res.size(); i++) out.print(res.get(i)+1+" "); out.close(); } static Point[] hull(Point[] data) { Arrays.sort(data); int n = data.length; Point[] res = new Point[n]; int k = 0; long maxy = 0, maxx = 0; long[] max = new long[100001]; Point[] unique = new Point[n]; int u = 0; for(int i = 0; i<n; i++) { Point p = data[i]; //if(k >= 2) System.out.println(cross(p, res[k-1], res[k-2])); while(u >= 2 && cross(p, unique[u-1], unique[u-2]) > 0) { while(k > 0 && res[k-1].x == unique[u-1].x && res[k-1].y == unique[u-1].y) k--; u--; } if(data[i].x >= max[(int) data[i].y] && (data[i].y >= maxy || data[i].x >= maxx)) { maxx = Math.max(maxx, data[i].x); maxy = Math.max(maxy, data[i].y); max[(int)data[i].y] = data[i].x; if(u == 0 || (p.x != unique[u-1].x || p.y != unique[u-1].y)) unique[u++] = p; res[k++] = p; } if(u > 1 && unique[u-1].x == unique[u-2].x && unique[u-1].y != unique[u-2].y) { while(k > 0 && res[k-1].x == unique[u-1].x && res[k-1].y == unique[u-1].y) k--; u--; } else if(u > 1 && unique[u-1].y == unique[u-2].y && unique[u-1].x != unique[u-2].x) { while(k > 0 && res[k-1].x == unique[u-1].x && res[k-1].y == unique[u-1].y) k--; u--; } } //for(Point p : res) System.out.println(p.x.num+" "+p.x.denom+" "+p.y.num+" "+p.y.denom); return Arrays.copyOf(res, k); } static long cross(Point p, Point a, Point b) { return a.x * p.y * b.x * b.y + p.x * b.y * a.x * a.y - a.y * p.x * b.x * b.y - p.y * b.x * a.x * a.y + p.x * p.y * a.y * b.x - p.x * p.y * a.x * b.y; } static class Point implements Comparable<Point> { long x, y; int i; public Point(long xx, long yy, int ii) { x = xx; y = yy; i = ii; } public int compareTo(Point o) { int cx = -Long.compare(x, o.x); if(cx != 0) return cx; return -Long.compare(y, o.y); } } public static class input { static BufferedReader reader; static StringTokenizer tokenizer; static void init(InputStream input) { reader = new BufferedReader(new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } static String next() throws IOException { while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } } }
Java
["3\n1 3\n2 2\n3 1", "3\n1 2\n1 1\n2 1"]
1 second
["1 2 3", "1 3"]
null
Java 8
standard input
[ "geometry", "math" ]
e54f8aff8ede309bd591cb9fbd565d1f
The first line of input contains a single integer n (1 ≀ n ≀ 2 × 105). The next n lines contain the details of competitors. i-th line contains two integers si and ri (1 ≀ si, ri ≀ 104).
2,600
In the first and the only line of output, print a sequence of numbers of possible winners in increasing order.
standard output
PASSED
57ec8978251495f4aedc4fd1b5d59e84
train_004.jsonl
1429029300
Tavas is a cheerleader in the new sports competition named "Pashmaks". This competition consists of two part: swimming and then running. People will immediately start running R meters after they finished swimming exactly S meters. A winner is a such person that nobody else finishes running before him/her (there may be more than one winner).Before the match starts, Tavas knows that there are n competitors registered for the match. Also, he knows that i-th person's swimming speed is si meters per second and his/her running speed is ri meters per second. Unfortunately, he doesn't know the values of R and S, but he knows that they are real numbers greater than 0.As a cheerleader, Tavas wants to know who to cheer up. So, he wants to know all people that might win. We consider a competitor might win if and only if there are some values of R and S such that with these values, (s)he will be a winner.Tavas isn't really familiar with programming, so he asked you to help him.
256 megabytes
import java.io.BufferedWriter; import java.util.InputMismatchException; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import java.math.BigInteger; import java.util.Vector; import java.io.OutputStream; import java.util.Stack; import java.util.Collections; import java.io.PrintWriter; import java.io.Writer; import java.io.IOException; import java.util.Arrays; import java.io.InputStream; import java.util.Collection; import java.io.OutputStreamWriter; import java.util.Comparator; /** * Built using CHelper plug-in * Actual solution is at the top * @author Stanislav Pak */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { class Line { final List<Integer> ids; final double a, b; Line(List<Integer> ids, double a, double b) { this.ids = ids; this.a = a; this.b = b; } public boolean equals(Object o) { if (o instanceof Line) { Line l = (Line) o; return Math.abs(l.a - a) < GeometryUtils.epsilon && Math.abs(l.b - b) < GeometryUtils.epsilon; } else { return false; } } public double at(double x) { return a * x + b; } public boolean parallelTo(Line line) { return Math.abs(line.a - a) < GeometryUtils.epsilon; } public double intersectWith(Line line) { assert !parallelTo(line); return (line.b - b) / (a - line.a); } } public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); Line[] lines = new Line[n]; for (int i = 0; i < n; ++i) { double s = in.readInt(); double r = in.readInt(); lines[i] = new Line(new ArrayList<Integer>(), 10000 / s, 10000 / r); lines[i].ids.add(i); } Arrays.sort(lines, new Comparator<Line>() { public int compare(Line o1, Line o2) { if (Math.abs(o1.a - o2.a) > GeometryUtils.epsilon) { if (o1.a > o2.a) return -1; return 1; } if (o1.b + GeometryUtils.epsilon < o2.b) return 1; if (o1.b > o2.b + GeometryUtils.epsilon) return -1; return 0; } }); int m = 1; for (int i = 1; i < n; ++i) { if (lines[m - 1].equals(lines[i])) { lines[m - 1].ids.add(lines[i].ids.get(0)); continue; } lines[m++] = lines[i]; } lines = Arrays.copyOf(lines, m); Stack<Line> stack = new Stack<>(); for (Line line : lines) { while (!stack.isEmpty()) { if (stack.peek().parallelTo(line)) { stack.pop(); continue; } if (stack.peek().intersectWith(line) <= GeometryUtils.epsilon) { stack.pop(); continue; } if (stack.size() == 1) break; Line last = stack.pop(); double x = last.intersectWith(stack.peek()); if (line.at(x) + GeometryUtils.epsilon >= last.at(x)) { stack.add(last); break; } } stack.add(line); } List<Integer> ids = new ArrayList<>(); for (Line line : stack) { ids.addAll(line.ids); } Collections.sort(ids); for (int i = 0; i < ids.size(); ++i) { if (i > 0) out.print(" "); out.print(ids.get(i) + 1); } out.printLine(); } } class GeometryUtils { public static double epsilon = 1e-8; } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine() { writer.println(); } public void close() { writer.close(); } public void print(int i) { writer.print(i); } }
Java
["3\n1 3\n2 2\n3 1", "3\n1 2\n1 1\n2 1"]
1 second
["1 2 3", "1 3"]
null
Java 8
standard input
[ "geometry", "math" ]
e54f8aff8ede309bd591cb9fbd565d1f
The first line of input contains a single integer n (1 ≀ n ≀ 2 × 105). The next n lines contain the details of competitors. i-th line contains two integers si and ri (1 ≀ si, ri ≀ 104).
2,600
In the first and the only line of output, print a sequence of numbers of possible winners in increasing order.
standard output
PASSED
c2e256e789fd15d25e3bf0740ba8518e
train_004.jsonl
1429029300
Tavas is a cheerleader in the new sports competition named "Pashmaks". This competition consists of two part: swimming and then running. People will immediately start running R meters after they finished swimming exactly S meters. A winner is a such person that nobody else finishes running before him/her (there may be more than one winner).Before the match starts, Tavas knows that there are n competitors registered for the match. Also, he knows that i-th person's swimming speed is si meters per second and his/her running speed is ri meters per second. Unfortunately, he doesn't know the values of R and S, but he knows that they are real numbers greater than 0.As a cheerleader, Tavas wants to know who to cheer up. So, he wants to know all people that might win. We consider a competitor might win if and only if there are some values of R and S such that with these values, (s)he will be a winner.Tavas isn't really familiar with programming, so he asked you to help him.
256 megabytes
import java.io.*; import java.util.*; public class C { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; static class Man implements Comparable<Man> { long x, y; int id; public Man(long x, long y, int id) { this.x = x; this.y = y; this.id = id; } @Override public int compareTo(Man o) { if (x != o.x) { return x < o.x ? 1 : -1; } return Long.compare(y, o.y); } } boolean bad(Man a, Man b, Man c) { long val = a.x * b.x * c.y * (b.y - a.y) + c.x * a.x * b.y * (a.y - c.y) + b.x * c.x * a.y * (c.y - b.y); return val < 0; } void solve() throws IOException { int n = nextInt(); Man[] a = new Man[n]; for (int i = 0; i < n; i++) { a[i] = new Man(nextInt(), nextInt(), i); } int[] repr = new int[n]; Arrays.fill(repr, -1); Arrays.sort(a); Man[] hull = new Man[n]; int sz = 1; hull[0] = a[0]; for (int i = 1; i < n; i++) { if (a[i].x == a[i - 1].x && a[i].y == a[i - 1].y) { repr[a[i].id] = a[i - 1].id; continue; } while (sz > 1 && bad(hull[sz - 2], hull[sz - 1], a[i])) { sz--; } hull[sz++] = a[i]; } while (sz > 1 && hull[sz - 1].x <= hull[sz - 2].x && hull[sz - 1].y <= hull[sz - 2].y) { sz--; } long bestX = -1; for (int i = 0; i < n; i++) { bestX = Math.max(bestX, a[i].x); } long bestXbestY = -1; for (int i = 0; i < n; i++) { if (a[i].x == bestX) { bestXbestY = Math.max(bestXbestY, a[i].y); } } long bestY = -1; for (int i = 0; i < n; i++) { bestY = Math.max(bestY, a[i].y); } long bestYbestX = -1; for (int i = 0; i < n; i++) { if (a[i].y == bestY) { bestYbestX = Math.max(bestYbestX, a[i].x); } } boolean[] good = new boolean[n]; for (int i = 0; i < sz; i++) { if (hull[i].x == bestX && hull[i].y < bestXbestY) { continue; } if (hull[i].y == bestY && hull[i].x < bestYbestX) { continue; } good[hull[i].id] = true; } for (int i = 0; i < n; i++) { if (repr[i] != -1) { good[i] = good[repr[i]]; } } for (int i = 0; i < n; i++) { if (good[i]) { out.print((i + 1) + " "); } } out.println(); } C() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new C(); } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["3\n1 3\n2 2\n3 1", "3\n1 2\n1 1\n2 1"]
1 second
["1 2 3", "1 3"]
null
Java 8
standard input
[ "geometry", "math" ]
e54f8aff8ede309bd591cb9fbd565d1f
The first line of input contains a single integer n (1 ≀ n ≀ 2 × 105). The next n lines contain the details of competitors. i-th line contains two integers si and ri (1 ≀ si, ri ≀ 104).
2,600
In the first and the only line of output, print a sequence of numbers of possible winners in increasing order.
standard output
PASSED
9340966313afe7b00c6667ceeaf246b4
train_004.jsonl
1429029300
Tavas is a cheerleader in the new sports competition named "Pashmaks". This competition consists of two part: swimming and then running. People will immediately start running R meters after they finished swimming exactly S meters. A winner is a such person that nobody else finishes running before him/her (there may be more than one winner).Before the match starts, Tavas knows that there are n competitors registered for the match. Also, he knows that i-th person's swimming speed is si meters per second and his/her running speed is ri meters per second. Unfortunately, he doesn't know the values of R and S, but he knows that they are real numbers greater than 0.As a cheerleader, Tavas wants to know who to cheer up. So, he wants to know all people that might win. We consider a competitor might win if and only if there are some values of R and S such that with these values, (s)he will be a winner.Tavas isn't really familiar with programming, so he asked you to help him.
256 megabytes
import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.BufferedReader; import java.util.StringTokenizer; import java.io.IOException; import java.util.Arrays; public class Problem { BufferedReader br; BufferedWriter out; StringTokenizer st; boolean eof; public class Line { public int a, b; public int i; } public static void main(String[] args) throws IOException{ new Problem(); } public boolean bad2(Line a, Line b, Line c) { //if(c.a == 0) return true; /*long n1 = 1l * a.a * c.a * (c.b - a.b); long d1 = 1l * a.b * c.b * (a.a - c.a); long n2 = 1l * a.a * b.a * (b.b - a.b); long d2 = 1l * a.b * b.b * (a.a - b.a);*/ return 1l*c.a*b.b*(c.b-a.b)*(a.a-b.a) > 1l*b.a*c.b*(b.b-a.b)*(a.a-c.a); } public boolean bad1(Line a, Line b) { return a.b >= b.b; } Problem() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new BufferedWriter(new PrintWriter(System.out)); //read input int n = nextInt(); //System.out.println(n); Line[] L = new Line[n]; for (int i = 0; i < n; i++) { L[i] = new Line(); L[i].a = nextInt(); L[i].b = nextInt(); L[i].i = i + 1; } //sort by slope Arrays.sort(L, (l1, l2) -> (l1.a < l2.a || (l1.a == l2.a && l1.b < l2.b))? -1 : 1); //construct upper hull Line[] a = new Line[n]; int sz = 0; for(int i = 0; i < n; i++) { if(i < n - 1 && L[i].a == L[i + 1].a) continue; while(sz > 1 && bad2(L[i], a[sz-1], a[sz-2])) sz--; while(sz > 0 && bad1(L[i], a[sz-1])) sz--; a[sz++] = L[i]; } ///print answer int fsz = sz; for(int i = 0, j = 0; i < fsz; i++) { while(L[j].a != a[i].a || L[j].b != a[i].b) j++; while(L[j].a == a[i].a && L[j].b == a[i].b && L[j].i != a[i].i) a[sz++] = L[j++]; } Arrays.sort(a, 0, sz, (x, y) -> x.i - y.i); for(int i = 0; i < sz; i++) { out.write(a[i].i + " "); } out.flush(); out.close(); } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["3\n1 3\n2 2\n3 1", "3\n1 2\n1 1\n2 1"]
1 second
["1 2 3", "1 3"]
null
Java 8
standard input
[ "geometry", "math" ]
e54f8aff8ede309bd591cb9fbd565d1f
The first line of input contains a single integer n (1 ≀ n ≀ 2 × 105). The next n lines contain the details of competitors. i-th line contains two integers si and ri (1 ≀ si, ri ≀ 104).
2,600
In the first and the only line of output, print a sequence of numbers of possible winners in increasing order.
standard output
PASSED
d420f529a881417f0465ac9ab6a7a799
train_004.jsonl
1429029300
Tavas is a cheerleader in the new sports competition named "Pashmaks". This competition consists of two part: swimming and then running. People will immediately start running R meters after they finished swimming exactly S meters. A winner is a such person that nobody else finishes running before him/her (there may be more than one winner).Before the match starts, Tavas knows that there are n competitors registered for the match. Also, he knows that i-th person's swimming speed is si meters per second and his/her running speed is ri meters per second. Unfortunately, he doesn't know the values of R and S, but he knows that they are real numbers greater than 0.As a cheerleader, Tavas wants to know who to cheer up. So, he wants to know all people that might win. We consider a competitor might win if and only if there are some values of R and S such that with these values, (s)he will be a winner.Tavas isn't really familiar with programming, so he asked you to help him.
256 megabytes
import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.BufferedReader; import java.util.StringTokenizer; import java.io.IOException; import java.util.Arrays; public class Problem { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; public class Line { public int a, b; public int i; } public static void main(String[] args) throws IOException{ new Problem(); } public boolean bad2(Line a, Line b, Line c) { //if(c.a == 0) return true; /*long n1 = 1l * a.a * c.a * (c.b - a.b); long d1 = 1l * a.b * c.b * (a.a - c.a); long n2 = 1l * a.a * b.a * (b.b - a.b); long d2 = 1l * a.b * b.b * (a.a - b.a);*/ return 1l*c.a*b.b*(c.b-a.b)*(a.a-b.a) > 1l*b.a*c.b*(b.b-a.b)*(a.a-c.a); } public boolean bad1(Line a, Line b) { return a.b >= b.b; } Problem() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); //read input int n = nextInt(); //System.out.println(n); Line[] L = new Line[n]; for (int i = 0; i < n; i++) { L[i] = new Line(); L[i].a = nextInt(); L[i].b = nextInt(); L[i].i = i + 1; } //sort by slope Arrays.sort(L, (l1, l2) -> (l1.a < l2.a || (l1.a == l2.a && l1.b < l2.b))? -1 : 1); //construct upper hull Line[] a = new Line[n]; int sz = 0; for(int i = 0; i < n; i++) { if(i < n - 1 && L[i].a == L[i + 1].a) continue; while(sz > 1 && bad2(L[i], a[sz-1], a[sz-2])) sz--; while(sz > 0 && bad1(L[i], a[sz-1])) sz--; a[sz++] = L[i]; } ///print answer int fsz = sz; for(int i = 0, j = 0; i < fsz; i++) { while(L[j].a != a[i].a || L[j].b != a[i].b) j++; while(L[j].a == a[i].a && L[j].b == a[i].b && L[j].i != a[i].i) a[sz++] = L[j++]; } Arrays.sort(a, 0, sz, (x, y) -> x.i - y.i); for(int i = 0; i < sz; i++) { out.print((a[i].i) + " "); } out.close(); } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["3\n1 3\n2 2\n3 1", "3\n1 2\n1 1\n2 1"]
1 second
["1 2 3", "1 3"]
null
Java 8
standard input
[ "geometry", "math" ]
e54f8aff8ede309bd591cb9fbd565d1f
The first line of input contains a single integer n (1 ≀ n ≀ 2 × 105). The next n lines contain the details of competitors. i-th line contains two integers si and ri (1 ≀ si, ri ≀ 104).
2,600
In the first and the only line of output, print a sequence of numbers of possible winners in increasing order.
standard output
PASSED
5fbe20636d4569aa6787e980d3ecb45b
train_004.jsonl
1429029300
Tavas is a cheerleader in the new sports competition named "Pashmaks". This competition consists of two part: swimming and then running. People will immediately start running R meters after they finished swimming exactly S meters. A winner is a such person that nobody else finishes running before him/her (there may be more than one winner).Before the match starts, Tavas knows that there are n competitors registered for the match. Also, he knows that i-th person's swimming speed is si meters per second and his/her running speed is ri meters per second. Unfortunately, he doesn't know the values of R and S, but he knows that they are real numbers greater than 0.As a cheerleader, Tavas wants to know who to cheer up. So, he wants to know all people that might win. We consider a competitor might win if and only if there are some values of R and S such that with these values, (s)he will be a winner.Tavas isn't really familiar with programming, so he asked you to help him.
256 megabytes
import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.BufferedReader; import java.util.StringTokenizer; import java.io.IOException; import java.util.Arrays; public class Problem { BufferedReader br; //PrintWriter out; StringTokenizer st; boolean eof; public class Line { public int a, b; public int i; } public static void main(String[] args) throws IOException{ new Problem(); } public boolean bad2(Line a, Line b, Line c) { //if(c.a == 0) return true; /*long n1 = 1l * a.a * c.a * (c.b - a.b); long d1 = 1l * a.b * c.b * (a.a - c.a); long n2 = 1l * a.a * b.a * (b.b - a.b); long d2 = 1l * a.b * b.b * (a.a - b.a);*/ return 1l*c.a*b.b*(c.b-a.b)*(a.a-b.a) > 1l*b.a*c.b*(b.b-a.b)*(a.a-c.a); } public boolean bad1(Line a, Line b) { return a.b >= b.b; } Problem() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); //read input int n = nextInt(); //System.out.println(n); Line[] L = new Line[n]; for (int i = 0; i < n; i++) { L[i] = new Line(); L[i].a = nextInt(); L[i].b = nextInt(); L[i].i = i + 1; } //sort by slope Arrays.sort(L, (l1, l2) -> (l1.a < l2.a || (l1.a == l2.a && l1.b < l2.b))? -1 : 1); //construct upper hull Line[] a = new Line[n]; int sz = 0; for(int i = 0; i < n; i++) { if(i < n - 1 && L[i].a == L[i + 1].a) continue; while(sz > 1 && bad2(L[i], a[sz-1], a[sz-2])) sz--; while(sz > 0 && bad1(L[i], a[sz-1])) sz--; a[sz++] = L[i]; } ///print answer int fsz = sz; for(int i = 0, j = 0; i < fsz; i++) { while(L[j].a != a[i].a || L[j].b != a[i].b) j++; while(L[j].a == a[i].a && L[j].b == a[i].b && L[j].i != a[i].i) a[sz++] = L[j++]; } Arrays.sort(a, 0, sz, (x, y) -> x.i - y.i); for(int i = 0; i < sz; i++) { System.out.print((a[i].i) + " "); } } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["3\n1 3\n2 2\n3 1", "3\n1 2\n1 1\n2 1"]
1 second
["1 2 3", "1 3"]
null
Java 8
standard input
[ "geometry", "math" ]
e54f8aff8ede309bd591cb9fbd565d1f
The first line of input contains a single integer n (1 ≀ n ≀ 2 × 105). The next n lines contain the details of competitors. i-th line contains two integers si and ri (1 ≀ si, ri ≀ 104).
2,600
In the first and the only line of output, print a sequence of numbers of possible winners in increasing order.
standard output
PASSED
10717799fe96edf9a19bb75a2cfd40c0
train_004.jsonl
1429029300
Tavas is a cheerleader in the new sports competition named "Pashmaks". This competition consists of two part: swimming and then running. People will immediately start running R meters after they finished swimming exactly S meters. A winner is a such person that nobody else finishes running before him/her (there may be more than one winner).Before the match starts, Tavas knows that there are n competitors registered for the match. Also, he knows that i-th person's swimming speed is si meters per second and his/her running speed is ri meters per second. Unfortunately, he doesn't know the values of R and S, but he knows that they are real numbers greater than 0.As a cheerleader, Tavas wants to know who to cheer up. So, he wants to know all people that might win. We consider a competitor might win if and only if there are some values of R and S such that with these values, (s)he will be a winner.Tavas isn't really familiar with programming, so he asked you to help him.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class C { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); class Player implements Comparable<Player> { long s; long r; Point point; List<Integer> indexes; public Player(long s, long r, int index) { this.s = s; this.r = r; this.point = new Point(this); this.indexes = new ArrayList<Integer>(); indexes.add(index); } public int compareTo(Player other) { if (this.s > other.s) return -1; if (this.s < other.s) return 1; if (this.r > other.r) return -1; if (this.r < other.r) return 1; return 0; } } void solve() throws IOException { int n = readInt(); Player[] players = new Player[n]; for (int i = 0; i < n; i++) { players[i] = new Player(readInt(), readInt(), i + 1); } Arrays.sort(players); boolean[] can = new boolean[n]; can[0] = true; long max = players[0].r; List<Player> potWins = new ArrayList<Player>(); for (int i = 1; i < n; i++) { if (players[i].compareTo(players[i - 1]) == 0) { can[i] = can[i - 1]; } if (players[i].r > max) { max = players[i].r; can[i] = true; } } for (int i = 0; i < n; i++) { if (can[i]) { potWins.add(players[i]); } } Stack<Player> stack = new Stack<Player>(); stack.push(potWins.get(0)); for(int i = 1; i < potWins.size(); i++) { Player cur = potWins.get(i); if(cur.compareTo(stack.peek()) == 0) { stack.peek().indexes.addAll(cur.indexes); continue; } while (stack.size() != 1) { Player prev = stack.pop(); Player prev2 = stack.peek(); if(check(prev2.point, prev.point, cur.point)) { stack.push(prev); break; } } stack.push(cur); } List<Integer> nums = new ArrayList<Integer>(); while (!stack.empty()) { nums.addAll(stack.pop().indexes); } Collections.sort(nums); for(int i: nums) { out.print(i + " "); } } class Drobe { long up; long down; Drobe(long up, long down) { this.up = up; this.down = down; } Drobe mult(Drobe a, Drobe b) { return new Drobe(a.up * b.up, a.down * b.down); } Drobe add(Drobe a, Drobe b) { return new Drobe(a.up * b.down + b.up * a.down, a.down * b.down); } Drobe sub(Drobe a, Drobe b) { return new Drobe(a.up * b.down - b.up * a.down, a.down * b.down); } Drobe mult(Drobe b) { return mult(this, b); } Drobe sub(Drobe b) { return sub(this, b); } } class Point { Drobe x; Drobe y; Point(Player player) { this.x = new Drobe(1, player.s); this.y = new Drobe(1, player.r); } } boolean check(Point a, Point b, Point c) { Drobe first = b.x.sub(a.x).mult(c.y.sub(a.y)); Drobe second = b.y.sub(a.y).mult(c.x.sub(a.x)); BigInteger f = BigInteger.valueOf(first.up); f = f.multiply(BigInteger.valueOf(second.down)); BigInteger s = BigInteger.valueOf(first.down); s = s.multiply(BigInteger.valueOf(second.up)); if(f.compareTo(s) >= 0) return true; return false; } void init() throws FileNotFoundException { if (ONLINE_JUDGE) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } int[] readArr(int n) throws IOException { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = readInt(); } return res; } long[] readArrL(int n) throws IOException { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = readLong(); } return res; } public static void main(String[] args) { new C().run(); } public void run() { try { long t1 = System.currentTimeMillis(); init(); solve(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = " + (t2 - t1)); } catch (Exception e) { e.printStackTrace(System.err); System.exit(-1); } } }
Java
["3\n1 3\n2 2\n3 1", "3\n1 2\n1 1\n2 1"]
1 second
["1 2 3", "1 3"]
null
Java 8
standard input
[ "geometry", "math" ]
e54f8aff8ede309bd591cb9fbd565d1f
The first line of input contains a single integer n (1 ≀ n ≀ 2 × 105). The next n lines contain the details of competitors. i-th line contains two integers si and ri (1 ≀ si, ri ≀ 104).
2,600
In the first and the only line of output, print a sequence of numbers of possible winners in increasing order.
standard output
PASSED
99e4c7361db45293bdafe707fe9fcc01
train_004.jsonl
1429029300
Tavas is a cheerleader in the new sports competition named "Pashmaks". This competition consists of two part: swimming and then running. People will immediately start running R meters after they finished swimming exactly S meters. A winner is a such person that nobody else finishes running before him/her (there may be more than one winner).Before the match starts, Tavas knows that there are n competitors registered for the match. Also, he knows that i-th person's swimming speed is si meters per second and his/her running speed is ri meters per second. Unfortunately, he doesn't know the values of R and S, but he knows that they are real numbers greater than 0.As a cheerleader, Tavas wants to know who to cheer up. So, he wants to know all people that might win. We consider a competitor might win if and only if there are some values of R and S such that with these values, (s)he will be a winner.Tavas isn't really familiar with programming, so he asked you to help him.
256 megabytes
import java.util.ArrayList; import java.util.List; import java.math.BigInteger; import java.io.OutputStream; import java.io.PrintWriter; import java.io.IOException; import java.util.Arrays; import java.util.TreeSet; import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.PrintStream; import java.util.Comparator; import java.util.Set; import java.util.StringTokenizer; /** * Built using CHelper plug-in * Actual solution is at the top * @author shu_mj @ http://shu-mj.com */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { Scanner in; PrintWriter out; public void solve(int testNumber, Scanner in, PrintWriter out) { this.in = in; this.out = out; run(); } void run() { int n = in.nextInt(); P[] ps = new P[n]; for (int i = 0; i < n; i++) { ps[i] = new P(10000. / in.nextInt(), 10000. / in.nextInt()); } P[] ps2 = ps.clone(); Arrays.sort(ps2); ps2 = Algo.unique(ps2); P[] ch = P.convexHull(ps2); P[] ch2 = new P[ch.length * 2]; for (int i = 0; i < ch.length; i++) ch2[i] = ch2[i + ch.length] = ch[i]; int l = 0, r = 0; for (int i = 0; i < ch.length; i++) { if (ch[i].x < ch[l].x || ch[i].x == ch[l].x && ch[i].y < ch[l].y) l = i; } r = l; for (int i = l; i < ch2.length; i++) { if (ch2[i].y < ch2[r].y || ch2[i].y == ch2[r].y && ch2[i].x < ch2[r].x) r = i; } Set<P> set = new TreeSet<>(); for (int i = l; i <= r; i++) { set.add(ch2[i]); } for (int i = 0; i < n; i++) { if (set.contains(ps[i])) { out.print((i + 1) + " "); } } out.println(); } } class Scanner { BufferedReader br; StringTokenizer st; public Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); eat(""); } private void eat(String s) { st = new StringTokenizer(s); } public String nextLine() { try { return br.readLine(); } catch (IOException e) { return null; } } public boolean hasNext() { while (!st.hasMoreTokens()) { String s = nextLine(); if (s == null) return false; eat(s); } return true; } public String next() { hasNext(); return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } class P implements Comparable<P> { public static final double EPS = 1e-9; public static double add(double a, double b) { if (Math.abs(a + b) < EPS * (Math.abs(a) + Math.abs(b))) return 0; return a + b; } public final double x, y; public P(double x, double y) { this.x = x; this.y = y; } public P sub(P p) { return new P(add(x, -p.x), add(y, -p.y)); } public double det(P p) { return add(x * p.y, -y * p.x); } public String toString() { return "(" + x + ", " + y + ")"; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; return compareTo((P) obj) == 0; } public int compareTo(P p) { int b = sig(x - p.x); if (b != 0) return b; return sig(y - p.y); } public static int sig(double x) { if (Math.abs(x) < EPS) return 0; return x < 0 ? -1 : 1; } //ε‡ΈεŒ… //ι€†ζ—Άι’ˆ δΈεŒ…ε«ηΊΏδΈŠηš„η‚Ή //ε¦‚ζžœιœ€θ¦εŒ…ε«ηΊΏδΈŠηš„η‚Ή ε°† <= 0 ζ”Ήζˆ < 0 //δ½†ζ˜―ιœ€θ¦ζ³¨ζ„ζ­€ζ—ΆδΈθƒ½ζœ‰ι‡η‚Ή public static P[] convexHull(P[] ps) { int n = ps.length, k = 0; if (n <= 1) return ps; Arrays.sort(ps); P[] qs = new P[n * 2]; for (int i = 0; i < n; qs[k++] = ps[i++]) { while (k > 1 && qs[k - 1].sub(qs[k - 2]).det(ps[i].sub(qs[k - 1])) < -EPS) k--; } for (int i = n - 2, t = k; i >= 0; qs[k++] = ps[i--]) { while (k > t && qs[k - 1].sub(qs[k - 2]).det(ps[i].sub(qs[k - 1])) < -EPS) k--; } P[] res = new P[k - 1]; System.arraycopy(qs, 0, res, 0, k - 1); return res; } } class Algo { public static <T extends Comparable<T>> T[] unique(T[] ts) { return unique(ts, 0, ts.length); } public static <T extends Comparable<T>> T[] unique(T[] ts, int b, int e) { if (b == e) return Arrays.copyOfRange(ts, b, e); int cnt = 1; for (int i = b + 1; i < e; i++) { if (ts[i].compareTo(ts[i - 1]) != 0) cnt++; } T[] res = Arrays.copyOf(ts, cnt); res[0] = ts[b]; int id = 1; for (int i = b + 1; i < e; i++) { if (ts[i].compareTo(ts[i - 1]) != 0) res[id++] = ts[i]; } return res; } }
Java
["3\n1 3\n2 2\n3 1", "3\n1 2\n1 1\n2 1"]
1 second
["1 2 3", "1 3"]
null
Java 8
standard input
[ "geometry", "math" ]
e54f8aff8ede309bd591cb9fbd565d1f
The first line of input contains a single integer n (1 ≀ n ≀ 2 × 105). The next n lines contain the details of competitors. i-th line contains two integers si and ri (1 ≀ si, ri ≀ 104).
2,600
In the first and the only line of output, print a sequence of numbers of possible winners in increasing order.
standard output
PASSED
89d0d0ccd60d694c3cd916b201a4a822
train_004.jsonl
1429029300
Tavas is a cheerleader in the new sports competition named "Pashmaks". This competition consists of two part: swimming and then running. People will immediately start running R meters after they finished swimming exactly S meters. A winner is a such person that nobody else finishes running before him/her (there may be more than one winner).Before the match starts, Tavas knows that there are n competitors registered for the match. Also, he knows that i-th person's swimming speed is si meters per second and his/her running speed is ri meters per second. Unfortunately, he doesn't know the values of R and S, but he knows that they are real numbers greater than 0.As a cheerleader, Tavas wants to know who to cheer up. So, he wants to know all people that might win. We consider a competitor might win if and only if there are some values of R and S such that with these values, (s)he will be a winner.Tavas isn't really familiar with programming, so he asked you to help him.
256 megabytes
import java.util.Arrays; import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Comparator; import java.io.IOException; import java.util.StringTokenizer; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { static class Contestant { int s; int r; Contestant nextSame; boolean canWin; } public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); Contestant[] contestants = new Contestant[n]; for (int i = 0; i < n; ++i) { contestants[i] = new Contestant(); contestants[i].s = in.nextInt(); contestants[i].r = in.nextInt(); } doit(contestants.clone()); boolean first = true; for (int i = 0; i < n; ++i) if (contestants[i].canWin) { if (first) first = false; else out.print(" "); out.print(i + 1); } out.println(); } private void doit(Contestant[] contestants) { Arrays.sort(contestants, new Comparator<Contestant>() { public int compare(Contestant o1, Contestant o2) { int z = o2.r - o1.r; if (z == 0) z = o2.s - o1.s; return z; } }); int cnt = 0; for (int i = 0; i < contestants.length; ++i) { contestants[cnt++] = contestants[i]; if (cnt >= 2 && contestants[cnt - 1].s <= contestants[cnt - 2].s) { if (contestants[cnt - 1].s == contestants[cnt - 2].s && contestants[cnt - 1].r == contestants[cnt - 2].r) { contestants[cnt - 1].nextSame = contestants[cnt - 2]; contestants[cnt - 2] = contestants[cnt - 1]; } --cnt; } else { while (cnt >= 3) { Contestant a = contestants[cnt - 3]; Contestant b = contestants[cnt - 2]; Contestant c = contestants[cnt - 1]; if ((a.r - b.r) * (long) c.r * (b.s - c.s) * a.s - (a.s - b.s) * (long) c.s * (b.r - c.r) * a.r < 0) { contestants[cnt - 2] = c; --cnt; } else { break; } } } } for (int i = 0; i < cnt; ++i) { Contestant cur = contestants[i]; while (cur != null) { cur.canWin = true; cur = cur.nextSame; } } } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["3\n1 3\n2 2\n3 1", "3\n1 2\n1 1\n2 1"]
1 second
["1 2 3", "1 3"]
null
Java 8
standard input
[ "geometry", "math" ]
e54f8aff8ede309bd591cb9fbd565d1f
The first line of input contains a single integer n (1 ≀ n ≀ 2 × 105). The next n lines contain the details of competitors. i-th line contains two integers si and ri (1 ≀ si, ri ≀ 104).
2,600
In the first and the only line of output, print a sequence of numbers of possible winners in increasing order.
standard output
PASSED
79a294552bf6b51ae1dd80afb2f4a261
train_004.jsonl
1603204500
You are a mayor of Berlyatov. There are $$$n$$$ districts and $$$m$$$ two-way roads between them. The $$$i$$$-th road connects districts $$$x_i$$$ and $$$y_i$$$. The cost of travelling along this road is $$$w_i$$$. There is some path between each pair of districts, so the city is connected.There are $$$k$$$ delivery routes in Berlyatov. The $$$i$$$-th route is going from the district $$$a_i$$$ to the district $$$b_i$$$. There is one courier on each route and the courier will always choose the cheapest (minimum by total cost) path from the district $$$a_i$$$ to the district $$$b_i$$$ to deliver products.The route can go from the district to itself, some couriers routes can coincide (and you have to count them independently).You can make at most one road to have cost zero (i.e. you choose at most one road and change its cost with $$$0$$$).Let $$$d(x, y)$$$ be the cheapest cost of travel between districts $$$x$$$ and $$$y$$$.Your task is to find the minimum total courier routes cost you can achieve, if you optimally select the some road and change its cost with $$$0$$$. In other words, you have to find the minimum possible value of $$$\sum\limits_{i = 1}^{k} d(a_i, b_i)$$$ after applying the operation described above optimally.
256 megabytes
import java.util.*; import java.io.*; public class Main { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } 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; din.close(); } } static ArrayList<Integer> edge[]; static int[][] dist,wt; static class Pair { int f,s; Pair(int f,int s) { this.f=f; this.s=s; } } public static void dijkshtra(int u,int n) { Arrays.fill(dist[u],Integer.MAX_VALUE); dist[u][u]=0; PriorityQueue<Pair> pq=new PriorityQueue<>((p1,p2)->p1.s-p2.s); boolean vis[]=new boolean[n+1]; for(int i=1;i<=n;i++) pq.add(new Pair(i,dist[u][i])); while(!pq.isEmpty()) { Pair p=pq.poll(); if(!vis[p.f]) { for(int v:edge[p.f]) { if(dist[u][v]>dist[u][p.f]+wt[p.f][v]&&!vis[v]) { dist[u][v]=dist[u][p.f]+wt[p.f][v]; pq.add(new Pair(v,dist[u][v])); } } vis[p.f]=true; } } } public static void main(String args[])throws Exception { Reader sc=new Reader(); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw=new PrintWriter(System.out); int n=sc.nextInt(); int m=sc.nextInt(); int k=sc.nextInt(); edge=new ArrayList[n+1]; for(int i=0;i<=n;i++) edge[i]=new ArrayList<>(); dist=new int[n+1][n+1]; wt=new int[n+1][n+1]; for(int i=0;i<m;i++) { int u=sc.nextInt(); int v=sc.nextInt(); int w=sc.nextInt(); edge[u].add(v); edge[v].add(u); wt[u][v]=w; wt[v][u]=w; } int q[][]=new int[k][2]; for(int i=0;i<k;i++) { q[i][0]=sc.nextInt(); q[i][1]=sc.nextInt(); } dist=new int[n+1][n+1]; for(int i=1;i<=n;i++) dijkshtra(i,n); int ans=Integer.MAX_VALUE; for(int i=1;i<=n;i++) { for(int j:edge[i]) { int cur=0; for(int p=0;p<k;p++) { int u=q[p][0]; int v=q[p][1]; cur+=Math.min(dist[u][v],Math.min(dist[u][i]+dist[j][v],dist[u][j]+dist[i][v])); } ans=Math.min(ans,cur); } } pw.println(ans); pw.flush(); pw.close(); } }
Java
["6 5 2\n1 2 5\n2 3 7\n2 4 4\n4 5 2\n4 6 8\n1 6\n5 3", "5 5 4\n1 2 5\n2 3 4\n1 4 3\n4 3 7\n3 5 2\n1 5\n1 3\n3 3\n1 5"]
1 second
["22", "13"]
NoteThe picture corresponding to the first example:There, you can choose either the road $$$(2, 4)$$$ or the road $$$(4, 6)$$$. Both options lead to the total cost $$$22$$$.The picture corresponding to the second example:There, you can choose the road $$$(3, 4)$$$. This leads to the total cost $$$13$$$.
Java 11
standard input
[ "graphs", "brute force", "shortest paths" ]
6ccb639373ca04646be8866273402c93
The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 1000$$$; $$$n - 1 \le m \le min(1000, \frac{n(n-1)}{2})$$$; $$$1 \le k \le 1000$$$) β€” the number of districts, the number of roads and the number of courier routes. The next $$$m$$$ lines describe roads. The $$$i$$$-th road is given as three integers $$$x_i$$$, $$$y_i$$$ and $$$w_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \ne y_i$$$; $$$1 \le w_i \le 1000$$$), where $$$x_i$$$ and $$$y_i$$$ are districts the $$$i$$$-th road connects and $$$w_i$$$ is its cost. It is guaranteed that there is some path between each pair of districts, so the city is connected. It is also guaranteed that there is at most one road between each pair of districts. The next $$$k$$$ lines describe courier routes. The $$$i$$$-th route is given as two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$) β€” the districts of the $$$i$$$-th route. The route can go from the district to itself, some couriers routes can coincide (and you have to count them independently).
2,100
Print one integer β€” the minimum total courier routes cost you can achieve (i.e. the minimum value $$$\sum\limits_{i=1}^{k} d(a_i, b_i)$$$, where $$$d(x, y)$$$ is the cheapest cost of travel between districts $$$x$$$ and $$$y$$$) if you can make some (at most one) road cost zero.
standard output
PASSED
3a1ef151f0d7d50d6147a25ddb3d758b
train_004.jsonl
1603204500
You are a mayor of Berlyatov. There are $$$n$$$ districts and $$$m$$$ two-way roads between them. The $$$i$$$-th road connects districts $$$x_i$$$ and $$$y_i$$$. The cost of travelling along this road is $$$w_i$$$. There is some path between each pair of districts, so the city is connected.There are $$$k$$$ delivery routes in Berlyatov. The $$$i$$$-th route is going from the district $$$a_i$$$ to the district $$$b_i$$$. There is one courier on each route and the courier will always choose the cheapest (minimum by total cost) path from the district $$$a_i$$$ to the district $$$b_i$$$ to deliver products.The route can go from the district to itself, some couriers routes can coincide (and you have to count them independently).You can make at most one road to have cost zero (i.e. you choose at most one road and change its cost with $$$0$$$).Let $$$d(x, y)$$$ be the cheapest cost of travel between districts $$$x$$$ and $$$y$$$.Your task is to find the minimum total courier routes cost you can achieve, if you optimally select the some road and change its cost with $$$0$$$. In other words, you have to find the minimum possible value of $$$\sum\limits_{i = 1}^{k} d(a_i, b_i)$$$ after applying the operation described above optimally.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.PriorityQueue; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.util.AbstractCollection; import java.util.NoSuchElementException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); GReducingDeliveryCost solver = new GReducingDeliveryCost(); solver.solve(1, in, out); out.close(); } static class GReducingDeliveryCost { static int n; static int m; static long[][] shortest_distance; static ArrayList<GReducingDeliveryCost.pair>[] adjlist; static ArrayList<GReducingDeliveryCost.pair2> edges; public void solve(int testNumber, Scanner sc, PrintWriter pw) { n = sc.nextInt(); m = sc.nextInt(); int k = sc.nextInt(); adjlist = new ArrayList[n + 1]; edges = new ArrayList<>(); shortest_distance = new long[n + 1][n + 1]; for (long[] a : shortest_distance) Arrays.fill(a, Integer.MAX_VALUE); for (int i = 0; i <= n; i++) adjlist[i] = new ArrayList<>(); for (int i = 0; i < m; i++) { int u = sc.nextInt(); int v = sc.nextInt(); int distance = sc.nextInt(); adjlist[u].add(new GReducingDeliveryCost.pair(v, distance)); adjlist[v].add(new GReducingDeliveryCost.pair(u, distance)); edges.add(new GReducingDeliveryCost.pair2(u, v)); } ArrayList<GReducingDeliveryCost.pair2> courier = new ArrayList<>(); for (int i = 0; i < k; i++) { courier.add(new GReducingDeliveryCost.pair2(sc.nextInt(), sc.nextInt())); } for (int i = 1; i <= n; i++) dijkstra(i); long ans = Long.MAX_VALUE; for (int i = 0; i < m; i++) { GReducingDeliveryCost.pair2 temp = edges.get(i); long sum = 0; for (int j = 0; j < k; j++) { GReducingDeliveryCost.pair2 c = courier.get(j); long min = Math.min(shortest_distance[c.u][c.v], shortest_distance[c.v][c.u]); min = Math.min(min, shortest_distance[c.u][temp.u] + shortest_distance[temp.v][c.v]); min = Math.min(min, shortest_distance[c.u][temp.v] + shortest_distance[temp.u][c.v]); sum += min; } ans = Math.min(ans, sum); } pw.println(ans); } static void dijkstra(int start) { shortest_distance[start][start] = 0; PriorityQueue<GReducingDeliveryCost.pair> pq = new PriorityQueue<>(); pq.add(new GReducingDeliveryCost.pair(start, 0)); while (!pq.isEmpty()) { GReducingDeliveryCost.pair temp = pq.poll(); if (temp.d > shortest_distance[start][temp.u]) continue; for (GReducingDeliveryCost.pair v : adjlist[temp.u]) { if (temp.d + v.d < shortest_distance[start][v.u]) { pq.add(new GReducingDeliveryCost.pair(v.u, shortest_distance[start][v.u] = temp.d + v.d)); } } } } static class pair implements Comparable<GReducingDeliveryCost.pair> { int u; long d; public pair(int u, long d) { this.u = u; this.d = d; } public String toString() { return u + " " + d; } public int compareTo(GReducingDeliveryCost.pair o) { return Long.compare(d, o.d); } } static class pair2 { int u; int v; public pair2(int u, int v) { this.u = u; this.v = v; } public String toString() { return u + " " + v; } } } static class Scanner { private InputStream in; private byte[] buffer = new byte[1024]; private int curbuf; private int lenbuf; public Scanner(InputStream in) { this.in = in; this.curbuf = this.lenbuf = 0; } public boolean hasNextByte() { if (curbuf >= lenbuf) { curbuf = 0; try { lenbuf = in.read(buffer); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return false; } return true; } private int readByte() { if (hasNextByte()) return buffer[curbuf++]; else return -1; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private void skip() { while (hasNextByte() && isSpaceChar(buffer[curbuf])) curbuf++; } public boolean hasNext() { skip(); return hasNextByte(); } public int nextInt() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } } }
Java
["6 5 2\n1 2 5\n2 3 7\n2 4 4\n4 5 2\n4 6 8\n1 6\n5 3", "5 5 4\n1 2 5\n2 3 4\n1 4 3\n4 3 7\n3 5 2\n1 5\n1 3\n3 3\n1 5"]
1 second
["22", "13"]
NoteThe picture corresponding to the first example:There, you can choose either the road $$$(2, 4)$$$ or the road $$$(4, 6)$$$. Both options lead to the total cost $$$22$$$.The picture corresponding to the second example:There, you can choose the road $$$(3, 4)$$$. This leads to the total cost $$$13$$$.
Java 11
standard input
[ "graphs", "brute force", "shortest paths" ]
6ccb639373ca04646be8866273402c93
The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 1000$$$; $$$n - 1 \le m \le min(1000, \frac{n(n-1)}{2})$$$; $$$1 \le k \le 1000$$$) β€” the number of districts, the number of roads and the number of courier routes. The next $$$m$$$ lines describe roads. The $$$i$$$-th road is given as three integers $$$x_i$$$, $$$y_i$$$ and $$$w_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \ne y_i$$$; $$$1 \le w_i \le 1000$$$), where $$$x_i$$$ and $$$y_i$$$ are districts the $$$i$$$-th road connects and $$$w_i$$$ is its cost. It is guaranteed that there is some path between each pair of districts, so the city is connected. It is also guaranteed that there is at most one road between each pair of districts. The next $$$k$$$ lines describe courier routes. The $$$i$$$-th route is given as two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$) β€” the districts of the $$$i$$$-th route. The route can go from the district to itself, some couriers routes can coincide (and you have to count them independently).
2,100
Print one integer β€” the minimum total courier routes cost you can achieve (i.e. the minimum value $$$\sum\limits_{i=1}^{k} d(a_i, b_i)$$$, where $$$d(x, y)$$$ is the cheapest cost of travel between districts $$$x$$$ and $$$y$$$) if you can make some (at most one) road cost zero.
standard output
PASSED
4bd21f8bd9fe847e70a6743b46982bb1
train_004.jsonl
1603204500
You are a mayor of Berlyatov. There are $$$n$$$ districts and $$$m$$$ two-way roads between them. The $$$i$$$-th road connects districts $$$x_i$$$ and $$$y_i$$$. The cost of travelling along this road is $$$w_i$$$. There is some path between each pair of districts, so the city is connected.There are $$$k$$$ delivery routes in Berlyatov. The $$$i$$$-th route is going from the district $$$a_i$$$ to the district $$$b_i$$$. There is one courier on each route and the courier will always choose the cheapest (minimum by total cost) path from the district $$$a_i$$$ to the district $$$b_i$$$ to deliver products.The route can go from the district to itself, some couriers routes can coincide (and you have to count them independently).You can make at most one road to have cost zero (i.e. you choose at most one road and change its cost with $$$0$$$).Let $$$d(x, y)$$$ be the cheapest cost of travel between districts $$$x$$$ and $$$y$$$.Your task is to find the minimum total courier routes cost you can achieve, if you optimally select the some road and change its cost with $$$0$$$. In other words, you have to find the minimum possible value of $$$\sum\limits_{i = 1}^{k} d(a_i, b_i)$$$ after applying the operation described above optimally.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.PriorityQueue; import java.util.Random; import java.util.StringTokenizer; import java.util.HashMap; import java.util.Map; public class Main { static class Pair { int vertex, weight; public Pair(int vertex, int weight) { this.vertex = vertex; this.weight = weight; } } static class Courier { int a, b; public Courier(int a, int b) { this.a = a; this.b = b; } } static void dijkstra(int u, int[] distance) { // returns array of minimum distances from source u // TODO Complete Dijkstra PriorityQueue<Pair> pq = new PriorityQueue<Pair>(new Comparator<Pair>() { public int compare(Pair p1, Pair p2) { return Long.compare(p1.weight, p2.weight); } }); Arrays.fill(distance, INF); Arrays.fill(vis, false); distance[u] = 0; pq.add(new Pair(u, distance[u])); while(!pq.isEmpty()) { Pair cur = pq.poll(); vis[cur.vertex] = true; for(Pair x : adj.get(cur.vertex)) { if(!vis[x.vertex]) { if(distance[x.vertex] > distance[cur.vertex] + x.weight) { distance[x.vertex] = distance[cur.vertex] + x.weight; pq.add(new Pair(x.vertex, distance[x.vertex])); } } } } } public static void main(String[] args){ new Thread(null, null, "Anshum Gupta", 99999999) { public void run() { try { solve(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static final long mxx = (long)(1e18 + 5), MOD = 998244353; static final int mxN = (int)(1e6), mxV = (int)(1e6), log = 18, INF = (int)1e9; static boolean[]vis; static ArrayList<ArrayList<Pair>> adj = new ArrayList<ArrayList<Pair>>(); static int n, m, q, k; static char[] str; static long[] fact; static int[][]a; static Courier[] couriers; public static void solve() throws Exception { // solve the problem here s = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out), true); // out = new PrintWriter("output.txt"); int tc = 1;//s.nextInt(); for(int i=1; i<=tc; i++) { // out.print("Case #" + i + ": "); testcase(); } out.flush(); out.close(); } static void testcase() { n = s.nextInt(); m = s.nextInt(); k = s.nextInt(); couriers = new Courier[k]; vis = new boolean[n + 1]; for(int i = 0; i <= n; i++) adj.add(new ArrayList<Main.Pair>()); for(int i = 0; i < m; i++) { int x = s.nextInt(), y = s.nextInt(), w = s.nextInt(); adj.get(x).add(new Pair(y, w)); adj.get(y).add(new Pair(x, w)); } for(int i = 0; i < k; i++) { int a = s.nextInt(), b = s.nextInt(); couriers[i] = new Courier(a, b); } // iterate over all edges and find the cost after setting that edge to zero int[][] distance = new int[n + 1][n + 1]; for(int i = 1; i <= n; i++) { dijkstra(i, distance[i]); } int ans = INF; for(int i = 1; i <= n; i++) { for(Pair p : adj.get(i)) { int cur = 0; for(Courier courier : couriers) { int o1 = distance[courier.a][courier.b]; int o2 = distance[courier.a][i] + distance[p.vertex][courier.b]; int o3 = distance[courier.a][p.vertex] + distance[i][courier.b]; cur += Math.min(o1, Math.min(o2, o3)); } ans = Math.min(ans, cur); } } out.println(ans); } public static PrintWriter out; public static MyScanner s; static void shuffleArray(int[] a) { Random random = new Random(); for (int i = a.length-1; i > 0; i--) { int index = random.nextInt(i + 1); int tmp = a[index]; a[index] = a[i]; a[i] = tmp; } } static void shuffleSort(int[] a) { shuffleArray(a); Arrays.parallelSort(a); } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public MyScanner(String fileName) { try { br = new BufferedReader(new FileReader(fileName)); } 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()); } int[] nextIntArray(int n){ int[]a = new int[n]; for(int i=0; i<n; i++) { a[i] = this.nextInt(); } return a; } long[] nextlongArray(int n) { long[]a = new long[n]; for(int i=0; i<n; i++) { a[i] = this.nextLong(); } return a; } Integer[] nextIntegerArray(int n){ Integer[]a = new Integer[n]; for(int i=0; i<n; i++) { a[i] = this.nextInt(); } return a; } Long[] nextLongArray(int n) { Long[]a = new Long[n]; for(int i=0; i<n; i++) { a[i] = this.nextLong(); } return a; } char[][] next2DCharArray(int n, int m){ char[][]arr = new char[n][m]; for(int i=0; i<n; i++) { arr[i] = this.next().toCharArray(); } return arr; } ArrayList<ArrayList<Integer>> readUndirectedUnweightedGraph(int n, int m) { ArrayList<ArrayList<Integer>>adj = new ArrayList<ArrayList<Integer>>(); for(int i=0; i<=n; i++)adj.add(new ArrayList<Integer>()); for(int i=0; i<m; i++) { int u = s.nextInt(); int v = s.nextInt(); adj.get(u).add(v); adj.get(v).add(u); } return adj; } ArrayList<ArrayList<Integer>> readDirectedUnweightedGraph(int n, int m) { ArrayList<ArrayList<Integer>>adj = new ArrayList<ArrayList<Integer>>(); for(int i=0; i<=n; i++)adj.add(new ArrayList<Integer>()); for(int i=0; i<m; i++) { int u = s.nextInt(); int v = s.nextInt(); adj.get(u).add(v); } return adj; } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["6 5 2\n1 2 5\n2 3 7\n2 4 4\n4 5 2\n4 6 8\n1 6\n5 3", "5 5 4\n1 2 5\n2 3 4\n1 4 3\n4 3 7\n3 5 2\n1 5\n1 3\n3 3\n1 5"]
1 second
["22", "13"]
NoteThe picture corresponding to the first example:There, you can choose either the road $$$(2, 4)$$$ or the road $$$(4, 6)$$$. Both options lead to the total cost $$$22$$$.The picture corresponding to the second example:There, you can choose the road $$$(3, 4)$$$. This leads to the total cost $$$13$$$.
Java 11
standard input
[ "graphs", "brute force", "shortest paths" ]
6ccb639373ca04646be8866273402c93
The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 1000$$$; $$$n - 1 \le m \le min(1000, \frac{n(n-1)}{2})$$$; $$$1 \le k \le 1000$$$) β€” the number of districts, the number of roads and the number of courier routes. The next $$$m$$$ lines describe roads. The $$$i$$$-th road is given as three integers $$$x_i$$$, $$$y_i$$$ and $$$w_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \ne y_i$$$; $$$1 \le w_i \le 1000$$$), where $$$x_i$$$ and $$$y_i$$$ are districts the $$$i$$$-th road connects and $$$w_i$$$ is its cost. It is guaranteed that there is some path between each pair of districts, so the city is connected. It is also guaranteed that there is at most one road between each pair of districts. The next $$$k$$$ lines describe courier routes. The $$$i$$$-th route is given as two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$) β€” the districts of the $$$i$$$-th route. The route can go from the district to itself, some couriers routes can coincide (and you have to count them independently).
2,100
Print one integer β€” the minimum total courier routes cost you can achieve (i.e. the minimum value $$$\sum\limits_{i=1}^{k} d(a_i, b_i)$$$, where $$$d(x, y)$$$ is the cheapest cost of travel between districts $$$x$$$ and $$$y$$$) if you can make some (at most one) road cost zero.
standard output
PASSED
69c0b2248b96b693f6f4cb1b6c51007f
train_004.jsonl
1603204500
You are a mayor of Berlyatov. There are $$$n$$$ districts and $$$m$$$ two-way roads between them. The $$$i$$$-th road connects districts $$$x_i$$$ and $$$y_i$$$. The cost of travelling along this road is $$$w_i$$$. There is some path between each pair of districts, so the city is connected.There are $$$k$$$ delivery routes in Berlyatov. The $$$i$$$-th route is going from the district $$$a_i$$$ to the district $$$b_i$$$. There is one courier on each route and the courier will always choose the cheapest (minimum by total cost) path from the district $$$a_i$$$ to the district $$$b_i$$$ to deliver products.The route can go from the district to itself, some couriers routes can coincide (and you have to count them independently).You can make at most one road to have cost zero (i.e. you choose at most one road and change its cost with $$$0$$$).Let $$$d(x, y)$$$ be the cheapest cost of travel between districts $$$x$$$ and $$$y$$$.Your task is to find the minimum total courier routes cost you can achieve, if you optimally select the some road and change its cost with $$$0$$$. In other words, you have to find the minimum possible value of $$$\sum\limits_{i = 1}^{k} d(a_i, b_i)$$$ after applying the operation described above optimally.
256 megabytes
import java.io.*; import java.util.*; public class A { static int n, m, k; static int[] a, b; static int[][] cost; static List<int[]> adj[]; public static void main(String[] args) throws IOException { Flash f = new Flash(); int T = 1; //f.ni(); for(int tc = 1; tc <= T; tc++){ n = f.ni(); m = f.ni(); k = f.ni(); adj = new ArrayList[n]; for(int i = 0; i < n; i++) adj[i] = new ArrayList<>(); for(int i = 0; i < m; i++){ int u = f.ni()-1, v = f.ni()-1, w = f.ni(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } a = new int[k]; b = new int[k]; for(int i = 0; i < k; i++){ a[i] = f.ni()-1; b[i] = f.ni()-1; } sop(fn()); } } static long fn() { cost = new int[n][n]; for(int i = 0; i < n; i++) dij(i); //for(int i = 0; i < n; i++)sop(Arrays.toString(cost[i])); long ans = Integer.MAX_VALUE; for(int u = 0; u < n; u++){ for(int[] node : adj[u]){ int v = node[0]; int d = 0; for(int i = 0; i < k; i++){ int min = cost[a[i]][b[i]]; min = Math.min(min, cost[a[i]][u] + cost[v][b[i]]); min = Math.min(min, cost[a[i]][v] + cost[u][b[i]]); d += min; } ans = Math.min(ans, d); } } return ans; } static void dij(int s){ PriorityQueue<int[]> pq = new PriorityQueue<>((a,b)->a[1]-b[1]); int[] d = new int[n]; Arrays.fill(d, Integer.MAX_VALUE); d[s] = 0; pq.add(new int[]{s, 0}); while(!pq.isEmpty()){ int[] node = pq.poll(); int u = node[0]; int dist = node[1]; for(int[] v : adj[u]){ if(dist+v[1] < d[v[0]]){ d[v[0]] = dist+v[1]; pq.add(new int[]{v[0], d[v[0]]}); } } } for(int i = 0; i < n; i++) cost[s][i] = d[i]; } static void sort(int[] a){ List<Integer> A = new ArrayList<>(); for(int i : a) A.add(i); Collections.sort(A); for(int i = 0; i < A.size(); i++) a[i] = A.get(i); } static int swap(int itself, int dummy){ return itself; } static void sop(Object o){ System.out.println(o); } static void print(int[] a){ StringBuilder sb = new StringBuilder(); for(int i = 0; i < a.length; i++) sb.append(a[i] + " "); System.out.println(sb); } static class Flash { 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 ns(){ String s = new String(); try{ s = br.readLine().trim(); }catch(IOException e){ e.printStackTrace(); } return s; } int ni(){ return Integer.parseInt(next()); } int[] arr(int n){ int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = ni(); return a; } long nl(){ return Long.parseLong(next()); } double nd(){ return Double.parseDouble(next()); } } }
Java
["6 5 2\n1 2 5\n2 3 7\n2 4 4\n4 5 2\n4 6 8\n1 6\n5 3", "5 5 4\n1 2 5\n2 3 4\n1 4 3\n4 3 7\n3 5 2\n1 5\n1 3\n3 3\n1 5"]
1 second
["22", "13"]
NoteThe picture corresponding to the first example:There, you can choose either the road $$$(2, 4)$$$ or the road $$$(4, 6)$$$. Both options lead to the total cost $$$22$$$.The picture corresponding to the second example:There, you can choose the road $$$(3, 4)$$$. This leads to the total cost $$$13$$$.
Java 11
standard input
[ "graphs", "brute force", "shortest paths" ]
6ccb639373ca04646be8866273402c93
The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 1000$$$; $$$n - 1 \le m \le min(1000, \frac{n(n-1)}{2})$$$; $$$1 \le k \le 1000$$$) β€” the number of districts, the number of roads and the number of courier routes. The next $$$m$$$ lines describe roads. The $$$i$$$-th road is given as three integers $$$x_i$$$, $$$y_i$$$ and $$$w_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \ne y_i$$$; $$$1 \le w_i \le 1000$$$), where $$$x_i$$$ and $$$y_i$$$ are districts the $$$i$$$-th road connects and $$$w_i$$$ is its cost. It is guaranteed that there is some path between each pair of districts, so the city is connected. It is also guaranteed that there is at most one road between each pair of districts. The next $$$k$$$ lines describe courier routes. The $$$i$$$-th route is given as two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$) β€” the districts of the $$$i$$$-th route. The route can go from the district to itself, some couriers routes can coincide (and you have to count them independently).
2,100
Print one integer β€” the minimum total courier routes cost you can achieve (i.e. the minimum value $$$\sum\limits_{i=1}^{k} d(a_i, b_i)$$$, where $$$d(x, y)$$$ is the cheapest cost of travel between districts $$$x$$$ and $$$y$$$) if you can make some (at most one) road cost zero.
standard output
PASSED
207a80689e2855aef847cf123913c239
train_004.jsonl
1603204500
You are a mayor of Berlyatov. There are $$$n$$$ districts and $$$m$$$ two-way roads between them. The $$$i$$$-th road connects districts $$$x_i$$$ and $$$y_i$$$. The cost of travelling along this road is $$$w_i$$$. There is some path between each pair of districts, so the city is connected.There are $$$k$$$ delivery routes in Berlyatov. The $$$i$$$-th route is going from the district $$$a_i$$$ to the district $$$b_i$$$. There is one courier on each route and the courier will always choose the cheapest (minimum by total cost) path from the district $$$a_i$$$ to the district $$$b_i$$$ to deliver products.The route can go from the district to itself, some couriers routes can coincide (and you have to count them independently).You can make at most one road to have cost zero (i.e. you choose at most one road and change its cost with $$$0$$$).Let $$$d(x, y)$$$ be the cheapest cost of travel between districts $$$x$$$ and $$$y$$$.Your task is to find the minimum total courier routes cost you can achieve, if you optimally select the some road and change its cost with $$$0$$$. In other words, you have to find the minimum possible value of $$$\sum\limits_{i = 1}^{k} d(a_i, b_i)$$$ after applying the operation described above optimally.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.nio.file.LinkOption; import java.util.*; public class TaskG { ArrayList<int[]>[] adj; int[][] shortestPath; public static void main(String[] args) throws IOException{ new TaskG().solve(); } private void solve() throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer tokenizer = new StringTokenizer(f.readLine()); int n = Integer.parseInt(tokenizer.nextToken()); int m = Integer.parseInt(tokenizer.nextToken()); int k = Integer.parseInt(tokenizer.nextToken()); adj = new ArrayList[n]; shortestPath = new int[n][n]; int[][] edges = new int[m][2]; for (int i = 0; i < n; i++) adj[i] = new ArrayList<int[]>(); for (int i = 0; i < m; i++) { tokenizer = new StringTokenizer(f.readLine()); int a = Integer.parseInt(tokenizer.nextToken()) - 1; int b = Integer.parseInt(tokenizer.nextToken()) - 1; int w = Integer.parseInt(tokenizer.nextToken()); int[] edge1 = {b, w}; int[] edge2 = {a, w}; adj[a].add(edge1); adj[b].add(edge2); edges[i][0] = a; edges[i][1] = b; } int[][] cPaths = new int[k][2]; for (int i = 0; i < k; i++) { tokenizer = new StringTokenizer(f.readLine()); cPaths[i][0] = Integer.parseInt(tokenizer.nextToken()) - 1; cPaths[i][1] = Integer.parseInt(tokenizer.nextToken()) - 1; } for (int center = 0; center < n; center++) { int[] currPaths = new int[n]; Arrays.fill(currPaths, Integer.MAX_VALUE); PriorityQueue<int[]> pq = new PriorityQueue<int[]>(new ArrayComparator()); int[] ar = {center, 0}; pq.add(ar); while (!pq.isEmpty()) { ar = pq.remove(); int node = ar[0]; if (currPaths[node] != Integer.MAX_VALUE) continue; currPaths[node] = ar[1]; for (int[] adjacent : adj[node]) { if (currPaths[adjacent[0]] != Integer.MAX_VALUE) continue; int otherNode = adjacent[0]; int[] newAr = {otherNode, currPaths[node] + adjacent[1]}; pq.add(newAr); } } shortestPath[center] = currPaths; } long best = Long.MAX_VALUE; for (int[] edge : edges) { long curr = 0; for (int[] path : cPaths) { long currPath = shortestPath[path[0]][path[1]]; currPath = Math.min(currPath, shortestPath[path[0]][edge[0]] + shortestPath[edge[1]][path[1]]); currPath = Math.min(currPath, shortestPath[path[0]][edge[1]] + shortestPath[edge[0]][path[1]]); curr += currPath; } best = Math.min(curr, best); } out.println(best); out.close(); } private static class ArrayComparator implements Comparator<int[]> { @Override public int compare(int[] o1, int[] o2) { return Integer.compare(o1[1], o2[1]); } } }
Java
["6 5 2\n1 2 5\n2 3 7\n2 4 4\n4 5 2\n4 6 8\n1 6\n5 3", "5 5 4\n1 2 5\n2 3 4\n1 4 3\n4 3 7\n3 5 2\n1 5\n1 3\n3 3\n1 5"]
1 second
["22", "13"]
NoteThe picture corresponding to the first example:There, you can choose either the road $$$(2, 4)$$$ or the road $$$(4, 6)$$$. Both options lead to the total cost $$$22$$$.The picture corresponding to the second example:There, you can choose the road $$$(3, 4)$$$. This leads to the total cost $$$13$$$.
Java 11
standard input
[ "graphs", "brute force", "shortest paths" ]
6ccb639373ca04646be8866273402c93
The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 1000$$$; $$$n - 1 \le m \le min(1000, \frac{n(n-1)}{2})$$$; $$$1 \le k \le 1000$$$) β€” the number of districts, the number of roads and the number of courier routes. The next $$$m$$$ lines describe roads. The $$$i$$$-th road is given as three integers $$$x_i$$$, $$$y_i$$$ and $$$w_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \ne y_i$$$; $$$1 \le w_i \le 1000$$$), where $$$x_i$$$ and $$$y_i$$$ are districts the $$$i$$$-th road connects and $$$w_i$$$ is its cost. It is guaranteed that there is some path between each pair of districts, so the city is connected. It is also guaranteed that there is at most one road between each pair of districts. The next $$$k$$$ lines describe courier routes. The $$$i$$$-th route is given as two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$) β€” the districts of the $$$i$$$-th route. The route can go from the district to itself, some couriers routes can coincide (and you have to count them independently).
2,100
Print one integer β€” the minimum total courier routes cost you can achieve (i.e. the minimum value $$$\sum\limits_{i=1}^{k} d(a_i, b_i)$$$, where $$$d(x, y)$$$ is the cheapest cost of travel between districts $$$x$$$ and $$$y$$$) if you can make some (at most one) road cost zero.
standard output
PASSED
3fed435b745e712f7dbdc6b2c8a028a6
train_004.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.util.*; import java.io.*; public class Main { 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 main(String args[]) throws IOException { Scan input=new Scan(); StringBuilder str=new StringBuilder(input.scanString()); System.out.println(solve(str)); } public static StringBuilder solve(StringBuilder str) { StringBuilder ans=new StringBuilder(""); boolean prev=false; for(int i=0;i<str.length();i++) { int j=i,count=0; while(j<str.length() && str.charAt(j)==str.charAt(i)) { count++; j++; } if(count>=3 && !prev) { ans.append(str.charAt(i)); ans.append(str.charAt(i)); prev=true; } else if(count>=3 && prev) { ans.append(str.charAt(i)); prev=false; } else if(count==2 && prev) { ans.append(str.charAt(i)); prev=false; } else if(count==2) { ans.append(str.charAt(i)); ans.append(str.charAt(i)); prev=true; } else if(count==1) { ans.append(str.charAt(i)); prev=false; } i=j-1; } return ans; } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 11
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
41fe345804b264dae2125c4a33dbbc98
train_004.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.util.*; import java.io.*; public class Codeforces { public static void main(String args[])throws Exception { BufferedReader bu=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb=new StringBuilder(); char s[]=bu.readLine().toCharArray(); int i,n=s.length,l=1; char cur=s[0]; boolean doub=false; for(i=1;i<n;i++) if(s[i]==cur) l++; else { if(l==1) {sb.append(cur); doub=false;} else { if(doub) {sb.append(cur); doub=false;} else {sb.append(""+cur+cur); doub=true;} } l=1; cur=s[i]; } if(l==1) sb.append(cur); else { if(doub) sb.append(cur); else sb.append(""+cur+cur); } System.out.print(sb); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 11
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
38d0648fdc0ac46ea6720041874cc107
train_004.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Random; public class Solution { public static void main(String[] args) { try (PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out))) { _Scanner sc = new _Scanner(System.in); String s = sc.next(); List<Character> chars = new ArrayList<>(); List<Integer> freqs = new ArrayList<>(); chars.add(s.charAt(0)); freqs.add(1); for (int i = 1; i < s.length(); i++) { char c = s.charAt(i); if (c == chars.get(chars.size() - 1)) { freqs.set(freqs.size() - 1, 2); } else { chars.add(c); freqs.add(1); } } boolean del = false; for (int i = 0; i < chars.size(); i++) { Character c = chars.get(i); if (del) { if (freqs.get(i) == 2) { freqs.set(i, 1); } } del = false; for (int j = 0; j < freqs.get(i); j++) { out.print(c); } if (freqs.get(i) == 2) { del = true; } } out.println(); } } private static void reverse(int[] vs) { for (int i = 0; i < vs.length / 2; i++) { swap(vs, i, vs.length - 1 - i); } } static class _Scanner { InputStream is; _Scanner(InputStream is) { this.is = is; } byte[] bb = new byte[1 << 15]; int k, l; byte getc() { try { if (k >= l) { k = 0; l = is.read(bb); if (l < 0) return -1; } return bb[k++]; } catch (IOException e) { throw new RuntimeException(e); } } byte skip() { byte b; while ((b = getc()) <= 32) ; return b; } int nextInt() { int n = 0; int sig = 1; for (byte b = skip(); b > 32; b = getc()) { if (b == '-') { sig = -1; } else { n = n * 10 + b - '0'; } } return sig * n; } long nextLong() { long n = 0; long sig = 1; for (byte b = skip(); b > 32; b = getc()) { if (b == '-') { sig = -1; } else { n = n * 10 + b - '0'; } } return sig * n; } public String next() { StringBuilder sb = new StringBuilder(); for (int b = skip(); b > 32; b = getc()) { sb.append(((char) b)); } return sb.toString(); } } private static void shuffle(int[] ar) { Random rnd = new Random(); for (int i = 0; i < ar.length; i++) { int j = i + rnd.nextInt(ar.length - i); swap(ar, i, j); } } private static void shuffle(Object[] ar) { Random rnd = new Random(); for (int i = 0; i < ar.length; i++) { int j = i + rnd.nextInt(ar.length - i); swap(ar, i, j); } } private static void swap(int[] ar, int i, int j) { int t = ar[i]; ar[i] = ar[j]; ar[j] = t; } private static void swap(Object[] ar, int i, int j) { Object t = ar[i]; ar[i] = ar[j]; ar[j] = t; } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 11
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
7c518d8ec65e7c734ce74ce8083f267d
train_004.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import javax.swing.plaf.synth.SynthSeparatorUI; public class temp1 { static long sx = 0, sy = 0, m = (long) (1e9 + 7); static ArrayList<Integer>[] a; static long[][] dp; static boolean b = true; static HashMap<Long, Integer> hm = new HashMap<>(); static ArrayList<Integer> p = new ArrayList<>(); static ArrayList<pair> ans = new ArrayList<>(); public static void main(String[] args) throws IOException { // Reader scn = new Reader(); Scanner scn = new Scanner(System.in); String s = scn.next(); ArrayList<pair> p = new ArrayList<>(); for (char ch : s.toCharArray()) { if (p.size() == 0 || p.get(p.size() - 1).ch != ch) { p.add(new pair(ch)); p.get(p.size() - 1).cnt++; } else { p.get(p.size() - 1).cnt++; } } for (pair rp : p) { if (rp.cnt > 2) rp.cnt = 2; } for (int i = 1; i < p.size(); i++) { if (p.get(i).cnt == 2 && p.get(i - 1).cnt == 2) p.get(i).cnt = 1; } StringBuilder sb = new StringBuilder(); for (pair rp : p) { while (rp.cnt-- > 0) sb.append(rp.ch); } System.out.println(sb); } // _________________________TEMPLATE_____________________________________________________________ // private static int gcd(int a, int b) { // if(a== 0) // return b; // // return gcd(b%a,a); // } // static class comp implements Comparator<pair> { // // @Override // public int compare(pair o1, pair o2) { // // return (int) (o1.y - o1.y); // } // // } private static class pair implements Comparable<pair> { char ch; int cnt; pair(char a) { ch = a; } @Override public int compareTo(pair o) { return 1; } } public static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[100000 + 1]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } 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; din.close(); } 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 int[][] nextInt2DArray(int m, int n) throws IOException { int[][] arr = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) arr[i][j] = nextInt(); } return arr; } // kickstart - Solution // atcoder - Main } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 11
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
2677aa25e503ccbfe928dd6127f8b8e3
train_004.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.util.Scanner; public class CodeForces { public static void main(String[] args) { Scanner in =new Scanner(System.in); String string=in.nextLine(); StringBuilder last=new StringBuilder(); StringBuilder tempAnswer=new StringBuilder(); for (char c:string.toCharArray()) { if (last.length()>1) { int size=last.length(); if (last.charAt(size-1)==last.charAt(size-2) && last.charAt(size-2) == c) continue; else { last.append(c); tempAnswer.append(c); } } else { last.append(c); tempAnswer.append(c); } } long lastOcc=1,currentOcc=1; StringBuilder answer= new StringBuilder(); char current=' '; for(char c:tempAnswer.toString().toCharArray()) { if(c != current) { current=c; lastOcc=currentOcc; currentOcc=1; answer.append(c); } else { if (currentOcc<=2 && lastOcc<2) { ++currentOcc; answer.append(c); } } } System.out.println(answer); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 11
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
7dd71a4ddee1e866090230dc6973c46e
train_004.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.util.*; import java.io.*; public class Main { 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; } } public static void main(String[] args) throws IOException { Reader sc=new Reader();Main G=new Main(); PrintWriter o = new PrintWriter(System.out); String s=sc.next();int c=0;int n=s.length(); StringBuilder s1=new StringBuilder(); StringBuilder s2=new StringBuilder(); for (int i=0;i<n-1;i++) { if (s.charAt(i)!=s.charAt(i+1)) c=0; else c++; if (c<2)s1.append(s.charAt(i)); } s1.append(s.charAt(n-1));n=s1.length(); //o.println(s1); int i; for (i=0;i<n-3;i++) { if (s1.charAt(i)!=s1.charAt(i+1)) s2.append(s1.charAt(i)); else if (s1.charAt(i+2)==s1.charAt(i+3)) { //o.println(i); s2.append(s1.charAt(i));s2.append(s1.charAt(i+1)); s2.append(s1.charAt(i+3)); i=i+3; } else {s2.append(s1.charAt(i));s2.append(s1.charAt(i+1));i++;} } for (;i<n;i++)s2.append(s1.charAt(i)); //o.println(s1); o.println(s2); //o.println("abbcbbcbbzbbcbbcbbxybbcbbcbb"); o.flush(); o.close(); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 11
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
925d3af2939d86ee6eb6d0e81f9dc5f0
train_004.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.util.*; public class Codeforces363C { public static void main(String[] args) { Scanner sc=new Scanner(System.in); //random characters char a , b = '.', c ='*', d = '+'; String s = sc.next(); sc.close(); for(int i = 0;i < s.length(); i++){ a = s.charAt(i); if(!((a==b&&b==c)||(a==b&&c==d))){ System.out.print(a); d=c; c=b; b=a; } } System.out.println(); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 11
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
d7701ea10aba22971716b0b0b62daa37
train_004.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
//https://codeforces.com/problemset/problem/363/C //C. Fixing Typos import java.util.*; import java.io.*; public class Fixing_Typos{ public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); StringBuilder sb = new StringBuilder(br.readLine().trim()); for(int i=1;i<sb.length();i++) { if(sb.charAt(i)==sb.charAt(i-1)){ int j = i; while(j+1<sb.length() && sb.charAt(j)==sb.charAt(j+1)) j++; if(j!=i) sb.delete(i+1,j+1); } } for(int i=1;i+2<sb.length();i++) { if(sb.charAt(i)==sb.charAt(i-1) && sb.charAt(i+1)==sb.charAt(i+2)) sb.deleteCharAt(i+1); } // String s = br.readLine().trim(); // char ch[] = s.toCharArray(); // int i = 0,j = 1; // boolean flag = false; // while(true && j<ch.length){ // if(flag && ch[i]==ch[j]){ // ch[i] = ' '; // i++; // j++; // } // else if(ch[i]==ch[j]){ // flag = true; // j++; // } // else if(ch[i]!=ch[j]){ // if(flag){ // if(j+1<ch.length && ch[j]==ch[j+1]){ // ch[j]=' '; // j++; // } // else{ // flag = false; // i = j; // j++; // } // } // else{ // i++; // j++; // } // } // } // for(int k=0;k<ch.length;k++) // if(ch[k]!=' ') // sb.append(ch[k]); pw.print(sb); pw.flush(); pw.close(); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 11
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
da61b003c709c079c02ed2b126f4949a
train_004.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
//https://codeforces.com/problemset/problem/363/C //C. Fixing Typos import java.util.*; import java.io.*; public class Fixing_Typos{ public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); StringBuilder sb = new StringBuilder(); String s = br.readLine().trim(); char ch[] = s.toCharArray(); int i = 0,j = 1; boolean flag = false; while(true && j<ch.length){ if(flag && ch[i]==ch[j]){ ch[i] = ' '; i++; j++; } else if(ch[i]==ch[j]){ flag = true; j++; } else if(ch[i]!=ch[j]){ if(flag){ if(j+1<ch.length && ch[j]==ch[j+1]){ ch[j]=' '; j++; } else{ flag = false; i = j; j++; } } else{ i++; j++; } } } for(int k=0;k<ch.length;k++) if(ch[k]!=' ') sb.append(ch[k]); pw.print(sb); pw.flush(); pw.close(); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 11
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
5659d1c6d12579cb9c52a8dd139b6b03
train_004.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top * * @author https://codeforces.com/ */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, Scanner in, PrintWriter out) { char a, b = 0, c = 1, d = 2; String s = in.nextLine(); for (int i = 0; i < s.length(); i++) { a = s.charAt(i); if (!(a == b && b == c) && !(a == b && c == d)) { out.print(a); d = c; c = b; b = a; } } } } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 11
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
af6304ce86645eeb9279f34516d96e3a
train_004.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); CFixingTypos solver = new CFixingTypos(); solver.solve(1, in, out); out.close(); } static class CFixingTypos { public void solve(int testNumber, InputReader in, OutputWriter out) { String s = in.nextString(); StringBuilder ans = new StringBuilder(); int currC = 0; int prevC = 0; char cch = '-'; if (s.length() < 3) { out.println(s); return; } for (int i = 0; i < s.length(); i++) { if (cch == s.charAt(i)) { currC++; } else { cch = s.charAt(i); prevC = currC; currC = 1; } if (prevC >= 2 && currC >= 2) { currC--; continue; } if (prevC < 2 && currC > 2) { currC--; continue; } ans.append(s.charAt(i)); } out.println(ans); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; ++i) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 11
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
04fc2281dd1e03876fe9d22671974c91
train_004.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); CFixingTypos solver = new CFixingTypos(); solver.solve(1, in, out); out.close(); } static class CFixingTypos { public void solve(int testNumber, InputReader in, OutputWriter out) { String s = in.nextString(); StringBuilder ans = new StringBuilder(); int currC = 0; int prevC = 0; char cch = '-'; char pch = '-'; if (s.length() < 3) { out.println(s); return; } for (int i = 0; i < s.length(); i++) { if (cch == s.charAt(i)) { currC++; } else { cch = s.charAt(i); prevC = currC; currC = 1; } if (prevC >= 2 && currC >= 2) { currC--; continue; } if (prevC < 2 && currC > 2) { continue; } ans.append(s.charAt(i)); } out.println(ans); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; ++i) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 11
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
0a5e59f11732627de0196eb39dc674ae
train_004.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; public class Main implements Runnable { static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new Main(),"Main",1<<27).start(); } static class Pair{ int nod; int ucn; Pair(int nod,int ucn){ this.nod=nod; this.ucn=ucn; } public static Comparator<Pair> wc = new Comparator<Pair>(){ public int compare(Pair e1,Pair e2){ //reverse order if(e1.ucn < e2.ucn) return 1; // 1 for swaping. else if (e1.ucn > e2.ucn) return -1; else{ // if(e1.siz>e2.siz) // return 1; // else // return -1; return 0; } } }; } public static long gcd(long a,long b){ if(b==0)return a; else return gcd(b,a%b); } ////recursive BFS public static int bfsr(int s,ArrayList<Integer>[] a,boolean[] b,int[] pre){ b[s]=true; int p = 1; int n = pre.length -1; int t = a[s].size(); int max = 1; for(int i=0;i<t;i++){ int x = a[s].get(i); if(!b[x]){ //dist[x] = dist[s] + 1; int xz = (bfsr(x,a,b,pre)); p+=xz; max = Math.max(xz,max); } } max = Math.max(max,(n-p)); pre[s] = max; return p; } //// iterative BFS public static int bfs(int s,ArrayList<Integer>[] a,int[] dist,boolean[] b,PrintWriter w){ b[s]=true; int siz = 0; Queue<Integer> q = new LinkedList<>(); q.add(s); while(q.size()!=0){ int i=q.poll(); Iterator<Integer> it = a[i].listIterator(); int z=0; while(it.hasNext()){ z=it.next(); if(!b[z]){ b[z]=true; dist[z] = dist[i] + 1; siz++; q.add(z); } } } return siz; } public static int lower(int key, int[] a){ int l = 0; int r = a.length-1; int res = 0; while(l<=r){ int mid = (l+r)/2; if(a[mid]<=key){ l = mid+1; res = mid+1; } else{ r = mid -1; } } return res; } ////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////// public void run() { InputReader sc = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int defaultValue=0; // int tc = sc.nextInt(); // while(tc-->0){ char[] s = sc.next().toCharArray(); int n = s.length; boolean f = false; ArrayList<Character> ans = new ArrayList<Character>(); ans.add(s[0]); for(int i=1;i<n;i++){ if(s[i]==ans.get(ans.size()-1)){ if(f){ continue; } else{ ans.add(s[i]); f = true; } } else{ f = false; ans.add(s[i]); } } int j = 0; ArrayList<Character> a = new ArrayList<Character>(); n = ans.size(); for(int i=0;i<n;i++){ int x = a.size(); if(i>1 && i<n-1){ if(a.get(x-1)==a.get(x-2)){ if(ans.get(i)==ans.get(i+1)){ continue; } else{ a.add(ans.get(i)); } } else{ a.add(ans.get(i)); } } else {a.add(ans.get(i));} } for(int i=0;i<a.size();i++){ w.print(a.get(i)); } //} w.flush(); w.close(); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 11
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
8133f1b08a9b0384a52209a152e74a39
train_004.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class CF363C { static BufferedReader __in; static PrintWriter __out; static StringTokenizer input; public static void main(String[] args) throws IOException { __in = new BufferedReader(new InputStreamReader(System.in)); __out = new PrintWriter(new OutputStreamWriter(System.out)); char[] s = rcha(); StringBuilder ans = new StringBuilder(); int rep = 0, next = 2; for(int i = 0; i < s.length; ++i) { if(i == 0 || s[i] != s[i - 1]) { if(rep == 2) { // if previous 2 repeating, next 2 cannot be same next = 1; } else { // next 2 repeating ok next = 2; } rep = 1; // new character, reset repetition ans.append(s[i]); } else { if(rep < next) { // up to 2 repeating ans.append(s[i]); ++rep; } } } prln(ans); close(); } // references // IBIG = 1e9 + 7 // IRAND ~= 3e8 // IMAX ~= 2e10 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IRAND = 327859546; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));} static int minstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));} static long minstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));} static int maxstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));} static long maxstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));} static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int floori(double d) {return (int)d;} static int ceili(double d) {return (int)ceil(d);} static long floorl(double d) {return (long)d;} static long ceill(double d) {return (long)ceil(d);} // input static void r() throws IOException {input = new StringTokenizer(__in.readLine());} static int ri() throws IOException {return Integer.parseInt(__in.readLine());} static long rl() throws IOException {return Long.parseLong(__in.readLine());} static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;} static char[] rcha() throws IOException {return __in.readLine().toCharArray();} static String rline() throws IOException {return __in.readLine();} static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());} static int ni() {return Integer.parseInt(input.nextToken());} static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());} static long nl() {return Long.parseLong(input.nextToken());} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {__out.println("yes");} static void pry() {__out.println("Yes");} static void prY() {__out.println("YES");} static void prno() {__out.println("no");} static void prn() {__out.println("No");} static void prN() {__out.println("NO");} static void pryesno(boolean b) {__out.println(b ? "yes" : "no");}; static void pryn(boolean b) {__out.println(b ? "Yes" : "No");} static void prYN(boolean b) {__out.println(b ? "YES" : "NO");} static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); __out.println(iter.next());} static void flush() {__out.flush();} static void close() {__out.close();}}
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 11
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
017f14604530e2bbac9a1b56b4a9e19b
train_004.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import com.sun.source.tree.Tree; import java.math.BigInteger; import java.sql.Array; 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 Solution { static long MOD=1000000007; // Complete the maximumSum function below. public static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static long gcd(long a, long b) { if (b == 0) return a; long r = a % b; return gcd(b, r); } static long lcm(long a, long b) { return (a * b) / gcd(a, b); } public class ListNode { int val; ListNode next; ListNode() { } ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; } } public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() { } TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } } class Node { public int val; public List<Node> children; public Node() { } public Node(int _val) { val = _val; } public Node(int _val, List<Node> _children) { val = _val; children = _children; } } static class Pair{ long key,value; public Pair(long a,long b){ key=a; value=b; } @Override public String toString() { return "Pair{" + "key=" + key + ", value=" + value + '}'; } } static int nearest_power_of_2(int k){ int op=0; while (k>1){ k/=2; op++; } return op; } static long getLength(long x){ int p=0; while (x>0){ p++; x/=2; } p--; long val=0; while (p>0){ p--; val+=Math.pow(2,p); } return val; } static long theGreatXor(long x) { long val=getLength(x); val^=x; val=Long.bitCount(val); return val; } public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader scanner = new InputReader(inputStream); PrintWriter w = new PrintWriter(outputStream); String a=scanner.next(); StringBuilder op=new StringBuilder(); char ans[]=new char[a.length()]; int idx=0; for(int i=0;i<a.length();i++){ ans[idx++]=a.charAt(i); if(idx>=3&&(ans[idx-1]==ans[idx-2])&&(ans[idx-2]==ans[idx-3])) idx--; else if(idx>=4&&(ans[idx-1]==ans[idx-2])&&(ans[idx-3]==ans[idx-4])) idx--; } for(int i=0;i<idx;i++) op.append(ans[i]); w.println(op); w.close(); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 11
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
a466f8eb4ce7762bcadf5f8c9a4ce409
train_004.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.util.Scanner; public class fixingTypos { public static void main(String[] args) { Scanner sc = new Scanner(System.in); StringBuilder s = new StringBuilder(sc.next()); for (int i = 1; i < s.length(); i++) { int j = i; if (s.charAt(j) == s.charAt(i - 1)) { while (j < s.length() && s.charAt(j) == s.charAt(i - 1)) { ++j; } s.delete(i + 1, j); } } for (int i = 1; i < s.length() - 1;) { if ((s.charAt(i) == s.charAt(i - 1)) && s.charAt(i) == s.charAt(i + 1)) { s.deleteCharAt(i); } else if ((i >= 2 && s.charAt(i - 1) == s.charAt(i - 2)) && s.charAt(i) == s.charAt(i + 1)) { s.deleteCharAt(i); } else { i++; } } System.out.println(s); sc.close(); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 11
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
505df343e24e6743c675ff0817f0ffe2
train_004.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.util.*; import java.io.*; public class Main{ static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.nextInt(); return array; } } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static int mod = (int)(1e9+7); public static long pow(long a,long b) { long ans = 1; while(b> 0) { if((b & 1)==1){ ans = (ans*a) % mod; } a = (a*a) % mod; b = b>>1; } return ans; } public static void main(String[] args) { InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); //IOUtils io = new IOUtils(); char[] s = in.nextLine().toCharArray(); int prevcount=0,curcount = 0; //int[] count = new int[26]; StringBuilder sb = new StringBuilder(); int c=-1; for(int i=0;i<s.length;i++) { if(c>=2 && sb.charAt(c-2)==sb.charAt(c-1) && sb.charAt(c)==s[i]) continue; if(c>=1 && sb.charAt(c)==sb.charAt(c-1) && sb.charAt(c)==s[i]) continue; sb.append(s[i]); c++; } out.printLine(sb); out.flush(); out.close(); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 11
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
3c3d91df0534c64c279886013834fe33
train_004.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf363c { public static void main(String[] args) throws IOException { char[] s = rcha(); int n = s.length; StringBuilder ans = new StringBuilder(); int lim = 2, cnt = 0; for(int i = 0; i < n; ++i) { if(i == 0 || s[i] != s[i - 1]) { if(cnt == 2) { lim = 1; } else { lim = 2; } cnt = 1; ans.append(s[i]); } else { if(cnt < lim) { ans.append(s[i]); ++cnt; } } } prln(ans); close(); } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random rand = new Random(); // references // IBIG = 1e9 + 7 // IRAND ~= 3e8 // IMAX ~= 2e10 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IRAND = 327859546; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));} static int minstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));} static long minstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));} static int maxstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));} static long maxstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));} static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int floori(double d) {return (int)d;} static int ceili(double d) {return (int)ceil(d);} static long floorl(double d) {return (long)d;} static long ceill(double d) {return (long)ceil(d);} static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static <T> void shuffle(T[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); T swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void sort(int[] a) {shuffle(a); Arrays.sort(a);} static void sort(long[] a) {shuffle(a); Arrays.sort(a);} static void sort(double[] a) {shuffle(a); Arrays.sort(a);} static void qsort(int[] a) {Arrays.sort(a);} static void qsort(long[] a) {Arrays.sort(a);} static void qsort(double[] a) {Arrays.sort(a);} static int randInt(int min, int max) {return rand.nextInt(max - min + 1) + min;} // input static void r() throws IOException {input = new StringTokenizer(__in.readLine());} static int ri() throws IOException {return Integer.parseInt(__in.readLine());} static long rl() throws IOException {return Long.parseLong(__in.readLine());} static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;} static char[] rcha() throws IOException {return __in.readLine().toCharArray();} static String rline() throws IOException {return __in.readLine();} static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());} static int ni() {return Integer.parseInt(input.nextToken());} static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());} static long nl() {return Long.parseLong(input.nextToken());} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {__out.println("yes");} static void pry() {__out.println("Yes");} static void prY() {__out.println("YES");} static void prno() {__out.println("no");} static void prn() {__out.println("No");} static void prN() {__out.println("NO");} static void pryesno(boolean b) {__out.println(b ? "yes" : "no");}; static void pryn(boolean b) {__out.println(b ? "Yes" : "No");} static void prYN(boolean b) {__out.println(b ? "YES" : "NO");} static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); if(n >= 0) __out.println(iter.next());} static void h() {__out.println("hlfd");} static void flush() {__out.flush();} static void close() {__out.close();} }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 11
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
9a04107a7cde574ea427d3dd9c65869e
train_004.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import javax.swing.*; import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { static PrintWriter out=new PrintWriter(System.out); public static void main(String[] args) throws IOException { //BufferedReader reader=new BufferedReader(new FileReader("input.txt")); //PrintWriter pw=new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); //Scanner scanner=new Scanner(System.in); //Reader sc = new Reader(); String s=reader.readLine(); StringBuilder ans= new StringBuilder(); for (int i = 0; i <s.length() ; i++) { boolean a=true,b=true; int l=ans.length(); if (l>1) if (s.charAt(i)==ans.charAt(l-1) && s.charAt(i)==ans.charAt(l-2)){ a=false; } if (l>2) if (s.charAt(i)==ans.charAt(l-1) && ans.charAt(l-2)==ans.charAt(l-3)){ b=false; } if (a && b) ans.append(s.charAt(i)); } out.println(ans); out.close(); } static long nextLucky(long n){ char[] s=String.valueOf(n).toCharArray(); for (int i = s.length-1; i >=0 ; i--) { if (s[i]=='4'){ s[i]='7'; for (int j = i+1; j <s.length ; j++) { s[j]='4'; } break; } else if (i==0){ Arrays.fill(s,'4'); return Long.parseLong("4"+String.valueOf(s)); } } return Long.parseLong(String.valueOf(s)); } static boolean isLucky(long n){ char[] s=String.valueOf(n).toCharArray(); int four=0,seven=0; for (int i = 0; i <s.length ; i++) { if (s[i]!='4' && s[i]!='7') return false; if (s[i]=='4')four++; if (s[i]=='7')seven++; } return four==seven; } static int kadens(int[] a,int x){ int maxSoFar=0; int maxEndHere=0; int count=0; boolean found=false; for (int i = 0; i <a.length ; i++) { maxEndHere+=a[i]; count++; if (maxEndHere%x==0){ maxEndHere=a[i]; count=1; } else found=true; if (maxSoFar<count) maxSoFar=count; } if (found) return maxSoFar; else return -1; } static int gcd(int a,int b){ if (b==0) return a; return gcd(b,a%b); } static boolean ok(int n){ if (n%2==0 || n%3==0 || n%5==0) return true; else return false; } static int find(int n,int[] p){ if (p[n]==n)return n; return p[n]=find(p[n],p); } static void union(int a,int b,int[] p,int[] level){ int aRoot=find(a,p); int bRoot=find(b,p); if (aRoot==bRoot)return; p[bRoot]=aRoot; level[aRoot]+=level[bRoot]; } } class node implements Comparable<node>{ Integer no; Integer cost; Vector<node> adj=new Vector<>(); public node(Integer no, Integer cost) { this.no = no; this.cost = cost; } @Override public String toString() { return "node{" + "no=" + no + ", cost=" + cost + '}'; } @Override public int compareTo(node o) { return o.cost-this.cost; } } class edge implements Comparable<edge>{ tuple u; Double cost; public edge(tuple u, Double cost) { this.u = u; this.cost = cost; } @Override public int compareTo(edge o) { return this.cost.compareTo(o.cost); } @Override public String toString() { return "edge{" + "u=" + u + ", cost=" + cost + '}'; } } ///* class tuple implements Comparable<tuple>{ int a; int b; tuple(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(tuple o) { return (this.a-o.a); } @Override public String toString() { return "tuple{" + "a=" + a + ", b=" + b + '}'; } } //*/ class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } 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; din.close(); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 11
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
1e74eb948ec124fa0a8dc71dc51a2ed8
train_004.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.util.InputMismatchException; import java.io.InputStreamReader; import java.io.BufferedOutputStream; import java.util.StringTokenizer; import java.io.Closeable; import java.io.BufferedReader; import java.io.InputStream; import java.io.Flushable; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; Input in = new Input(inputStream); Output out = new Output(outputStream); CFixingTypos solver = new CFixingTypos(); solver.solve(1, in, out); out.close(); } } public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1<<29); thread.start(); thread.join(); } static class CFixingTypos { public CFixingTypos() { } public void solve(int kase, Input in, Output pw) { String s = in.next(); StringBuilder ans = new StringBuilder(); boolean dup = false; for(int i = 0; i<s.length(); i++) { if(i<=1) { ans.append(s.charAt(i)); }else { char last = ans.charAt(ans.length()-1), cur = s.charAt(i); if(cur==last&&cur==ans.charAt(ans.length()-2)) { }else if(i>=3&&cur==last&&ans.charAt(ans.length()-2)==ans.charAt(ans.length()-3)) { }else { ans.append(cur); } } } pw.println(ans); } } static class Input { BufferedReader br; StringTokenizer st; public Input(InputStream is) { this(is, 1<<20); } public Input(InputStream is, int bs) { br = new BufferedReader(new InputStreamReader(is), bs); st = null; } public boolean hasNext() { try { while(st==null||!st.hasMoreTokens()) { String s = br.readLine(); if(s==null) { return false; } st = new StringTokenizer(s); } return true; }catch(Exception e) { return false; } } public String next() { if(!hasNext()) { throw new InputMismatchException(); } return st.nextToken(); } } static class Output implements Closeable, Flushable { public StringBuilder sb; public OutputStream os; public int BUFFER_SIZE; public boolean autoFlush; public String LineSeparator; public Output(OutputStream os) { this(os, 1<<16); } public Output(OutputStream os, int bs) { BUFFER_SIZE = bs; sb = new StringBuilder(BUFFER_SIZE); this.os = new BufferedOutputStream(os, 1<<17); autoFlush = false; LineSeparator = System.lineSeparator(); } public void print(String s) { sb.append(s); if(autoFlush) { flush(); }else if(sb.length()>BUFFER_SIZE >> 1) { flushToBuffer(); } } public void println(Object... o) { for(int i = 0; i<o.length; i++) { if(i!=0) { print(" "); } print(String.valueOf(o[i])); } println(); } public void println() { sb.append(LineSeparator); } private void flushToBuffer() { try { os.write(sb.toString().getBytes()); }catch(IOException e) { e.printStackTrace(); } sb = new StringBuilder(BUFFER_SIZE); } public void flush() { try { flushToBuffer(); os.flush(); }catch(IOException e) { e.printStackTrace(); } } public void close() { flush(); try { os.close(); }catch(IOException e) { e.printStackTrace(); } } } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 11
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
e75c5bef4678c00c44c41371ab10ad81
train_004.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class FixingTypos { public static void main(String[] args) throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String str = bf.readLine(); StringBuilder ans = new StringBuilder(); char temp; for (int i = 0; i < str.length(); i++) { temp = str.charAt(i); if (i>1&&str.charAt(i-2)==str.charAt(i-1)&&str.charAt(i-1)==str.charAt(i)) continue; if (ans.length()>2&&ans.charAt(ans.length()-1)==temp&&ans.charAt(ans.length()-2)==ans.charAt(ans.length()-3)) continue; ans.append(temp); } System.out.print(ans); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 11
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
96e154534e9fb3c0aeb36aae806667bc
train_004.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java .io.*; import java.util.*; import java.lang.*; public class RATHOD { public static void main (String[] args) { Scanner sc=new Scanner(System.in); String str=sc.next(); str=str+"*"; int i; char prevch=str.charAt(0); int count=1; char ch; int prevchcount=0; for(i=1;i<str.length();i++) { ch=str.charAt(i); if(ch==prevch) count++; else { if(count>=2) { if(prevchcount<2) { System.out.print(prevch+""+prevch); prevchcount=2; prevch=ch; } else { System.out.print(prevch); prevchcount=1; prevch=ch; } } else { System.out.print(prevch); prevchcount=1; prevch=ch; } count=1; } } } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 11
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
50b093822489474aeba84c841a82f9d4
train_004.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.util.*; import java.io.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.next(); int N = s.length(); StringBuilder ans=new StringBuilder(); int index=0; int prevcount=0; while(index<N) { char ch=s.charAt(index); int count=0; while(index<N&&s.charAt(index)==ch) { index++; count++; } if(prevcount>=2) { count=1; } else{ count=Math.min(count,2); } for(int i=0;i<count;i++) { ans.append(ch); } prevcount=count; } System.out.print(ans); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 11
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
1fc0f10c030d93731455156b5e29f80a
train_004.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.util.*; import java.io.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.next(); int N = s.length(); // 3 in a row // Multiple followed by multiple. // Go through each group of characters. // Keep track of repeat of previous group. StringBuilder sb = new StringBuilder(); int prevCount = 0; int index = 0; while (index < N) { char c = s.charAt(index); int count = 0; while (index < N && s.charAt(index) == c) { index++; count++; } if (prevCount >= 2) { count = 1; // No matter what, must be single. } else { // Make sure les than 3 in a row. count = Math.min(count, 2); } for (int i = 0; i < count; i++) { sb.append(c); } prevCount = count; } System.out.println(sb.toString()); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 11
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
995f4b1d4a47a31b04da4f1a58a0b78b
train_004.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { static boolean FROM_FILE = false; static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { if (FROM_FILE) { try { br = new BufferedReader(new FileReader("input.txt")); } catch (IOException error) { } } else { 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 fr = new FastReader(); PrintWriter out = null; if (FROM_FILE) { try { out = new PrintWriter(new FileWriter("output.txt")); } catch (IOException error) { } } else { out = new PrintWriter(new OutputStreamWriter(System.out)); } char[] str = fr.nextLine().toCharArray(); int n = str.length; int i = 0, prev_two = 0, res = 0; StringBuilder sb = new StringBuilder(); while (i < n) { int j = i + 1; while (j < n && str[j] == str[i]) j += 1; int len = j - i; if (len >= 2) { int s = sb.length(); if (s >= 2 && sb.charAt(s - 1) == sb.charAt(s - 2)) sb.append(str[i]); else sb.append(str[i]).append(str[i]); } else { sb.append(str[i]); } i = j; } out.println(sb.toString()); out.flush(); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 11
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
bd24a5e9bb943049df7d3832086d403e
train_004.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.util.*; import java.io.*; public class Main{ public static void main(String []args){ Scanner sc = new Scanner(System.in); String s=sc.nextLine(); int count=1; boolean check=false; for(int i=0;i<s.length()-1;i++){ if(s.charAt(i)==s.charAt(i+1)) count++; else{ if(count>1){ if(check){ System.out.print(Character.toString(s.charAt(i))); check=false; } else{ System.out.print(Character.toString(s.charAt(i))+Character.toString(s.charAt(i))); check=true; } } else{ System.out.print(Character.toString(s.charAt(i))); check=false; } count=1; } } if(count>1){ if(check) System.out.print(Character.toString(s.charAt(s.length()-1))); else System.out.print(Character.toString(s.charAt(s.length()-1))+Character.toString(s.charAt(s.length()-1))); } else{ System.out.print(Character.toString(s.charAt(s.length()-1))); } } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 11
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
b2f852bf1e6ff68e1b0224b2e60677ec
train_004.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.io.*; import java.util.*; public class main { static StringBuilder out=new StringBuilder(); static FastReader in=new FastReader(); public static int[] getIntArray(int n){ int arr[]=new int[n]; for(int i=0;i<n;i++){ arr[i]=in.nextInt(); } return arr; } static int m=(int)(1e9 + 7); static int [][]t; static boolean isDiv[]=new boolean[100001]; public static void solve(){ char s[]=in.nextLine().toCharArray(); int n=s.length; int preCount=0; int currCount=0; for(int i=0;i<s.length;){ if(i==n-1 || s[i+1]!=s[i] || s[i]==Character.MIN_VALUE){ preCount=1; i++; continue; } currCount=2; int j=i+2; while(j<n && s[j]==s[i]){ s[j]=Character.MIN_VALUE; j++; } if(preCount==2){ s[i+1]=Character.MIN_VALUE; preCount=1; }else{ preCount=2; } i=j; } for(char a:s){ if(a==Character.MIN_VALUE)continue; out.append(a); } } public static void main(String args[]){ int t=1; while(t-->0){ solve(); out.append('\n'); } System.out.println(out); } } 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
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 11
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
1c096ef5377e46061ff43a64ac40fc64
train_004.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class C { static MyScanner in = new MyScanner(); static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); static long H,W; static BitSet bs; static long mod = 1000000007; public static void main(String args[]) throws IOException { String line = in.next(); int n= line.length(); ArrayList<Integer> list = new ArrayList<>(); ArrayList<Character> chars = new ArrayList<>(); for(int i=0;i<line.length();i++){ char candiante = line.charAt(i); int c = 1; for(int j=i+1;j<line.length();j++){ if(candiante==line.charAt(j)){ c++; }else{ break; } } i+=(c-1); list.add(c); chars.add(candiante); } // for(int i=0;i<list.size();i++){ if(list.get(i)>=3){ list.set(i, 2); } } for(int i=0;i<list.size()-1;i++){ if(list.get(i)==2&&list.get(i+1)==2){ list.set(i+1,1); } } for(int i=0;i<list.size();i++){ for(int j=0;j<list.get(i);j++){ System.out.print(chars.get(i)); } } out.flush(); } static class IP implements Comparable<IP>{ public int first,second; IP(int first, int second){ this.first = first; this.second = second; } public int compareTo(IP ip){ if(first==ip.first) return second-ip.second; return first-ip.first; } } static boolean same(String n){ for(int i=0;i<n.length();i++){ if(n.charAt(0)!=n.charAt(i)){ return false; } } return true; } static long gcd(long a, long b){ return b!=0?gcd(b, a%b):a; } static boolean isEven(long a) { return (a&1)==0; } 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
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 11
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
b95ab3c4a2ca7565a53c84005b9a31b8
train_004.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class FixingTypos { public static void main(String[] args) throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String str = bf.readLine(); StringBuilder ans = new StringBuilder(); char temp; for (int i = 0; i < str.length(); i++) { temp = str.charAt(i); if (i>1&&str.charAt(i-2)==str.charAt(i-1)&&str.charAt(i-1)==str.charAt(i)) continue; if (ans.length()>2&&ans.charAt(ans.length()-1)==temp&&ans.charAt(ans.length()-2)==ans.charAt(ans.length()-3)) continue; ans.append(temp); } System.out.print(ans); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 11
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
ef764a201a0090f12da6daee2fd416bf
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; /** * Created with IntelliJ IDEA. * User: ekrylov * Date: 11/3/13 * Time: 11:36 AM * To change this template use File | Settings | File Templates. */ public class A { public static void main(String[] args) throws Exception{ new A().solve(); } private void solve() throws Exception{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); String input = in.readLine(); int n = Integer.parseInt(input.split(" ")[0]); int m = Integer.parseInt(input.split(" ")[1]); int a[][] = new int[51][51]; for (int i = 0; i < n; i++) { input = in.readLine(); int j = 0; for (String mm : input.split(" ")) { if (mm.equals("1")) { a[i][j] = 1; } j++; } } for (int i = 1; i < n - 1; i++) { if (a[i][0] == 1 || a[i][m - 1] == 1) { out.print(2); out.flush(); return; } } for (int i = 1; i < m - 1; i++) { if (a[0][i] == 1 || a[n - 1][i] == 1) { out.print(2); out.flush(); return; } } out.print(4); out.flush(); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
f5f7d9959b18d09857f82ec3b45703cd
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
/* Date : Nov 13, 2013 Problem Name : Table Location : http://codeforces.com/contest/359/problem/A Algorithm : check if we have a good table on the edge. Status : solving */ import java.util.*; import java.io.*; public class Main { static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); public static void main(String[] args){ String[] inp = getLine().trim().replaceAll("\\s+", " ").split(" "); int numRows = Integer.parseInt(inp[0]); int numCols = Integer.parseInt(inp[1]); boolean is2 = false; for (int i = 0; i < numRows; i++){ String[] row = getLine().trim().replaceAll("\\s+", " ").split(" "); if (i == 0 || i == numRows - 1) for (String str : row) if (str.equals("1")) is2 = true; if (row[0].equals("1") || row[numCols-1].equals("1")) is2 = true; } System.out.println(is2 ? "2" : "4"); } static String getLine(){ try { return reader.readLine(); } catch (Exception e){} return null; } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
8a78a5aff2ab8e5014cc340834bcea65
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.util.Scanner; public class Table { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int m = scanner.nextInt(); int g[][] = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { g[i][j] = scanner.nextInt(); } } int c = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if(g[i][j] == 1) { if(i == 0 || i == n - 1 || j == 0 || j == m - 1 ) { c = 2; } else { if(c == 0){ c = 4; } } } } } System.out.println(c); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
6c822b71df648280845a2c4d7b2f780f
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.util.*; import java.io.*; public class a{ public static void main(String [] args){ Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int m = in.nextInt(); int a[][] = new int[n][m]; for (int i=0;i<n;i++) for (int j=0;j<m;j++) a[i][j] = in.nextInt(); for (int i=0;i<n;i++) if (a[i][0] == 1 || a[i][m-1] == 1) { out.println(2); out.close(); return; } for (int i=0;i<m;i++) if (a[0][i] == 1 || a[n-1][i] == 1) { out.println(2); out.close(); return; } out.println(4); out.close(); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
5048fca044b0c7bc365d34af11a34544
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.util.Scanner; public class Table { public int solve(char[][] input, int n, int m) { for (int i = 1; i < n; i++) { if (input[i][0] == '1' || input[i][m - 1] == '1') return 2; } for (int i = 1; i < m; i++) { if (input[0][i] == '1' || input[n - 1][i] == '1') return 2; } for (int i = 1; i < n - 1; i++) { for (int j = 1; j < m - 1; j++) { if (input[i][j] == '1') return 4; } } return 0; } public static void main (String[] args) { Scanner s = new Scanner(System.in); if (s.hasNext()){ int n = s.nextInt(); int m = s.nextInt(); s.nextLine(); char [][]input = new char [n][m]; for(int i = 0 ; i < n ; i++){ input[i] = s.nextLine().replace(" ","").toCharArray(); } System.out.println(new Table().solve(input, n, m)); } } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
8fc7b01530726eeeb3804a182a55a12a
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.io.*; import java.util.*; import java.lang.StringBuilder; public class Solution359A { public static void main(String[] args) { //Scanner sc = new Scanner(System.in); MyScanner sc = new MyScanner(); int n = sc.nextInt(); int m = sc.nextInt(); boolean result = false; for (int i = 0 ; i < n; i++) { for (int j = 0 ; j < m ; j++) { int cell = sc.nextInt(); if(cell == 1) { if (i == 0 || i == n-1 || j == 0 || j == m-1) { result = true; } } } } if (result) System.out.println(2); else System.out.println(4); } } 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 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
535fc987fd70276d7e0143803a5af734
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.io.*; import java.math.*; import java.text.*; import java.util.*; /* br = new BufferedReader(new FileReader("input.txt")); pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); */ public class Main { private static BufferedReader br; private static StringTokenizer st; private static PrintWriter pw; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); //int qq = 1; int qq = Integer.MAX_VALUE; //int qq = readInt(); for(int casenum = 1; casenum <= qq; casenum++) { int n = readInt(); int m = readInt(); int ret = 4; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(readInt() == 1 && ((i == 0 || i == n-1) || (j == 0 || j == m-1))) { ret = 2; } } } pw.println(ret); } pw.close(); } private static void exitImmediately() { pw.close(); System.exit(0); } private static long readLong() throws IOException { return Long.parseLong(nextToken()); } private static double readDouble() throws IOException { return Double.parseDouble(nextToken()); } private static int readInt() throws IOException { return Integer.parseInt(nextToken()); } private static String nextToken() throws IOException { while(st == null || !st.hasMoreTokens()) { if(!br.ready()) { exitImmediately(); } st = new StringTokenizer(br.readLine().trim()); } return st.nextToken(); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
55e870a64412adc6ad9f46f6c04aa617
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.io.*; import java.util.StringTokenizer; public class Main implements Runnable { private void solve() throws Exception { int n = nextInt(); int m = nextInt(); int res = 4; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int v = nextInt(); if (v == 1 && (i == 0 || i == n - 1 || j == 0 || j == m - 1)) { res = 2; } } } out.println(res); } public String next() throws IOException { while (!st.hasMoreTokens()) { final String s = in.readLine(); if (s == null) { return null; } st = new StringTokenizer(s); } return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } IO io; BufferedReader in; StringTokenizer st; PrintWriter out; public Main() { // io = file; io = standard; } public void run() { try { io.initIO(); try { solve(); } catch (Exception e) { e.printStackTrace(); } finally { try { io.finalizeIO(); } catch (IOException e) { e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { new Thread(new Main()).start(); } IO standard = new IO() { public void initIO() { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); st = new StringTokenizer(""); } public void finalizeIO() { out.flush(); } }; IO file = new IO() { public void initIO() throws IOException { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter(new File("output.txt")); st = new StringTokenizer(""); } public void finalizeIO() throws IOException { in.close(); out.close(); } }; interface IO { public void initIO() throws IOException; public void finalizeIO() throws IOException; } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
6504731fb4edbb270d5a97407c54fef0
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Table2 { public static void main(String[] args) { InputReader r = new InputReader(System.in); int n = r.nextInt(); int m = r.nextInt(); int[][] arr = new int[n][m]; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { arr[i][j] = r.nextInt(); } } boolean can = false; for (int i = 0; i < n; i++) { if (arr[i][0] == 1 || arr[i][m - 1] == 1) can = true; } for (int i = 0; i < m; i++) { if (arr[0][i] == 1 || arr[n-1][i] == 1) can = true; } if (can) System.out.println(2); else System.out.println(4); } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
17c2349a8a731b26077518e96a67dd53
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.util.Scanner; public class game { public static void main(String[] args) { Scanner a=new Scanner(System.in); int row=a.nextInt(); int column=a.nextInt(); int table[][]= new int[row][column]; for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) { table[i][j]=a.nextInt(); if(table[i][j]==1 && ( i==0 || i==row-1 || j==0 || j==column-1)){ System.out.println(2); return; } } } System.out.println(4); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
34b053533942fe4d151fc7673fe83bc4
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.util.Scanner; public class P1_209 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int array[][] = new int[n][m]; int numOnes = 0; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { array[i][j] = in.nextInt(); if (array[i][j] == 1 && (i == 0 || i == n - 1 || j == 0 || j == m - 1)) numOnes++; } if(numOnes>0) System.out.println(2); else System.out.println(4); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
9e2de5ec65402ded42512eac8d9a2298
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.util.Scanner; public class Table{ public static void main(String args[]) { Scanner scan = new Scanner(System.in); boolean tmam = false; int n = scan.nextInt(); int m = scan.nextInt(); for(int i=0; i<n; i++) for(int j=0; j<m; j++) { int current = scan.nextInt(); if(current == 1 && (j == 0 || j == m-1 || i == 0 || i == n-1)) tmam = true; } System.out.println((tmam)?2:4); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
5164c352764f58d6549bc8909ecf571a
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.util.*; public class hfd { public static void main(String[] args){ Scanner sc=new Scanner(System.in); int i,j,flag=0; int n=sc.nextInt(); int m=sc.nextInt(); for (i=0;i<n;++i) for (j=0;j<m;++j) { int ts=sc.nextInt(); if (ts==1&&(i==0||j==0||i==n-1||j==m-1)) flag=1; } if (flag==1) System.out.println(2); else System.out.println(4); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
e9b2a85dbbc38b52e4f99e1acae57819
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * * @author baha */ public class A { static Scanner in; static Output out; static int a[][] = null; static int b[][] = null; static int s = 0; public static void main(String[] args) throws Exception { boolean isFile = false; String filenameIn = null; String filenameOut = null; if (isFile) { in = new Scanner(filenameIn); out = new Output(new File(filenameOut)); } else { in = new Scanner(); out = new Output(System.out); } int n = in.nextInt(); int m = in.nextInt(); a = new int[n][m]; b = new int[n][m]; List<P> pp = new ArrayList<P>(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int v = in.nextInt(); if (v == 1) { pp.add(new P(i, j)); } a[i][j] = v; } } int step = 0; while (!isFilled()) { P foundP = null; int x = 0; int y = 0; int max = Integer.MIN_VALUE; for (P p : pp) { int s = 0; if (max <= (s = count(p.x, p.y, 0, 0))) { foundP = p; x = 0; y = 0; max = s; } if (max <= (s = count(p.x, p.y, 0, m - 1))) { foundP = p; x = 0; y = m - 1; max = s; } if (max <= (s = count(p.x, p.y, n - 1, 0))) { foundP = p; x = n - 1; y = 0; max = s; } if (max <= (s = count(p.x, p.y, n - 1, m - 1))) { foundP = p; x = n - 1; y = m - 1; max = s; } } change(foundP.x, foundP.y, x, y); step++; } out.println(step); } public static boolean isFilled() { for (int i = 0; i < b.length; i++) { for (int j = 0; j < b[0].length; j++) { if (b[i][j] == 0) { return false; } } } return true; } public static int count(int gx, int gy, int x, int y) { int count = 0; int minX = Math.min(gx, x); int minY = Math.min(gy, y); int maxX = Math.max(gx, x); int maxY = Math.max(gy, y); for (int i = minX; i <= maxX; i++) { for (int j = minY; j <= maxY; j++) { if (b[i][j] == 0) { count++; } } } return count; } public static void change(int gx, int gy, int x, int y) { int minX = Math.min(gx, x); int minY = Math.min(gy, y); int maxX = Math.max(gx, x); int maxY = Math.max(gy, y); for (int i = minX; i <= maxX; i++) { for (int j = minY; j <= maxY; j++) { b[i][j] = s + 1; } } s++; } private static class P { public int x; public int y; public P(int a, int b) { this.x = a; this.y = b; } } private static void print() { for (int i = 0; i < b.length; i++) { for (int j = 0; j < b[0].length; j++) { System.out.print(b[i][j] + " "); } System.out.println(""); } } private static class Scanner { StringTokenizer st = null; BufferedReader in; public Scanner() { in = new BufferedReader(new InputStreamReader(System.in)); } public Scanner(String fileName) throws FileNotFoundException { in = new BufferedReader(new FileReader(fileName)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public String nextLine() throws IOException { return in.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } } private static class Output extends PrintStream { public Output(OutputStream out) { super(out); } public Output(File file) throws FileNotFoundException { super(file); } } private static void create(String... files) { for (String file : files) { if (!new File(file).exists()) { try { new File(file).createNewFile(); } catch (IOException ex) { ex.printStackTrace(); } }; } } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
6622423012cefab798f58ab1dac1a9a0
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.io.*; import java.util.*; public class A implements Runnable { private void solve() throws IOException { int n = nextInt(), m = nextInt(); boolean up = false, down = false, right = false, left = false; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { int a = nextInt(); if (a == 1) { if (i == 0) up = true; if (i == n - 1) down = true; if (j == 0) left = true; if (j == m - 1) right = true; } } if (up || down || left || right) print(2); else print(4); } public static void main(String[] args) { new A().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(System.out); solve(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(261); } } void halt() { writer.close(); System.exit(0); } void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } void println(Object... objects) { print(objects); writer.println(); } String nextLine() throws IOException { return reader.readLine(); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(nextLine()); return tokenizer.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
f955591c8386890aa922c07e13c9a2e2
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; public class CF_Solution_A { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; static BufferedReader in; static PrintWriter out; static StringTokenizer tok = new StringTokenizer(""); static void init() throws FileNotFoundException{ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } static String readString() throws IOException{ while(!tok.hasMoreTokens()){ try{ tok = new StringTokenizer(in.readLine()); }catch (Exception e){ return null; } } return tok.nextToken(); } static int readInt() throws IOException{ return Integer.parseInt(readString()); } long readLong() throws IOException{ return Long.parseLong(readString()); } double readDouble() throws IOException{ return Double.parseDouble(readString()); } public static void main(String[] args){ run(); } static long timeBegin; static long timeEnd; static void time(){ timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } static long memoryTotal; static long memoryFree; static void memory(){ memoryFree = Runtime.getRuntime().freeMemory(); System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB"); } static void run(){ try{ timeBegin = System.currentTimeMillis(); memoryTotal = Runtime.getRuntime().freeMemory(); init(); solve(); out.close(); time(); memory(); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } boolean DEBUG = true; static void solve() throws IOException{ int n = readInt(); int m = readInt(); double [][] table = new double [n+1][m+1]; for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ table[i][j] = readInt(); } } for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ if(table[i][j]==1){ if(i==n||j==m){ out.println(2); return; } if(i==1||j==1){ out.println(2); return; } } } } out.println(4); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
caa948bd359e7fa4ebd558e16bc57dff
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int r = scan.nextInt(); int c = scan.nextInt(); int a[][] = new int[r][c]; int ans1 = 999999; int ans2=999999; int ans3 = 99999999; for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { a[i][j] = scan.nextInt(); if (a[i][j] == 1) { if (i == 0 && j == 0 || i == 0 && j == c - 1 || i == r - 1 && j == 0 || i == r - 1 && j == c - 1) { ans1 = 1; continue; } if (i == 0 || i == r - 1 || j == 0 || j == c - 1) { ans2 = 2; continue; } if (i != 0 && i != r - 1 && j != 0 && j != c - 1) { ans3 = 4; } } } } System.out.println(Math.min(Math.min(ans1, ans2), ans3)); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
4b4b18641ae881ece4f871c6a70ce0ca
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main implements Runnable { private void solve() throws IOException { int n = nextInt(); int m = nextInt(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int a = nextInt(); if (a == 1 && (i == 0 || i == n - 1 || j == 0 || j == m - 1)) { out.println(2); return; } } } out.println(4); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) return null; eat(line); } return st.nextToken(); } public static void main(String[] args) { new Thread(null, new Main(), "Main", 1 << 28).start(); } private BufferedReader in; private PrintWriter out; private StringTokenizer st; @Override public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); eat(""); solve(); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(566); } } private void eat(String s) { st = new StringTokenizer(s); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
f75793665eae3ff93394f7e3c47d6235
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int cell = sc.nextInt(); if (cell == 1 && (i == n - 1 || j == m - 1 || j == 0 || i == 0)) { System.out.println(2); return; } } } System.out.println(4); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
029841479205f44c76458ed7dc909e71
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * Created by 875k on 12/31/13. */ public class CF209A { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tok = new StringTokenizer(br.readLine()); int n = Integer.parseInt(tok.nextToken()); int m = Integer.parseInt(tok.nextToken()); tok = new StringTokenizer(br.readLine()); tok.nextToken(); for(int i = 0; i < m - 1; i++) { int x = Integer.parseInt(tok.nextToken()); if(x == 1) { System.out.println(2); System.exit(0); } } for(int i = 0; i < n - 2; i++) { tok = new StringTokenizer(br.readLine()); int x = Integer.parseInt(tok.nextToken()); if(x == 1) { System.out.println(2); System.exit(0); } for(int j = 0; j < m - 2; j++) { tok.nextToken(); } x = Integer.parseInt(tok.nextToken()); if(x == 1) { System.out.println(2); System.exit(0); } } tok = new StringTokenizer(br.readLine()); tok.nextToken(); for(int i = 0; i < m - 1; i++) { int x = Integer.parseInt(tok.nextToken()); if(x == 1) { System.out.println(2); System.exit(0); } } System.out.println(4); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
ebf32512cd9a93e2ae5643ac17b8ee67
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.util.*; import java.awt.geom.*; import java.io.*; import java.lang.reflect.Array; public class Main{ private void doit(){ InStream sc = new InStream(); while(sc.hasNext()){ int h = sc.nextInt(); int w = sc.nextInt(); int [][] data = new int[h][w]; for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++){ data[i][j] = sc.nextInt(); } } if(isS(data, h,w)){ System.out.println(2); } else{ System.out.println(4); } } } private boolean isS(int[][] data, int h, int w) { for(int i = 0; i < data.length; i++){ if(data[i][0] == 1 || data[i][w-1] == 1){ return true; } } for(int i = 0; i < w; i++){ if(data[0][i] == 1 || data[h-1][i] == 1){ return true; } } return false; } class InStream{ BufferedReader in;StringTokenizer st; public InStream() { this.in = new BufferedReader(new InputStreamReader(System.in)); this.st = null; } String next() { while (st==null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (Exception e) {} } return st.nextToken(); } boolean hasNext(){ try{ st = new StringTokenizer(in.readLine()); return true; }catch(Exception e){return false;} } int nextInt() { return Integer.parseInt(next());} long nextLong() {return Long.parseLong(next());} double nextDouble() {return Double.parseDouble(next());} } private void debug(Object... o) { System.out.println("debug = " + Arrays.deepToString(o)); } public static void main(String[] args) { new Main().doit(); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
e19cc3a11ab35709476b79fae7c19932
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Integer.*; import static java.lang.Math.*; public class Problem359A { static BufferedReader in; static PrintWriter out; public static void main(String[] args) throws Exception { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); new Problem359A().go(); out.close(); } void go() throws IOException { String[] inp = in.readLine().trim().split("\\s+"); int n = parseInt(inp[0]); int m = parseInt(inp[1]); for (int i = 0; i < n; i++) { String line = in.readLine().trim(); if (line.startsWith("1") || line.endsWith("1") || (line.indexOf("1") >= 0 && (i == 0 || i == n - 1))) { out.println("2"); return; } } out.println("4"); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
80d747e523e897cfbba93c245634e380
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class A209 { public void solve() throws IOException { Scanner sc = new Scanner(System.in); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int i = 0, j = 0, k = 0; long ans = 0, sum = 0, count = 0; int n = sc.nextInt(); int m = sc.nextInt(); int aa[][] = new int[n][m]; for (i = 0; i < n; ++i) { for (j = 0; j < m; ++j) { aa[i][j] = sc.nextInt(); } } for (i = 0; i < n; ++i) { for (j = 0; j < m; ++j) { if (((j == 0 || j == m - 1) || (i == 0 || i == n - 1)) && aa[i][j] == 1) { System.out.println("2"); System.exit(0); } } } System.out.println("4"); } public static void main(String[] args) throws IOException { new A209().solve(); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
4c383a1f9327a4b1b610848000c40058
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.io.*; import java.util.*; public class A359 { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(in.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); byte grid[][] = new byte[n][m]; boolean flag = false; for (int i = 0; i < n; i++) { StringTokenizer getLine = new StringTokenizer(in.readLine()); for (int j = 0; j < m; j++) { grid[i][j] = Byte.parseByte(getLine.nextToken()); if (grid[i][j] == 1 && (i == 0 || i == n - 1 || j == 0 || j == m-1)) { flag = true; break; } } } System.out.println(flag?2:4); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
4418993e3cddc05c155b0d6302768d04
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.util.*; public class a { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(), m = input.nextInt(); boolean[][] data = new boolean[n][m]; for(int i = 0; i<n; i++) for(int j =0; j<m; j++) data[i][j] = input.nextInt() == 1; boolean side = false, corner = false; for(int i = 0; i<n; i++) for(int j = 0; j<m; j++) { if(data[i][j]) { if((i == 0 || i == n-1) && (j==0 || j == m-1)) corner = true; else if((i == 0 || i == n-1) || (j==0 || j == m-1)) side = true; } } if(corner)System.out.println(1); else if(side) System.out.println(2); else System.out.println(4); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
4b2abf776c29441e2c1e335fbcd24cb7
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.util.*; public class contestTwoC {public static void main(String[] args) throws Exception{ Scanner input = new Scanner(System.in); int f=0; int n = input.nextInt(); int m= input.nextInt(); int [][] table=new int[n][m]; for(int i = 0; i < n; i++){ for ( int j = 0; j < m; j++) table[i][j]=input.nextInt(); } //to find the goods for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(i==0 || j==0 || i==n-1 || j==m-1){ if(table[i][j]==1){ f=1; System.out.println(2); break; } } } if( f==1) break; } if (f==0){ System.out.println(4); } }}
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
1e005fdc9f0632e2102000bc6114b0f1
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.util.Scanner; public class Table { public static void main(String[] args) { new Table().solve(); } public void solve(){ Scanner in = new Scanner(System.in); int row = in.nextInt(); int col = in.nextInt(); for(int i = 0; i< row; i++){ for(int j =0; j<col; j++){ int num = in.nextInt(); if(num==1&&(i==0||i==row-1)){ System.out.println("2"); return; } if(num==1&&(j==0||j==col-1)){ System.out.println("2"); return; } } } System.out.println("4"); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
9d06967abe0d03041b2af96d2fac32b6
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.util.*; import java.io.*; public class A { FastScanner in; PrintWriter out; public void solve() throws IOException { int n = in.nextInt(); int m = in.nextInt(); int[][] a = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = in.nextInt(); } } int ans = 4; for (int i = 0; i < n; i++) { if (a[i][0] + a[i][m-1] != 0) { ans = 2; } } for (int i = 0; i < m; i++) { if (a[0][i] + a[n-1][i] != 0) { ans = 2; } } if (a[n-1][m-1] + a[0][m-1] + a[n-1][0] + a[0][0] != 0) { ans = 1; } out.print(ans); } public void run() { try { in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream f) { try { br = new BufferedReader(new InputStreamReader(f)); } 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(); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { try { return br.readLine(); } catch (Exception e) { return null; } } int nextInt() { return Integer.parseInt(next()); } } public static void main(String[] arg) { new A().run(); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
9e5b2440d894d457947e8d7b7e10562e
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.util.Scanner; public class Codeforces { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = sc.nextInt(); } } boolean b = false; for (int i = 1; i < n -1; i++) { if(arr[i][0] == 1 || arr[i][m-1] == 1){ b = true; break; } } if(!b){ for (int i = 1; i < m-1; i++) { if(arr[0][i] == 1 || arr[n-1][i] == 1){ b = true; break; } } } if(b) System.out.println(2); else System.out.println(4); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
5aab1b0d62fd77cb95e186f9a415ffed
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author coderbd */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int m = in.readInt(); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (in.readInt() == 1 && (i == 0 || j == 0 || i == n - 1 || j == m - 1)) { out.printLine("2"); return; } out.printLine("4"); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
6b936c67c00f03c697fc3ea09fda6b48
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Codeforces implements Runnable { private BufferedReader br = null; private PrintWriter pw = null; private StringTokenizer stk = new StringTokenizer(""); public static void main(String[] args) { new Thread(new Codeforces()).run(); } public void run() { /* * try { br = new BufferedReader(new FileReader("input.txt")); pw = new * PrintWriter("output.txt"); } catch (FileNotFoundException e) { * e.printStackTrace(); } */ br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new OutputStreamWriter(System.out)); solver(); pw.close(); } private void nline() { try { if (!stk.hasMoreTokens()) stk = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException("KaVaBUnGO!!!", e); } } private String nstr() { while (!stk.hasMoreTokens()) nline(); return stk.nextToken(); } private int ni() { return Integer.valueOf(nstr()); } private Integer nI() { return Integer.valueOf(nstr()); } private long nl() { return Long.valueOf(nstr()); } private double nd() { return Double.valueOf(nstr()); } String nextLine() { try { return br.readLine(); } catch (IOException e) { } return null; } private void solver() { int n = ni(), m = ni(); int a[][] = new int[n][m]; boolean isTwo = false; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = ni(); if (a[i][j]==1){ if (i==0 || j==0 || i==n-1 || j==m-1) isTwo = true; } } } System.out.println(isTwo ? 2 : 4); } private BigInteger nbi() { return new BigInteger(nstr()); } void exit() { System.exit(0); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
ca7b82a77eeefad2f91d63b628e56ce6
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.io.IOException; import java.util.Scanner; public class A359 { public static void main(String[] args) throws IOException { solve(); } public static void solve() throws IOException { Scanner scan = new Scanner(System.in); String nm[] = scan.nextLine().split(" "); int N = Integer.parseInt(nm[0]); int M = Integer.parseInt(nm[1]); String line1 = scan.nextLine(); if(line1.indexOf("1") >= 0){ System.out.println(2); return; } for (int i = 1; i < N-1; i++) { String line = scan.nextLine(); if(line.startsWith("1") || line.endsWith("1")){ System.out.println(2); return; } } String lineN = scan.nextLine(); if(lineN.indexOf("1") >= 0){ System.out.println(2); return; } System.out.println(4); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
54d518bf3ab765ff50f004690942e257
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Trung Pham */ public class A { public static void main(String[] args) { Scanner in = new Scanner(); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int m = in.nextInt(); boolean [][]data = new boolean[n][m]; boolean ok = false; for(int i = 0; i <n && !ok; i++){ for (int j = 0; j < m; j++){ int a = in.nextInt(); if(a == 1 && (i == 0 || i == (n - 1)|| j == 0 || j == (m - 1))){ ok = true; break; } } } if(ok){ out.println(2); }else{ out.println(4); } out.close(); } static class Point implements Comparable<Point> { int index, pos; public Point(int index, int pos) { this.index = index; this.pos = pos; } @Override public int compareTo(Point o) { if (pos != o.pos) { return pos - o.pos; } else { return index - o.index; } } } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } static class FT { int[] data; FT(int n) { data = new int[n]; } void update(int index, int val) { // System.out.println("UPDATE INDEX " + index); while (index < data.length) { data[index] += val; index += index & (-index); // System.out.println("NEXT " +index); } } int get(int index) { // System.out.println("GET INDEX " + index); int result = 0; while (index > 0) { result += data[index]; index -= index & (-index); // System.out.println("BACK " + index); } return result; } } static int gcd(int a, int b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static int pow(int a, int b) { if (b == 0) { return 1; } if (b == 1) { return a; } int val = pow(a, b / 2); if (b % 2 == 0) { return val * val; } else { return val * val * a; } } // static Point intersect(Point a, Point b, Point c) { // double D = cross(a, b); // if (D != 0) { // return new Point(cross(c, b) / D, cross(a, c) / D); // } // return null; // } // // static Point convert(Point a, double angle) { // double x = a.x * cos(angle) - a.y * sin(angle); // double y = a.x * sin(angle) + a.y * cos(angle); // return new Point(x, y); // } // static Point minus(Point a, Point b) { // return new Point(a.x - b.x, a.y - b.y); // } // // static Point add(Point a, Point b) { // return new Point(a.x + b.x, a.y + b.y); // } // // static double cross(Point a, Point b) { // return a.x * b.y - a.y * b.x; // // // } // // static class Point { // // int x, y; // // Point(int x, int y) { // this.x = x; // this.y = y; // } // // @Override // public String toString() { // return "Point: " + x + " " + y; // } // } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() { //System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
b175f8be68bbbbf8a2fe6bdfb488b793
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.util.Scanner; public class Table { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(); int m = input.nextInt(); int temp; boolean res = false; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { temp = input.nextInt(); if (!res && temp == 1 && (i == 0 || i == n - 1 || j == 0 || j == m - 1)) { res = true; } } } if (res) { System.out.println(2); } else { System.out.println(4); } } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
bdee08840549ff714bd94b0e07a11824
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Main { public static void main (String[] args) throws java.lang.Exception { // your code goes here Scanner s=new Scanner(System.in); int x=s.nextInt(); int y=s.nextInt(); boolean b=1<0; for(int i=0;i<x;i++) for(int j=0;j<y;j++) { int val=s.nextInt(); if(val==1&&(i==0||j==0||(i==x-1)||(j==y-1))) {b=1>0;} //System.out.println(); } System.out.println(b?2:4); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
b11210f479368ad18febd66ebfc8c88b
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; import java.math.BigDecimal; import java.math.BigInteger; public class palin { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(System.out); Scanner scan = new Scanner(System.in); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(), m = in.nextInt(), a[][] = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = in.nextInt(); } } for (int i = 0; i < m; i++) { if (a[0][i] != 0 || a[n - 1][i] != 0) { out.print(2); return; } } for (int i = 0; i < n; i++) { if (a[i][0] != 0 || a[i][m - 1] != 0) { out.print(2); return; } } out.print(4); } } class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public float nextFloat() { return Float.parseFloat(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
912b437573464b85513cbe699caa568a
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.io.*; import java.util.*; import java.awt.*; public class Main { static BufferedReader br = new BufferedReader( new InputStreamReader(System.in) ); static StringTokenizer st = new StringTokenizer(""); static String next() throws Exception { while ( !st.hasMoreTokens() ) { String s = br.readLine(); if ( s == null ) return null; st = new StringTokenizer( s ); } return st.nextToken(); } public static void main(String [] asda) throws Exception { PrintWriter out = new PrintWriter( new BufferedOutputStream(System.out) ); // int N = Integer.parseInt( next() ); int M = Integer.parseInt( next() ); boolean found = false; for (int x = 0; x < N; x++) { for (int y = 0; y < M; y++) { boolean one = next().equals("1"); found |= one && (x == 0 || y == 0 || x == N - 1 || y == M - 1); } } out.println( found ? 2 : 4 ); out.flush(); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
1c9ea6f4ec53b906b36e44e1983cbcb9
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.lang.Math; import java.util.Scanner; import java.io.*; import java.util.*; public class Some { public static void main(String[] args){ Some a = new Some(); a.run(); } boolean simpleTest(int a){ for (int i = 2; i * i <= a; i++){ if (a % i == 0){ return false; } } return true; } boolean pall(String word){ for (int i = 1; i * 2 <= word.length(); i++){ if (word.charAt(i-1) != word.charAt(word.length() - i)){ return false; } } return true; } void run(){ PrintWriter out = new PrintWriter(System.out); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int[][] mas = new int[51][51]; for (int i = 1; i <= n; i++){ for (int j = 1; j <= m; j++){ mas[i][j] = sc.nextInt(); } } int k = -1; for (int i = 1; i <= n; i++){ if ((mas[i][1] == 1) || (mas[i][m] == 1)){ k = 2; break; } } for (int i = 1; i <= m; i++){ if ((mas[1][i] == 1) || (mas[n][i] == 1)){ k = 2; break; } } if (k == -1) k = 4; out.println(k); out.flush(); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
593fc58ac722b1ae202e4b151de4cdb7
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.io.PrintStream; import java.util.HashMap; import java.util.Map; import java.util.Scanner; /** * Created with IntelliJ IDEA. * User: zwh * Date: 11/1/13 * Time: 11:30 PM * To change this template use File | Settings | File Templates. */ public class A { static Scanner scan = new Scanner(System.in); static PrintStream out = System.out; public static void main (String[] args) { int n = scan.nextInt(); int m = scan.nextInt(); for (int i = 0; i < n; ++i) for (int j = 0 ; j < m; ++j) { if (scan.nextInt() == 1) { if (i == 0 || i == n - 1 || j == 0 || j == m - 1) { out.println(2); return; } } } out.println(4); return; } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
8e1eba945a5cb691f69fadc9c384b2a9
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.util.*; import java.util.regex.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.lang.Integer.*; import static java.lang.Double.*; import static java.util.Collections.*; import java.io.*; public class _359_A_Table { //->solution screencast http://youtu.be/oHg5SJYRHA0 public void solve() { int n = ni(), m = ni(); int [][]a=new int[n][m]; for (int i = 0; i < n; i++) { a[i]=na(m); } for (int i = 0; i < m; i++) { if(a[0][i]==1 || a[n-1][i]==1){ out.println(2); return; } } for (int i = 0; i < n; i++) { if(a[i][0]==1 || a[i][m-1]==1){ out.println(2); return; } } out.println(4); } // IO methods void run() throws Exception { long s = System.currentTimeMillis(); solve(); out.flush(); pr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception {new _359_A_Table().run();} InputStream in=System.in; PrintWriter out=new PrintWriter(System.out); private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private byte[] inbuf = new byte[1024]; private int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = in.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) {return !(c >= 33 && c <= 126);} private int skip() {int b;while ((b = readByte()) != -1 && isSpaceChar(b));return b;} public String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != // ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } public char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } public int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } public int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } public long nl(){ long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } void pr(Object... ob) {if (!oj)System.out.println(Arrays.deepToString(ob).replace("],", "],\n"));} }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
2b71c5efe91a5ac0490636a6ed01dd60
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.util.*; public class cf359A{ public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); boolean got = false; for(int i=0; i<n; i++) for(int j=0; j<m; j++) { int this_val = sc.nextInt(); if(this_val == 1 && (j == 0 || j == m-1 || i == 0 || i == n-1)) got = true; } if(got) System.out.println(2); else System.out.println(4); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
50bdc18d45f111277a853b2cb871526e
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.util.Scanner; public class JavaApplication1 { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here int n,m; Scanner sc = new Scanner(System.in); m = sc.nextInt(); n = sc.nextInt(); int h; boolean isb = false; for(int i=1; i<=m; i++) { h = sc.nextInt(); if(h == 1) { isb = true; } for(int j=2; j<=n-1; j++) { h = sc.nextInt(); if ((i == 1 || i == m)&& h == 1) { isb = true; } } h = sc.nextInt(); if(h == 1){ isb = true;} } if(isb == true) { System.out.print("2");} else { System.out.print("4");} } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
165973afd7846b0b13739ce6b019af84
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.util.*; public class Table359A { public static void main(String[] args) { // Set up scanner Scanner sc = new Scanner(System.in); // System.out.println("Enter number of rows"); int n = sc.nextInt(); // System.out.println("Enter number of columns"); int m = sc.nextInt(); for (int r=0; r<n; r++) { for (int c=0; c<m; c++) { // System.out.println("Enter next entry"); int x = sc.nextInt(); if (x == 1) { if (r == 0 || c == 0 || r == n-1 || c == m-1) { System.out.println(2); return; } } } } System.out.println(4); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
78a1ca346c1b759b8a3b2cd9a85f99db
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
/* Author: Gaurav Gupta Date: Nov 2, 2013 */ import java.io.InputStream; import java.io.PrintWriter; import java.io.DataInputStream; public class Table{ public static void main(String[] args) throws Exception { ParserdoubtR2 sc = new ParserdoubtR2(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); int m= sc.nextInt(); int N=0; int arr[][]= new int[n][m]; int side =0; for(int i=0;i<n;i++) for(int j=0;j<m;j++) { arr[i][j]=sc.nextInt(); if (arr[i][j]==1) N++; if(arr[i][j]==1 &&(i==0||j==0||i==n-1||j==m-1)) side = 1; } if(side==1) pw.println(2); else pw.println(4); pw.close(); } } class ParserdoubtR2 { final private int BUFFER_SIZE = 1 << 19; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public ParserdoubtR2(InputStream in) { din = new DataInputStream(in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String nextString() throws Exception { StringBuffer sb = new StringBuffer(""); byte c = read(); while (c <= ' ') c = read(); do { sb.append((char) c); c = read(); } while (c > ' '); return sb.toString(); } public char nextChar() throws Exception { byte c = read(); while (c <= ' ') c = read(); return (char) c; } public int nextInt() throws Exception { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) return -ret; return ret; } public long nextLong() throws Exception { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) return -ret; return ret; } private void fillBuffer() throws Exception { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws Exception { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
e771d9e1699c7f7c2bd486990628dab8
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
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(); boolean happened = false; for (int i = 0; i < n; i++) { for (int k = 0; k < m; k++) { int t = sc.nextInt(); if (t == 1) { if (i == 0 || i == n-1 || k == 0 || k == m-1) { happened = true; } } } } if (happened) { System.out.println("2"); } else { System.out.println("4"); } } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
fe8669e006f9913eb690da093f940b65
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StreamTokenizer; import static java.lang.Integer.*; import static java.lang.System.out; import static java.lang.Math.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] line = in.readLine().trim().split("\\s+"); int n = parseInt(line[0]), m = parseInt(line[1]); boolean isTwo = false; for (int i = 0; !isTwo && i < n; i++) { line = in.readLine().trim().split("\\s+"); for (int j = 0; !isTwo&&j < m; j++) isTwo = isTwo||(i==0||i==n-1||j==0||j==m-1)&&parseInt(line[j])==1; } out.println(isTwo ? "2" : "4"); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output
PASSED
c646e9fcb1380caa2fec114f4378208d
train_004.jsonl
1383379200
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class A { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); char[][] grid = new char[n][]; for (int i = 0; i < n; i++) grid[i] = br.readLine().replaceAll(" ", "").toCharArray(); boolean ok = false; for (int i = 0; i < n && !ok; i++) for (int j = 0; j < m && !ok; j++) if (grid[i][j] == '1' && (i == 0 || i == n - 1 || j == 0 || j == m - 1)) ok = true; if (ok) System.out.println(2); else System.out.println(4); } }
Java
["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"]
1 second
["4", "2"]
NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Java 6
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0d2fd9b58142c4f5282507c916690244
The first line contains exactly two integers n, m (3 ≀ n, m ≀ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.
1,000
Print a single number β€” the minimum number of operations Simon needs to carry out his idea.
standard output