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 | 1ba9a7c8e7ec86070d72a218203e86e8 | train_004.jsonl | 1421053200 | Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.TreeSet;
public class Main {
public static Node[] node;
public static Queue<Node> qu = new LinkedList<Node>();
public static void main(String[] args) throws NumberFormatException, IOException{
ContestScanner in = new ContestScanner();
int n = in.nextInt();
node = new Node[n];
if(n == 1){
System.out.println(0);
return;
}
for(int i=0; i<n; i++){
node[i] = new Node(i, in.nextInt(), in.nextInt());
if(node[i].qNum == 1) qu.add(node[i]);
}
int count = 0;
// int[][] map = new int[n][n];
StringBuilder sb = new StringBuilder();
while(!qu.isEmpty()){
Node nd = qu.poll();
int id = nd.xor;
if(nd.qNum == 0) continue;
// nd.createEdge(node[id]);
// node[id].createEdge(nd);
// map[nd.id][id] = 1;
// map[id][nd.id] = 1;
sb.append(nd.id+" "+id+"\n");
node[id].qNum--;
node[id].xor ^= nd.id;
if(node[id].qNum == 1){
qu.add(node[id]);
}
count++;
}
System.out.println(count);
System.out.println(sb.toString());
// for(Node nd: node){
// for(Node v: nd.edge){
// if(map[nd.id][v.id] != 1){
// map[nd.id][v.id] = 1;
// map[v.id][nd.id] = 1;
// System.out.println(nd.id+" "+v.id);
// }
// }
// }
}
}
//
//class Data{
// String oldest;
// String newN;
//
//}
class MyComp implements Comparator<int[]>{
public int compare(int[] a, int[] b) {
return a[0] - b[0];
}
}
//
//class Reverse implements Comparator<Integer>{
// public int compare(Integer arg0, Integer arg1) {
// return arg1 - arg0;
// }
//}
class Node implements Comparable<Node>{
int id;
int qNum;
int xor;
List<Node> edge = new ArrayList<Node>();
public Node(int id, int q, int xor){
this.id = id;
qNum = q;
this.xor = xor;
}
public void createEdge(Node node){
edge.add(node);
}
@Override
public int compareTo(Node n) {
return n.qNum - qNum;
}
}
//
//
//class NodeW{
// int id;
// List<NodeW> edge = new ArrayList<NodeW>();
// List<Integer> costList = new ArrayList<Integer>();
// public NodeW(int id) {
// this.id = id;
// }
// public void createEdge(NodeW node, int cost) {
// edge.add(node);
// costList.add(cost);
// }
//}
class Range<T extends Comparable<T>> implements Comparable<Range<T>>{
T start;
T end;
public Range(T start, T end){
this.start = start;
this.end = end;
}
public boolean inRange(T val){
if(start.compareTo(val) <= 0 && end.compareTo(val) >= 0){
return true;
}
return false;
}
public boolean isCommon(Range<T> range){
if(inRange(range.start) || inRange(range.end) || range.inRange(start)){
return true;
}
return false;
}
public Range<T> connect(Range<T> range){
if(!isCommon(range)) return null;
Range<T> res = new Range<T>(start.compareTo(range.start) <= 0 ? start : range.start,
end.compareTo(range.end) >= 0 ? end : range.end);
return res;
}
public boolean connectToThis(Range<T> range){
if(!isCommon(range)) return false;
start = start.compareTo(range.start) <= 0 ? start : range.start;
end = end.compareTo(range.end) >= 0 ? end : range.end;
return true;
}
@Override
public int compareTo(Range<T> range) {
int res = start.compareTo(range.start);
if(res == 0) return end.compareTo(range.end);
return res;
}
public String toString(){
return "["+start+","+end+"]";
}
}
class RangeSet<T extends Comparable<T>>{
TreeSet<Range<T>> ranges = new TreeSet<Range<T>>();
public void add(Range<T> range){
Range<T> con = ranges.floor(range);
if(con != null){
if(con.connectToThis(range))
range = con;
}
con = ranges.ceiling(range);
while(con != null && range.connectToThis(con)){
ranges.remove(con);
con = ranges.ceiling(range);
}
ranges.add(range);
}
public String toString(){
StringBuilder bld = new StringBuilder();
for(Range<T> r: ranges){
bld.append(r+"\n");
}
return bld.toString();
}
}
class MyMath{
public final static double PIhalf = Math.PI/2.0;
public static double pAngle(double x, double y){
// �x�N�g��(1, 0)��(x, y)�Ƃ̂Ȃ��p��Ԃ�(rad:0 to 2pi)
if(x == 0){
if(y == 0){
System.err.println("pAngle error: zero vector.");
return 0;
}else if(y < 0){
return PIhalf*3.0;
}else{
return PIhalf;
}
}
double rad = Math.atan(y/x);
if(rad < 0){
rad += Math.PI*2.0;
}
return rad;
}
public static long fact(long n){
long res = 1;
while(n > 0){
res *= n--;
}
return res;
}
public static long[][] pascalT(int n){
long[][] tri = new long[n][];
for(int i=0; i<n; i++){
tri[i] = new long[i+1];
for(int j=0; j<i+1; j++){
if(j == 0 || j == i){
tri[i][j] = 1;
}else{
tri[i][j] = tri[i-1][j-1] + tri[i-1][j];
}
}
}
return tri;
}
// �ő����
static int gcd(int a, int b){
return b == 0 ? a : gcd(b, a % b);
}
// �ŏ����{��
static int lcm(int a, int b){
return a * b / gcd(a, b);
}
}
class ContestScanner{
private BufferedReader reader;
private String[] line;
private int idx;
public ContestScanner() throws FileNotFoundException{
reader = new BufferedReader(new InputStreamReader(System.in));
}
public ContestScanner(String filename) throws FileNotFoundException{
reader = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
}
public String nextToken() throws IOException{
if(line == null || line.length <= idx){
line = reader.readLine().trim().split(" ");
idx = 0;
}
return line[idx++];
}
public long nextLong() throws IOException, NumberFormatException{
return Long.parseLong(nextToken());
}
public int nextInt() throws NumberFormatException, IOException{
return (int)nextLong();
}
public double nextDouble() throws NumberFormatException, IOException{
return Double.parseDouble(nextToken());
}
} | Java | ["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"] | 1 second | ["2\n1 0\n2 0", "1\n0 1"] | NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor". | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"sortings",
"data structures",
"trees"
] | 14ad30e33bf8cad492e665b0a486008e | The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space. | 1,500 | In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order. | standard output | |
PASSED | d2b29d93fb335ffb297b195ded01e468 | train_004.jsonl | 1421053200 | Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha. | 256 megabytes | import java.io.*;
import java.util.*;
public class Task {
public static void main(String[] args) throws IOException {
new Task().solve();
}
PrintWriter out;
int cnt = 0;
int n;
boolean[] used;
ArrayList<Integer>[] g;
ArrayList<Integer>[] rg;
ArrayList<Integer> tsort = new ArrayList<Integer>();
int[] comp;
int[] compsize;
void solve() throws IOException{
Reader in = new Reader("input.txt");
out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) );
//out = new PrintWriter(new FileWriter(new File("output.txt")));
HashMap<String, String> map = new HashMap<>();
int n = in.nextInt();
int[] d = new int[n];
int[] xor = new int[n];
Pair[] pairs = new Pair[n];
Queue<Integer> queue = new LinkedList<Integer>();
for (int i = 0; i < n; i++) {
d[i] = in.nextInt();
xor[i] = in.nextInt();
pairs[i] = new Pair(d[i], xor[i], i);
if (d[i] == 1)
queue.add(i);
}
Arrays.sort(pairs);
int m = 0;
int[] from = new int[n+1];
int[] to = new int[n+1];
while (!queue.isEmpty()) {
int v = queue.poll();
if (d[v] > 0) {
from[m] = v;
to[m] = xor[v];
m++;
d[xor[v]]--;
if (d[xor[v]] == 1)
queue.add(xor[v]);
xor[xor[v]] = xor[xor[v]] ^ v;
}
}
out.println(m);
for (int i = 0; i < m; i++)
out.println(from[i] + " " + to[i]);
out.flush();
out.close();
}
long pow(int x, int m) {
if (m == 0)
return 1;
return x*pow(x, m-1);
}
}
class Pair implements Comparable<Pair> {
int v;
int z;
int i;
Pair (int v, int z, int i) {
this.v = v;
this.z = z;
this.i = i;
}
@Override
public int compareTo(Pair p) {
if (v > p.v)
return 1;
if (v < p.v)
return -1;
return 0;
}
}
class Item implements Comparable<Item> {
int v;
int l;
int z;
Item(int v, int l, int z) {
this.v = v;
this.l = l;
this.z = z;
}
@Override
public int compareTo(Item item) {
if (l > item.l)
return 1;
else
if (l < item.l)
return -1;
else {
if (z > item.z)
return 1;
else
if (z < item.z)
return -1;
return 0;
}
}
}
class Reader {
StringTokenizer token;
BufferedReader in;
public Reader(String file) throws IOException {
//in = new BufferedReader( new FileReader( file ) );
in = new BufferedReader( new InputStreamReader( System.in ) );
}
public byte nextByte() throws IOException {
return Byte.parseByte(Next());
}
public int nextInt() throws IOException {
return Integer.parseInt(Next());
}
public long nextLong() throws IOException {
return Long.parseLong(Next());
}
public String nextString() throws IOException {
return in.readLine();
}
public String Next() throws IOException {
while (token == null || !token.hasMoreTokens()) {
token = new StringTokenizer(in.readLine());
}
return token.nextToken();
}
}
| Java | ["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"] | 1 second | ["2\n1 0\n2 0", "1\n0 1"] | NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor". | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"sortings",
"data structures",
"trees"
] | 14ad30e33bf8cad492e665b0a486008e | The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space. | 1,500 | In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order. | standard output | |
PASSED | dc40fed0f512f6a0032b49482722570f | train_004.jsonl | 1421053200 | Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha. | 256 megabytes | import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;
public class MainC {
MyScanner sc = new MyScanner();
Scanner sc2 = new Scanner(System.in);
final int MOD = 1000000007;
int[] dx = { 1, 0, 0, -1 };
int[] dy = { 0, 1, -1, 0 };
void run() {
int n = sc.nextInt();
int[] degree = new int[n];
int[] xor = new int[n];
LinkedList<Integer> leaf = new LinkedList<Integer>();
for (int i = 0; i < n; i++) {
degree[i] = sc.nextInt();
xor[i] = sc.nextInt();
if (degree[i] == 1) {
leaf.add(i);
}
}
int cnt = 0;
StringBuilder out = new StringBuilder();
while (!leaf.isEmpty()) {
int v = leaf.poll();
if (degree[v] == 1) {
out.append(v + " " + xor[v] + "\n");
cnt++;
} else {
continue;
}
degree[xor[v]]--;
if (degree[xor[v]] == 1) {
leaf.add(xor[v]);
}
xor[xor[v]] ^= v;
}
out.insert(0, cnt + "\n");
System.out.print(out);
}
public static void main(String[] args) {
new MainC().run();
}
void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
void debug2(int[][] array) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j]);
}
System.out.println();
}
}
boolean inner(int h, int w, int limH, int limW) {
return 0 <= h && h < limH && 0 <= w && w < limW;
}
void swap(int[] x, int a, int b) {
int tmp = x[a];
x[a] = x[b];
x[b] = tmp;
}
// find minimum i (a[i] >= border)
int lower_bound(int a[], int border) {
int l = -1;
int r = a.length;
while (r - l > 1) {
int mid = (l + r) / 2;
if (border <= a[mid]) {
r = mid;
} else {
l = mid;
}
}
// r = l + 1
return r;
}
class MyScanner {
int nextInt() {
try {
int c = System.in.read();
while (c != '-' && (c < '0' || '9' < c))
c = System.in.read();
if (c == '-')
return -nextInt();
int res = 0;
do {
res *= 10;
res += c - '0';
c = System.in.read();
} while ('0' <= c && c <= '9');
return res;
} catch (Exception e) {
return -1;
}
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
String next() {
try {
StringBuilder res = new StringBuilder("");
int c = System.in.read();
while (Character.isWhitespace(c))
c = System.in.read();
do {
res.append((char) c);
} while (!Character.isWhitespace(c = System.in.read()));
return res.toString();
} catch (Exception e) {
return null;
}
}
int[] nextIntArray(int n) {
int[] in = new int[n];
for (int i = 0; i < n; i++) {
in[i] = nextInt();
}
return in;
}
int[][] nextInt2dArray(int n, int m) {
int[][] in = new int[n][m];
for (int i = 0; i < n; i++) {
in[i] = nextIntArray(m);
}
return in;
}
double[] nextDoubleArray(int n) {
double[] in = new double[n];
for (int i = 0; i < n; i++) {
in[i] = nextDouble();
}
return in;
}
long[] nextLongArray(int n) {
long[] in = new long[n];
for (int i = 0; i < n; i++) {
in[i] = nextLong();
}
return in;
}
}
}
| Java | ["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"] | 1 second | ["2\n1 0\n2 0", "1\n0 1"] | NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor". | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"sortings",
"data structures",
"trees"
] | 14ad30e33bf8cad492e665b0a486008e | The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space. | 1,500 | In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order. | standard output | |
PASSED | cd2d8a1e3b4d16cb5465af8c688036ec | train_004.jsonl | 1421053200 | Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha. | 256 megabytes | import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;
public class MainC {
Scanner sc = new Scanner(System.in);
void run() {
int n = sc.nextInt();
int[] degree = new int[n];
int[] xor = new int[n];
LinkedList<Integer> leaf = new LinkedList<Integer>();
for (int i = 0; i < n; i++) {
degree[i] = sc.nextInt();
xor[i] = sc.nextInt();
if (degree[i] == 1)
leaf.add(i);
}
int cnt = 0;
StringBuilder out = new StringBuilder();
while (!leaf.isEmpty()) {
int v = leaf.poll();
if (degree[v] != 1) continue;
out.append(v + " " + xor[v] + "\n");
cnt++;
degree[xor[v]]--;
xor[xor[v]] ^= v;
if (degree[xor[v]] == 1) leaf.add(xor[v]);
}
out.insert(0, cnt + "\n");
System.out.print(out);
}
public static void main(String[] args) {
new MainC().run();
}
}
| Java | ["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"] | 1 second | ["2\n1 0\n2 0", "1\n0 1"] | NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor". | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"sortings",
"data structures",
"trees"
] | 14ad30e33bf8cad492e665b0a486008e | The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space. | 1,500 | In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order. | standard output | |
PASSED | 48471c3a40f8032c5aa19ed3ade865ed | train_004.jsonl | 1421053200 | Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
import java.util.concurrent.*;
public class P501C {
@SuppressWarnings("unchecked")
public void run() throws Exception {
int n = nextInt();
int [] d = new int [n];
int [] s = new int [n];
boolean [] u = new boolean [n];
ArrayList<int []> e = new ArrayList<int []>();
for (int i = 0; i < n; i++) {
d[i] += nextInt();
s[i] ^= nextInt();
int idx = i;
while ((!u[idx]) && (d[idx] == 1) && (!u[s[idx]])) {
e.add(new int [] {idx, s[idx]});
d[idx] = 0;
d[s[idx]]--;
s[s[idx]] ^= idx;
u[idx] = true;
idx = s[idx];
}
}
println(e.size());
for (int [] ee : e) {
println(ee[0] + " " + ee[1]);
}
}
public static void main(String... args) throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedOutputStream(System.out));
new P501C().run();
br.close();
pw.close();
}
static BufferedReader br;
static PrintWriter pw;
StringTokenizer stok;
String nextToken() throws IOException {
while (stok == null || !stok.hasMoreTokens()) {
String s = br.readLine();
if (s == null) { return null; }
stok = new StringTokenizer(s);
}
return stok.nextToken();
}
void print(byte b) { print("" + b); }
void print(int i) { print("" + i); }
void print(long l) { print("" + l); }
void print(double d) { print("" + d); }
void print(char c) { print("" + c); }
void print(Object o) {
if (o instanceof int[]) { print(Arrays.toString((int [])o));
} else if (o instanceof long[]) { print(Arrays.toString((long [])o));
} else if (o instanceof char[]) { print(Arrays.toString((char [])o));
} else if (o instanceof byte[]) { print(Arrays.toString((byte [])o));
} else if (o instanceof short[]) { print(Arrays.toString((short [])o));
} else if (o instanceof boolean[]) { print(Arrays.toString((boolean [])o));
} else if (o instanceof float[]) { print(Arrays.toString((float [])o));
} else if (o instanceof double[]) { print(Arrays.toString((double [])o));
} else if (o instanceof Object[]) { print(Arrays.toString((Object [])o));
} else { println("" + o); }
}
void print(String s) { pw.print(s); }
void println() { println(""); }
void println(byte b) { println("" + b); }
void println(int i) { println("" + i); }
void println(long l) { println("" + l); }
void println(double d) { println("" + d); }
void println(char c) { println("" + c); }
void println(Object o) { print("" + o); }
void println(String s) { pw.println(s); }
int nextInt() throws IOException { return Integer.parseInt(nextToken()); }
long nextLong() throws IOException { return Long.parseLong(nextToken()); }
double nextDouble() throws IOException { return Double.parseDouble(nextToken()); }
char nextChar() throws IOException { return (char) (br.read()); }
String next() throws IOException { return nextToken(); }
String nextLine() throws IOException { return br.readLine(); }
int [] readInt(int size) throws IOException {
int [] array = new int [size];
for (int i = 0; i < size; i++) { array[i] = nextInt(); }
return array;
}
long [] readLong(int size) throws IOException {
long [] array = new long [size];
for (int i = 0; i < size; i++) { array[i] = nextLong(); }
return array;
}
double [] readDouble(int size) throws IOException {
double [] array = new double [size];
for (int i = 0; i < size; i++) { array[i] = nextDouble(); }
return array;
}
String [] readLines(int size) throws IOException {
String [] array = new String [size];
for (int i = 0; i < size; i++) { array[i] = nextLine(); }
return array;
}
} | Java | ["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"] | 1 second | ["2\n1 0\n2 0", "1\n0 1"] | NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor". | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"sortings",
"data structures",
"trees"
] | 14ad30e33bf8cad492e665b0a486008e | The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space. | 1,500 | In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order. | standard output | |
PASSED | 98a04353a6c195f28aacacd3b10a0be9 | train_004.jsonl | 1421053200 | Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
public class SolutionC {
public static void main(String[] args){
new SolutionC().run();
}
int q[];
int deg[];
int x[];
int y[];
int s[];
void solve(){
int n = in.nextInt();
deg = new int[n];
s = new int[n];
x = new int[n];
y = new int[n];
q = new int[n];
int sz = 0;
int sz2 = 0;
for(int i = 0; i < n; i++){
deg[i] = in.nextInt();
s[i] = in.nextInt();
if(deg[i] <= 1){
q[sz++] = i;
}
}
while(sz > 0){
sz--;
int t = q[sz];
if( deg[t] == 0) continue;
deg[t]--;
deg[s[t]]--;
x[sz2] = t;
y[sz2] = s[t];
sz2++;
s[s[t]] ^= t;
if(deg[s[t]] == 1) {
q[sz] = s[t];
sz++;
}
}
out.println(sz2);
for(int i = 0; i < sz2; i++)
out.println(x[i] + " " + y[i]);
}
PrintWriter out;
FastScanner in;
public void run(){
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
}
class FastScanner{
BufferedReader bf;
StringTokenizer st;
public FastScanner(InputStream is){
bf = new BufferedReader(new InputStreamReader(is));
}
String next(){
while(st == null || !st.hasMoreTokens()){
try{
st = new StringTokenizer(bf.readLine());
}
catch(Exception ex){
ex.printStackTrace();
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
float nextFloat(){
return Float.parseFloat(next());
}
BigInteger nextBigInteger(){
return new BigInteger(next());
}
BigDecimal nextBigDecimal(){
return new BigDecimal(next());
}
int[] nextArray(int n){
int x[] = new int[n];
for(int i = 0; i < n; i++){
x[i] = Integer.parseInt(next());
}
return x;
}
}
}
| Java | ["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"] | 1 second | ["2\n1 0\n2 0", "1\n0 1"] | NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor". | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"sortings",
"data structures",
"trees"
] | 14ad30e33bf8cad492e665b0a486008e | The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space. | 1,500 | In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order. | standard output | |
PASSED | 1ce44cb601845179620c345fb7bfe60e | train_004.jsonl | 1421053200 | Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
static final long MODULO = (int) (1e9 + 7);
public int[] p1;
public int[] p2;
public int length;
public List<Pair> p;
int[] index;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
p = new ArrayList<Pair>();
index = new int[n];
int t1, t2;
length = 0;
for (int i = 0; i < n; i++) {
t1 = in.nextInt();
t2 = in.nextInt();
// if (t1 > 0) {
p.add(new Pair(t1, t2, length));
// }
length++;
}
Collections.sort(p);
Pair tmp;
for (int i = 0; i < n; i++){
tmp = p.get(i);
index[tmp.num] = i;
}
p1 = new int[n];
p2 = new int[n];
length = 0;
for (Pair pair : p) {
if (pair.count == 1) {
pair.change();
}
}
System.out.println(length);
for (int i = 0; i < length; i++){
System.out.println(p1[i] + " " + p2[i]);
}
//System.out.println(Arrays.toString(p1));
//System.out.println(Arrays.toString(p2));
}
class Pair implements Comparable<Pair> {
public int count;
public int x;
public int num;
public Pair(int count, int x, int num) {
this.count = count;
this.x = x;
this.num = num;
}
public void change() {
this.count--;
Pair tmp = p.get(index[x]);
//System.out.println(this.toString());
//System.out.println(tmp.toString());
tmp.count--;
tmp.x ^= num;
p1[length] = num;
p2[length++] = tmp.num;
if (tmp.count == 1) {
tmp.change();
}
}
public String toString() {
return "" + num + " " + count + " " + x;
}
@Override
public int compareTo(Pair arg0) {
// TODO Auto-generated method stub
return this.count - arg0.count;
}
}
}
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\n2 3\n1 0\n1 0", "2\n1 1\n1 0"] | 1 second | ["2\n1 0\n2 0", "1\n0 1"] | NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor". | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"sortings",
"data structures",
"trees"
] | 14ad30e33bf8cad492e665b0a486008e | The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space. | 1,500 | In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order. | standard output | |
PASSED | 7f9c4b708178c6bdc3a5154b2da896e1 | train_004.jsonl | 1421053200 | Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha. | 256 megabytes | import java.util.*;
import java.io.*;
public class CF501C {
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(bf.readLine());
int[] deg = new int[N];
int[] XOR = new int[N];
Queue<Integer> ones = new LinkedList<Integer>();
StringTokenizer st;
for (int i = 0; i < N; i++){
st = new StringTokenizer(bf.readLine());
deg[i] = Integer.parseInt(st.nextToken());
XOR[i] = Integer.parseInt(st.nextToken());
if (deg[i] == 1){
ones.add(i);
}
}
HashMap<Integer, Integer> AtoB = new HashMap<Integer, Integer>();
while (!ones.isEmpty()){
int number = ones.poll();
if (deg[number] != 0){
int key = number;
int value = XOR[number];
AtoB.put(key, value);
deg[XOR[number]]--;
XOR[XOR[number]] = XOR[XOR[number]]^number;
if (deg[XOR[number]]==1){
ones.add(XOR[number]);
}
}
}
System.out.println(AtoB.size());
for (Integer key : AtoB.keySet()) {
System.out.println(key + " " + AtoB.get(key));
}
}
}
| Java | ["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"] | 1 second | ["2\n1 0\n2 0", "1\n0 1"] | NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor". | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"sortings",
"data structures",
"trees"
] | 14ad30e33bf8cad492e665b0a486008e | The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space. | 1,500 | In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order. | standard output | |
PASSED | c2d1c28fd33a2fbb5e60e2407516bd02 | train_004.jsonl | 1421053200 | Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha. | 256 megabytes | import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.HashMap;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Rafael Regis
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
FastWriter out = new FastWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
}
class TaskC {
public void solve(int testNumber, FastReader in, FastWriter out) {
int n = in.nextInt();
Map<Integer, Triple<Integer, Integer, Integer>> m = new HashMap<>();
ArrayList<Triple<Integer, Integer, Integer>> l = new ArrayList<>();
for (int i = 0; i < n; i++) {
int d = in.nextInt();
int s = in.nextInt();
Triple<Integer, Integer, Integer> e = new Triple<>(d, s, i);
m.put(i, e);
if (e._1 == 1) {
l.add(e);
}
}
List<Pair<Integer, Integer>> g = new ArrayList<>();
while (!l.isEmpty()) {
Triple<Integer, Integer, Integer> t = l.remove(l.size() - 1);
if (t._1 == 0) continue;
Triple<Integer, Integer, Integer> a = m.get(t._2);
a._2 = a._2 ^ t._3;
a._1--;
g.add(new Pair<>(a._3, t._3));
if (a._1 == 1) {
l.add(a);
}
}
out.println(g.size());
for (Pair<Integer, Integer> p : g) {
out.println(p._1 + " " + p._2);
}
}
}
class FastReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public FastReader(InputStream stream) {
this.reader = new BufferedReader(new InputStreamReader(stream));
this.tokenizer = new StringTokenizer("");
}
public String next() {
return ensureTokens() ? tokenizer.nextToken() : null;
}
private boolean ensureTokens() {
while(!tokenizer.hasMoreTokens()){
try{
tokenizer = new StringTokenizer(reader.readLine());
} catch (Exception e){
return false;
}
}
return true;
}
public int nextInt() {
return Integer.parseInt(next());
}
}
class FastWriter {
private final PrintWriter printWriter;
public FastWriter(OutputStream stream) {
printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream)));
}
public void close() {
printWriter.close();
}
public void println(int element) {
printWriter.println(element);
}
public void println(String element) {
printWriter.println(element);
}
}
class Triple<
A extends Comparable<A>,
B extends Comparable<B>,
C extends Comparable<C>
> implements Comparable<Triple<A, B, C>> {
public A _1;
public B _2;
public C _3;
public Triple(A _1, B _2, C _3) {
this._1 = _1;
this._2 = _2;
this._3 = _3;
}
public int compareTo(Triple<A, B, C> o) {
if (_1.equals(o._1)) {
if (_2.equals(o._2)) {
return _3.compareTo(o._3);
}
return _2.compareTo(o._2);
}
return _1.compareTo(o._1);
}
}
class Pair<A extends Comparable<A>, B extends Comparable<B>> implements Comparable<Pair<A,
B>> {
public A _1;
public B _2;
public Pair(A _1, B _2) {
this._1 = _1;
this._2 = _2;
}
public int compareTo(Pair<A, B> o) {
if (_1.equals(o._1))
return _2.compareTo(o._2);
return _1.compareTo(o._1);
}
}
| Java | ["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"] | 1 second | ["2\n1 0\n2 0", "1\n0 1"] | NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor". | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"sortings",
"data structures",
"trees"
] | 14ad30e33bf8cad492e665b0a486008e | The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space. | 1,500 | In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order. | standard output | |
PASSED | b9be6f0a3b2a4ff9d8c94aa0e49e3a4c | train_004.jsonl | 1421053200 | Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha. | 256 megabytes | import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.HashMap;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Rafael Regis
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
FastWriter out = new FastWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
}
class TaskC {
public void solve(int testNumber, FastReader in, FastWriter out) {
int n = in.nextInt();
Map<Integer, Triple<Integer, Integer, Integer>> m = new HashMap<>();
ArrayList<Triple<Integer, Integer, Integer>> l = new ArrayList<>();
for (int i = 0; i < n; i++) {
int d = in.nextInt();
int s = in.nextInt();
Triple<Integer, Integer, Integer> e = new Triple<>(d, s, i);
m.put(i, e);
if (e._1 == 1) {
l.add(e);
}
}
List<Pair<Integer, Integer>> g = new ArrayList<>();
while (!l.isEmpty()) {
Triple<Integer, Integer, Integer> t = l.remove(l.size() - 1);
if (t._1 == 0) continue;
Triple<Integer, Integer, Integer> a = m.get(t._2);
a._2 = a._2 ^ t._3;
a._1--;
g.add(new Pair<>(a._3, t._3));
if (a._1 == 1) {
l.add(a);
}
}
out.println(g.size());
for (Pair<Integer, Integer> p : g) {
out.println(p._1 + " " + p._2);
}
}
}
class FastReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public FastReader(InputStream stream) {
this.reader = new BufferedReader(new InputStreamReader(stream));
this.tokenizer = new StringTokenizer("");
}
public String next() {
return ensureTokens() ? tokenizer.nextToken() : null;
}
private boolean ensureTokens() {
while(!tokenizer.hasMoreTokens()){
try{
tokenizer = new StringTokenizer(reader.readLine());
} catch (Exception e){
return false;
}
}
return true;
}
public int nextInt() {
return Integer.parseInt(next());
}
}
class FastWriter {
private final PrintWriter printWriter;
public FastWriter(OutputStream stream) {
printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream)));
}
public void close() {
printWriter.close();
}
public void println(int element) {
printWriter.println(element);
}
public void println(String element) {
printWriter.println(element);
}
}
class Triple<
A extends Comparable<A>,
B extends Comparable<B>,
C extends Comparable<C>
> implements Comparable<Triple<A, B, C>> {
public A _1;
public B _2;
public C _3;
public Triple(A _1, B _2, C _3) {
this._1 = _1;
this._2 = _2;
this._3 = _3;
}
public int compareTo(Triple<A, B, C> o) {
if (_1.equals(o._1)) {
if (_2.equals(o._2)) {
return _3.compareTo(o._3);
}
return _2.compareTo(o._2);
}
return _1.compareTo(o._1);
}
}
class Pair<A extends Comparable<A>, B extends Comparable<B>> implements Comparable<Pair<A,
B>> {
public A _1;
public B _2;
public Pair(A _1, B _2) {
this._1 = _1;
this._2 = _2;
}
public int compareTo(Pair<A, B> o) {
if (_1.equals(o._1))
return _2.compareTo(o._2);
return _1.compareTo(o._1);
}
}
| Java | ["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"] | 1 second | ["2\n1 0\n2 0", "1\n0 1"] | NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor". | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"sortings",
"data structures",
"trees"
] | 14ad30e33bf8cad492e665b0a486008e | The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space. | 1,500 | In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order. | standard output | |
PASSED | 788f931068a0064824d7ab3c5815abf4 | train_004.jsonl | 1421053200 | Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha. | 256 megabytes | import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeSet;
public class B {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
long m = sc.nextInt();
final List<Integer> degree = new ArrayList<Integer>();
List<Integer> xor = new ArrayList<Integer>();
for(int i = 0; i < m; i++) {
degree.add(sc.nextInt());
xor.add(sc.nextInt());
}
long edges = 0;
Map<Integer, ArrayList<Integer>> nodes = new HashMap<Integer, ArrayList<Integer>>();
TreeSet<Integer> process = new TreeSet<Integer>(new Comparator<Integer>(){
@Override
public int compare(Integer a, Integer b) {
if (degree.get(a).compareTo(degree.get(b)) != 0) {
return degree.get(a).compareTo(degree.get(b));
}
return a.compareTo(b);
}
});
for(int i = 0; i < m; i++) {
process.add(i);
}
while(!process.isEmpty()) {
int current = process.first();
process.remove(current);
if(degree.get(current) == 0) {
continue;
}
int other = xor.get(current);
if(!nodes.containsKey(current)) {
nodes.put(current, new ArrayList<Integer>());
}
nodes.get(current).add(other);
edges++;
process.remove(other);
xor.set(other, xor.get(other) ^ current);
degree.set(other, degree.get(other) - 1);
process.add(other);
}
System.out.println(edges);
for(Map.Entry<Integer, ArrayList<Integer>> e : nodes.entrySet()) {
for(int o : e.getValue()) {
System.out.println(e.getKey() + " " + o);
}
}
}
}
| Java | ["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"] | 1 second | ["2\n1 0\n2 0", "1\n0 1"] | NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor". | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"sortings",
"data structures",
"trees"
] | 14ad30e33bf8cad492e665b0a486008e | The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space. | 1,500 | In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order. | standard output | |
PASSED | d0d27631bc8706a7afae83d74a12cce2 | train_004.jsonl | 1421053200 | Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha. | 256 megabytes | import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class MishaForest {
private static Scanner in;
public static void main(String[] args ) {
in = new Scanner(System.in);
int n = in.nextInt();
int[] deg = new int[n];
int[] xor = new int[n];
Set<Integer> deg1 = new HashSet<Integer>();
int edges=0;
for(int i=0; i<n; i++) {
deg[i] = in.nextInt();
xor[i] = in.nextInt();
edges += deg[i];
if(deg[i]==1)
deg1.add(i);
}
edges/=2;
System.out.println(edges);
for(int i : deg1) {
int x = i;
while(deg[x] == 1) {
System.out.println(x + " " + xor[x]);
int y = xor[x];
deg[y]--;
xor[y]^=x;
x=y;
}
}
}
} | Java | ["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"] | 1 second | ["2\n1 0\n2 0", "1\n0 1"] | NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor". | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"sortings",
"data structures",
"trees"
] | 14ad30e33bf8cad492e665b0a486008e | The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space. | 1,500 | In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order. | standard output | |
PASSED | de604dae5de0a0eda38f89085daed795 | train_004.jsonl | 1421053200 | Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha. | 256 megabytes | import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class MishaForest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] d = new int[n];
int[] s = new int[n];
int ans = 0;
Queue<Integer> queue = new LinkedList<Integer>();
for (int i = 0; i < n; i++) {
d[i] = in.nextInt();
s[i] = in.nextInt();
if (d[i] == 1)
queue.add(i);
}
ArrayList<int[]> res = new ArrayList<int[]>();
while (!queue.isEmpty()) {
int u = queue.poll();
if (d[u] == 0)
continue;
d[u]--;
int v = s[u];
d[v]--;
s[v] = s[v] ^ u;
if (d[v] == 1)
queue.add(v);
int[] edge = new int[2];
edge[0] = u;
edge[1] = v;
res.add(edge);
}
System.out.println(res.size());
for (int i = 0; i < res.size(); i++)
System.out.println(res.get(i)[0] + " " + res.get(i)[1]);
}
}
| Java | ["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"] | 1 second | ["2\n1 0\n2 0", "1\n0 1"] | NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor". | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"sortings",
"data structures",
"trees"
] | 14ad30e33bf8cad492e665b0a486008e | The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space. | 1,500 | In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order. | standard output | |
PASSED | b9b0468208e1c181e92601b168d685d0 | train_004.jsonl | 1421053200 | Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int[] D = new int[N];
int[] X = new int[N];
Queue<Integer> queue = new LinkedList<Integer>();
for (int i = 0; i < N; i++) {
D[i] = scanner.nextInt();
X[i] = scanner.nextInt();
if (D[i] == 1) {
queue.add(i);
}
}
List<int[]> answers = new ArrayList<int[]>();
while (!queue.isEmpty()) {
int v = (int) queue.poll();
int d = X[v];
if (D[v] == 1) {
answers.add(new int[] { v, d });
X[d] = X[d] ^ v;
D[d]--;
if (D[d] == 1) {
queue.add(d);
}
}
}
System.out.println(answers.size());
for (int i = 0; i < answers.size(); i++) {
int[] a = (int[]) answers.get(i);
System.out.println(a[0] + " " + a[1]);
}
}
}
| Java | ["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"] | 1 second | ["2\n1 0\n2 0", "1\n0 1"] | NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor". | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"sortings",
"data structures",
"trees"
] | 14ad30e33bf8cad492e665b0a486008e | The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space. | 1,500 | In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order. | standard output | |
PASSED | 06c8262e0c65bb625e4cc2f3ac26ef55 | train_004.jsonl | 1421053200 | Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main{
BufferedReader in;
StringTokenizer str = null;
PrintWriter out;
private String next() throws Exception{
while (str == null || !str.hasMoreElements())
str = new StringTokenizer(in.readLine());
return str.nextToken();
}
private int nextInt() throws Exception{
return Integer.parseInt(next());
}
public void run() throws Exception{
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
int n = nextInt();
int []d = new int[n];
int []s = new int[n];
for(int i = 0; i < n; ++i) {
d[i] = nextInt();
s[i] = nextInt();
}
boolean inqueue[] = new boolean[n];
Queue<Integer> q = new LinkedList<Integer>();
for(int i = 0; i < n; ++i) {
if (d[i] == 1) {
q.add(i);
inqueue[i] = true;
}
}
List<int[]> ans = new LinkedList<int[]>();
while(q.size() > 0) {
int x = q.poll();
if (d[x] == 0) continue;
int parent = s[x];
if (d[parent] > 0) {
ans.add(new int[]{x, parent});
s[parent] ^= x;
d[parent]--;
if (d[parent] == 1) {
q.add(parent);
}
}
}
out.println(ans.size());
for(int []i : ans) {
out.println(i[0] + " " + i[1]);
}
out.close();
}
public static void main(String args[]) throws Exception{
new Main().run();
}
} | Java | ["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"] | 1 second | ["2\n1 0\n2 0", "1\n0 1"] | NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor". | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"sortings",
"data structures",
"trees"
] | 14ad30e33bf8cad492e665b0a486008e | The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space. | 1,500 | In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order. | standard output | |
PASSED | 68977a41d180210062aeb08df8c66636 | train_004.jsonl | 1421053200 | Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha. | 256 megabytes | import java.io.*;
import java.util.*;
public class C {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int n = Integer.parseInt(br.readLine());
HashMap<Integer, Integer> hm1 = new HashMap<Integer, Integer>();
HashMap<Integer, Integer> hm2 = new HashMap<Integer, Integer>();
int sum = 0;
Queue<Integer> q = new LinkedList<Integer>();
StringTokenizer st = null;//new StringTokenizer(br.readLine());
for (int i = 0; i < n; ++i) {
st = new StringTokenizer(br.readLine());
int edges = Integer.parseInt(st.nextToken());
int xor = Integer.parseInt(st.nextToken());
sum += edges;
hm1.put(i, edges);
hm2.put(i, xor);
if (edges == 1)
q.add(i);
}
out.println(sum/2);
while(!q.isEmpty()) {
int num = q.remove();
if (hm1.get(num) == 1) {
hm1.put(num, 0);
int connected = hm2.get(num);
out.println(num + " " + connected);
int remaining = hm2.get(connected)^num;
int edges = hm1.get(connected);
hm1.put(connected, edges-1);
hm2.put(connected, remaining);
if (edges-1 == 1) {
q.add(connected);
}
}
}
out.flush();
out.close();
System.exit(0);
}
}
| Java | ["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"] | 1 second | ["2\n1 0\n2 0", "1\n0 1"] | NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor". | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"sortings",
"data structures",
"trees"
] | 14ad30e33bf8cad492e665b0a486008e | The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space. | 1,500 | In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order. | standard output | |
PASSED | 28637c29f6ce4003c26632bef039fb66 | train_004.jsonl | 1421053200 | Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha. | 256 megabytes | import java.io.InputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CFS501C {
public final static String IN_FILE = "test/CFS501C.in";
public final static String OUT_FILE = "test/CFS501C.out";
static class G {
int v;
int d;
int s;
}
static class P {
int x;
int y;
}
public static void main(String[] args) throws Exception {
// InputStream in = new FileInputStream(IN_FILE);
//
// @SuppressWarnings("resource")
// PrintStream out = new PrintStream(OUT_FILE);
InputStream in = System.in;
PrintStream out = System.out;
Scanner IN = new Scanner(in);
int n = IN.nextInt();
G[] M = new G[n];
List<G> queue = new ArrayList<G>();
for (int i = 0; i < n; i++) {
G g = new G();
g.v = i;
g.d = IN.nextInt();
g.s = IN.nextInt();
if (g.d == 1)
queue.add(g);
M[i] = g;
}
IN.close();
List<P> list = new ArrayList<P>();
while (queue.size() > 0) {
List<G> newQueue = new ArrayList<G>();
for (G m : queue) {
if(m.d != 1) {
continue;
}
G x = M[m.s];
x.s ^= m.v;
x.d--;
if (x.d == 1) {
newQueue.add(x);
}
P p = new P();
p.x = m.v;
p.y = m.s;
list.add(p);
}
queue = newQueue;
}
out.println(list.size());
for (P p : list)
out.println(p.x + " " + p.y);
}
}
| Java | ["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"] | 1 second | ["2\n1 0\n2 0", "1\n0 1"] | NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor". | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"sortings",
"data structures",
"trees"
] | 14ad30e33bf8cad492e665b0a486008e | The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space. | 1,500 | In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order. | standard output | |
PASSED | f0d4aba0e6705e1c12a8e21d20c5687f | train_004.jsonl | 1421053200 | Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main( String args[] ) throws IOException {
BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );
PrintWriter pw = new PrintWriter( System.out );
int T = Integer.parseInt( br.readLine() );
Node[] V = new Node[T];
LinkedList<Node> b = new LinkedList<Node>();
ArrayList<Ans> ans = new ArrayList<Ans>();
for( int i = 0; i < T; i++ ){
String ar[] = br.readLine().split(" ");
Node s = new Node( i, Integer.parseInt( ar[0] ), Integer.parseInt( ar[1] ) );
V[i] = s;
if( s.in == 1 ) b.add( s );
}
// for( Node v : b ){
// pw.printf( "%d %d %d\n", v.ind, v.in, v.x );
// }
// pw.println();
// pw.flush();
while( b.size() > 0 ){
// Collections.sort( b );
// pw.println("CurrSize: " + b.size() );
Node cu = b.poll();
if( cu.in == 0 ) continue;
// pw.printf("%d %d %d\n", cu.ind, cu.in, cu.x );
// pw.flush();
cu.in = 0;
ans.add( new Ans( cu.ind, cu.x ) );
V[cu.x].x ^= cu.ind;
V[cu.x].in--;
if( V[cu.x].in == 1 ) {
// pw.printf( "Added %d %d %d to queue\n", V[cu.x].ind, V[cu.x].in, V[cu.x].x );
// pw.flush();
b.add( V[cu.x] );
}
// pw.printf( "Added %d %d\n", cu.ind, cu.x );
// pw.flush();
// pw.println("End loop" );
// pw.flush();
}
pw.println( ans.size() );
for( Ans a : ans ){
pw.printf( "%d %d\n", a.s, a.t );
}
pw.close();
}
}
class Node implements Comparable {
int ind, in, x;
public Node( int a, int b, int c ){
ind = a;
in = b;
x = c;
}
public int compareTo( Object other ){
Node o = (Node) other;
if( in == o.in ){
if( x == o.x ) return ind - o.ind;
return x - o.x;
} return in - o.in;
}
}
class Ans {
int s, t;
public Ans( int a, int b ){
s = a;
t = b;
}
} | Java | ["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"] | 1 second | ["2\n1 0\n2 0", "1\n0 1"] | NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor". | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"sortings",
"data structures",
"trees"
] | 14ad30e33bf8cad492e665b0a486008e | The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space. | 1,500 | In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order. | standard output | |
PASSED | add47f74d888b6b16139b35033fa3105 | train_004.jsonl | 1421053200 | Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main implements Runnable {
public void solve() throws IOException {
int N = nextInt();
int[] degree = new int[N];
int[] xorValue = new int[N];
int degreeSum = 0;
LinkedList<Integer> ll = new LinkedList<Integer>();
for(int i = 0; i < N; i++){
degree[i] = nextInt();
xorValue[i] = nextInt();
if(degree[i] == 1) ll.add(i);
degreeSum += degree[i];
}
out.println(degreeSum / 2);
while(!ll.isEmpty()){
int i = ll.poll();
int other = xorValue[i];
if(degree[i] == 0) continue;
out.println(i + " " + other);
degree[i]--;
degree[other]--;
xorValue[i] ^= other;
xorValue[other] ^= i;
if(degree[other] == 1) ll.add(other);
}
}
//-----------------------------------------------------------
public static void main(String[] args) {
new Main().run();
}
public void debug(Object... arr){
System.out.println(Arrays.deepToString(arr));
}
public void print1Int(int[] a){
for(int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
System.out.println();
}
public void print2Int(int[][] a){
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[0].length; j++){
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
tok = null;
solve();
in.close();
out.close();
} catch (IOException e) {
System.exit(0);
}
}
public String nextToken() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
PrintWriter out;
BufferedReader in;
StringTokenizer tok;
} | Java | ["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"] | 1 second | ["2\n1 0\n2 0", "1\n0 1"] | NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor". | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"sortings",
"data structures",
"trees"
] | 14ad30e33bf8cad492e665b0a486008e | The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space. | 1,500 | In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order. | standard output | |
PASSED | ceb5431af221fbb7a8fc624ac368ddd7 | train_004.jsonl | 1421053200 | Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha. | 256 megabytes | import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution{
int verticeCount;
int[] degree;
int[] xor;
public void solve(){
Scanner scan = new Scanner(System.in);
int count = 0;
// get degrees and xor sum of adjacent vertices from standard input
verticeCount = scan.nextInt();
degree = new int[verticeCount];
xor = new int[verticeCount];
for (int i = 0; i < verticeCount; i++){
degree[i] = scan.nextInt();
count += degree[i];
xor[i] = scan.nextInt();
}
System.out.println(count / 2);
// use a dfs scan to output
for (int i = 0; i < verticeCount; i++){
if(degree[i] != 1)
continue;
int index = i;
while (degree[index] == 1){
System.out.println(index + " " + xor[index]);
degree[index] --;
int nextIndex = xor[index];
xor[nextIndex] ^= index;
degree[nextIndex] --;
xor[index] = 0;
index = nextIndex;
}
}
scan.close();
}
public static void main(String[] args){
Solution solution = new Solution();
solution.solve();
}
} | Java | ["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"] | 1 second | ["2\n1 0\n2 0", "1\n0 1"] | NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor". | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"sortings",
"data structures",
"trees"
] | 14ad30e33bf8cad492e665b0a486008e | The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space. | 1,500 | In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order. | standard output | |
PASSED | 67db81bec2fb58efce12aaa3eae22c03 | train_004.jsonl | 1421053200 | Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class CF285C {
private FastScanner in;
private PrintWriter out;
class Pair {
int a, b;
public Pair(int a, int b){
this.a = a;
this.b = b;
}
}
public void solve() throws IOException {
int n = in.nextInt();
int[] degree = new int[n];
int[] sum = new int[n];
Queue<Integer> q = new LinkedList<Integer>();
ArrayList<Integer> edges = new ArrayList<Integer>();
for (int i = 0; i < n; i++){
int a = in.nextInt();
int b = in.nextInt();
degree[i] = a;
sum[i] = b;
if (a == 1){
q.add(i);
}
}
while (!q.isEmpty()){
int next = q.poll();
if (degree[next] != 1) continue;
int s = sum[next];
if (degree[s] - 1 == 1){
q.add(s);
}
degree[s]--;
sum[s] ^= next;
edges.add(next);
edges.add(s);
}
out.println(edges.size()/2);
for (int i = 0; i < edges.size(); i += 2){
out.println(edges.get(i) + " " + edges.get(i+1));
}
}
public static void main(String[] args) {
new CF285C().run();
}
public void run() {
try {
in = new FastScanner();
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private class FastScanner {
private BufferedReader br;
private StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
| Java | ["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"] | 1 second | ["2\n1 0\n2 0", "1\n0 1"] | NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor". | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"sortings",
"data structures",
"trees"
] | 14ad30e33bf8cad492e665b0a486008e | The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space. | 1,500 | In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order. | standard output | |
PASSED | edf019253d10fe5d0e3d19bb150d1e2e | train_004.jsonl | 1421053200 | Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha. | 256 megabytes | import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class SolveContest {
private BufferedReader in;
private PrintWriter out;
public SolveContest() {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter(new FileWriter("output.txt"),true);
solve();
} catch (Exception e) {
e.printStackTrace();
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
} finally {
try {
in.close();
} catch (IOException e) {
}
out.close();
}
}
StringTokenizer st;
String nextToken() {
while (st == null || !st.hasMoreTokens())
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
}
return st.nextToken();
}
int nextInt() {
return Integer.valueOf(nextToken());
}
long nextLong() {
return Long.valueOf(nextToken());
}
public void solve() {
int n = nextInt();
TreeSet<Node> set = new TreeSet<Node>();
Pair[] ps = new Pair[n];
for (int i = 0; i < n; i++) {
int deg = nextInt();
int s = nextInt();
set.add(new Node(i, deg, s));
ps[i] = new Pair(deg,s);
}
List<Pair> edges = new ArrayList<Pair>();
while(!set.isEmpty()) {
Node leaf = set.pollFirst();
if (leaf.degree == 0) continue;
edges.add(new Pair(leaf.i, leaf.xor));
leaf.degree -= 1;
Pair p = ps[leaf.xor];
p.b ^= leaf.i;
set.remove(new Node(leaf.xor, p.a, 1));
p.a--;
set.add(new Node(leaf.xor,p.a,p.b));
if (leaf.degree <= 1) {
set.add(leaf);
}
}
out.println(edges.size());
for (int i = 0; i < edges.size(); i++) {
out.println(edges.get(i).a + " " + edges.get(i).b);
}
}
public static void main(String[] args) {
new SolveContest();
}
}
class Node implements Comparable<Node>{
int i;
int degree;
int xor;
public Node(int i, int degree, int xor) {
this.i = i;
this.degree = degree;
this.xor = xor;
}
@Override
public int compareTo(Node o) {
if (degree-o.degree == 0)
return i-o.i;
return degree-o.degree;
}
@Override
public String toString() {
return i+" " + degree + " " + xor;
}
}
class Pair {
int a;
int b;
public Pair(int a, int b) {
this.a = a;
this.b = b;
}
}
| Java | ["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"] | 1 second | ["2\n1 0\n2 0", "1\n0 1"] | NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor". | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"sortings",
"data structures",
"trees"
] | 14ad30e33bf8cad492e665b0a486008e | The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space. | 1,500 | In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order. | standard output | |
PASSED | fe10493d86fac1eed41440d1defbd896 | train_004.jsonl | 1421053200 | Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha. | 256 megabytes | import java.util.*;
import java.io.*;
public class MishaForest
{
public static void main(String[]args)
{
InputReader1 sc = new InputReader1(System.in);
int N = sc.nextInt();
int DEG[]=new int[N] , XORSUM[]=new int[N];
Queue<Integer>Q = new LinkedList<Integer>();
int used = 0 ;
for(int i = 0 ; i < N ; i++)
{
DEG[i] = sc.nextInt();
XORSUM[i] = sc.nextInt();
if(DEG[i] == 1)
Q.add(i);
}
ArrayList<pair> ANS = new ArrayList<pair>();
while(!Q.isEmpty())
{
int from = Q.poll();
if(DEG[from] == 0) continue;
DEG[from]--;
int to = XORSUM[from];
XORSUM[from]=0;
ANS.add(new pair(from,to));
XORSUM[to]^=from;
DEG[to]--;
if(DEG[to]==1)Q.add(to);
}
System.out.println(ANS.size());
for(pair x:ANS)
System.out.println(x.first+" "+x.second);
}
}
class pair
{
int first , second;
public pair(int first , int second)
{
this.first = first;
this.second = second;
}
}
class InputReader1
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader1(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c & 15;
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public 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 & 15;
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
//while (c != '\n' && c != '\r' && c != '\t' && c != -1)
//c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (c != '\n' && c != '\r' && c != '\t' && c != -1);
return res.toString();
}
public static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
} | Java | ["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"] | 1 second | ["2\n1 0\n2 0", "1\n0 1"] | NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor". | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"sortings",
"data structures",
"trees"
] | 14ad30e33bf8cad492e665b0a486008e | The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space. | 1,500 | In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order. | standard output | |
PASSED | e104353454591a4f7f81b2051cdcd3ae | train_004.jsonl | 1421053200 | Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha. | 256 megabytes | import java.util.*;
public class CF501Cii {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int[] Deg = new int[N];
int[] Sum = new int[N];
//
Queue<Integer> queue = new LinkedList<Integer>();
for (int i = 0; i < N; i++) {
Deg[i] = scanner.nextInt();
Sum[i] = scanner.nextInt();
if (Deg[i] == 1) {
queue.add(i);
}
}
List<int[]> answers = new ArrayList<int[]>();
while (!queue.isEmpty()) {
int v = queue.poll();
int d = Sum[v];
if (Deg[v] == 1) {
answers.add(new int[] { v, d });
Sum[d] = Sum[d] ^ v;
Deg[d]--;
if (Deg[d] == 1) {
queue.add(d);
}
}
}
System.out.println(answers.size());
for (int i = 0; i < answers.size(); i++) {
int[] a = answers.get(i);
System.out.println(a[0] + " " + a[1]);
}
}
} | Java | ["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"] | 1 second | ["2\n1 0\n2 0", "1\n0 1"] | NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor". | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"sortings",
"data structures",
"trees"
] | 14ad30e33bf8cad492e665b0a486008e | The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space. | 1,500 | In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order. | standard output | |
PASSED | 77ccb843f5a43c31bb072c885a96cdb0 | train_004.jsonl | 1421053200 | Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha. | 256 megabytes | /*
ID: wilbs43
LANG: JAVA7
STATUS: incomplete
*/
import java.util.*;
public class CF501Ci {
// static TreeMap<Integer, TreeSet<Integer>> map;
// static Point vert[];
public static void main(String[] args) {
// Scanner in = new Scanner(new File("CF501C.in"));
Scanner in = new Scanner(System.in);
int N = in.nextInt();
int[] Deg = new int[N];
int[] Sum = new int[N];
// vert = new Point[n];
Queue<Integer> q = new LinkedList<Integer>();
for (int i = 0; i < N; i++) {
// String line[] = in.nextLine().split(" ");
Deg[i] = in.nextInt();
Sum[i] = in.nextInt();
if (Deg[i] == 1) {
q.add(i);
}
}
List<int[]> answers = new ArrayList<int[]>();
while (!q.isEmpty()) {
int v = q.poll();
int d = Sum[v];
if (Deg[v] == 1) {
answers.add(new int[] { v, d });
Sum[d] ^= v;
Deg[d]--;
if (Deg[d] == 1) {
q.add(d);
}
}
}
System.out.println(answers.size());
for (int i = 0; i < answers.size(); i++) {
int[] a = answers.get(i);
System.out.println(a[0] + " " + a[1]);
}
}
}
| Java | ["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"] | 1 second | ["2\n1 0\n2 0", "1\n0 1"] | NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor". | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"sortings",
"data structures",
"trees"
] | 14ad30e33bf8cad492e665b0a486008e | The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space. | 1,500 | In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order. | standard output | |
PASSED | 0b78386ed5ffe08eb88877149052aeac | train_004.jsonl | 1421053200 | Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha. | 256 megabytes | /*
ID: wilbs43
LANG: JAVA7
STATUS: incomplete
*/
import java.util.*;
public class CF501Ci {
// static TreeMap<Integer, TreeSet<Integer>> map;
// static Point vert[];
public static void main(String[] args) {
// Scanner in = new Scanner(new File("CF501C.in"));
Scanner in = new Scanner(System.in);
int N = in.nextInt();
int[] Deg = new int[N];
int[] Sum = new int[N];
// vert = new Point[n];
Queue<Integer> q = new LinkedList<Integer>();
for (int i = 0; i < N; i++) {
// String line[] = in.nextLine().split(" ");
Deg[i] = in.nextInt();
Sum[i] = in.nextInt();
if (Deg[i] == 1) {
q.add(i);
}
}
int ct = 0;
String out = "";
List<int[]> answers = new ArrayList<int[]>();
while (!q.isEmpty()) {
int v = q.poll();
int d = Sum[v];
if (Deg[v] == 1) {
answers.add(new int[] { v, d });
// out += v + " " + d;
ct++;
Sum[d] ^= v;
Deg[d]--;
if (Deg[d] == 1) {
q.add(d);
}
}
}
System.out.println(answers.size());
for (int i = 0; i < answers.size(); i++) {
int[] a = answers.get(i);
System.out.println(a[0] + " " + a[1]);
}
}
}
| Java | ["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"] | 1 second | ["2\n1 0\n2 0", "1\n0 1"] | NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor". | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"sortings",
"data structures",
"trees"
] | 14ad30e33bf8cad492e665b0a486008e | The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space. | 1,500 | In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order. | standard output | |
PASSED | 641299b80c98626e6496149f7bc855a1 | train_004.jsonl | 1451487900 | Limak is a little polar bear. In the snow he found a scroll with the ancient prophecy. Limak doesn't know any ancient languages and thus is unable to understand the prophecy. But he knows digits!One fragment of the prophecy is a sequence of n digits. The first digit isn't zero. Limak thinks that it's a list of some special years. It's hard to see any commas or spaces, so maybe ancient people didn't use them. Now Limak wonders what years are listed there.Limak assumes three things: Years are listed in the strictly increasing order; Every year is a positive integer number; There are no leading zeros. Limak is going to consider all possible ways to split a sequence into numbers (years), satisfying the conditions above. He will do it without any help. However, he asked you to tell him the number of ways to do so. Since this number may be very large, you are only asked to calculate it modulo 109 + 7. | 512 megabytes | import java.util.*;
import java.io.*;
public class C
{
public static void main(String[] args)
{
new C().solve();
}
FasterScanner in=new FasterScanner();
PrintWriter out=new PrintWriter(System.out);
int mod=(int)(1e9)+7;
public void solve()
{
int n=in.nextInt();
String str=in.nextLine();
int[][] cmp=new int[n][n+1];
int[][] fnl=new int[n][n+1];
for(int i=0;i<cmp.length;i++)
Arrays.fill(fnl[i],-2);
for(int len=1;len<=n;len++)
{
if(n-2*len>=0)
{
int f=n-2*len;
int s=n-len;
int idx=-1;
for(int i=0;i<len;i++)
{
if(str.charAt(f+i)!=str.charAt(s+i))
{
idx=i;
if(str.charAt(f+i)>str.charAt(s+i))
{
fnl[f][len]=1;
}
else
{
fnl[f][len]=-1;
}
break;
}
}
cmp[f][len]=idx;
if(cmp[f][len]==-1)
{
fnl[f][len]=0;
}
}
for(int i=n-2*len-1;i>=0;i--)
{
if(str.charAt(i)!=str.charAt(i+len))
{
cmp[i][len]=0;
}
else
{
if(cmp[i+1][len]==-1 || cmp[i+1][len]==len-1)
{
cmp[i][len]=-1;
}
else
{
cmp[i][len]=cmp[i+1][len]+1;
}
}
if(cmp[i][len]==-1)
{
fnl[i][len]=0;
}
else if(str.charAt(i+cmp[i][len])>str.charAt(i+len+cmp[i][len]))
{
fnl[i][len]=1;
}
else
{
fnl[i][len]=-1;
}
}
}
// for(int i=0;i<cmp.length;i++)
// {
// System.out.println(Arrays.toString(cmp[i]));
// }
// System.out.println("fnl");
// for(int i=0;i<fnl.length;i++)
// {
// System.out.println(Arrays.toString(fnl[i]));
// }
long[][] dp=new long[n][n+1];
for(int i=0;i<n;i++)
{
if(str.charAt(i)!='0')
dp[i][n-i]=1;
}
// long ans=1;
for(int len=n-1;len>0;len--)
{
for(int i=n-len-1;i>=0;i--)
{
if(str.charAt(i)=='0' || fnl[i][len]==-2)
dp[i][len]=0;
else if(fnl[i][len]==-1)
{
dp[i][len]=dp[i+len][len];
}
else
{
dp[i][len]=dp[i+len][len+1];
}
dp[i][len]+=dp[i][len+1];
dp[i][len]%=mod;
}
//ans+=dp[0][len];
//ans%=mod;
}
// System.out.println("fnl");
// for(int i=0;i<dp.length;i++)
// {
// System.out.println(Arrays.toString(dp[i]));
// }
out.println(dp[0][1]);
out.close();
}
class s implements Comparable<s>
{
int time;
int floor;
public s(int t,int f)
{
this.time=t;
this.floor=f;
}
@Override
public int compareTo(s o) {
// TODO Auto-generated method stub
if(this.floor!=o.floor)
return Integer.compare(this.floor, o.floor);
else
return Integer.compare(this.time, o.time);
}
}
public static class FasterScanner {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = System.in.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
private boolean isEndOfLine(int c) {
return c=='\n' || c=='\r' || c==-1;
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c=='\n' || c=='\r' || c==-1 || c==' ' || c=='\t';
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n)
{
int[] arr=new int[n];
for(int i=0;i<n;i++)
{
arr[i]=nextInt();
}
return arr;
}
public long[] nextLongArray(int n)
{
long[] arr=new long[n];
for(int i=0;i<n;i++)
{
arr[i]=nextLong();
}
return arr;
}
public int[] nextIntArray10(int n)
{
int[] arr=new int[n+1];
for(int i=1;i<=n;i++)
{
arr[i]=nextInt();
}
return arr;
}
public long[] nextLongArray10(int n)
{
long[] arr=new long[n+1];
for(int i=1;i<=n;i++)
{
arr[i]=nextLong();
}
return arr;
}
public int[] nextIntArray11(int n)
{
int[] arr=new int[n+2];
for(int i=1;i<=n;i++)
{
arr[i]=nextInt();
}
return arr;
}
public long[] nextLongArray11(int n)
{
long[] arr=new long[n+2];
for(int i=1;i<=n;i++)
{
arr[i]=nextLong();
}
return arr;
}
}
} | Java | ["6\n123434", "8\n20152016"] | 2.5 seconds | ["8", "4"] | NoteIn the first sample there are 8 ways to split the sequence: "123434" = "123434" (maybe the given sequence is just one big number) "123434" = "1" + "23434" "123434" = "12" + "3434" "123434" = "123" + "434" "123434" = "1" + "23" + "434" "123434" = "1" + "2" + "3434" "123434" = "1" + "2" + "3" + "434" "123434" = "1" + "2" + "3" + "4" + "34" Note that we don't count a split "123434" = "12" + "34" + "34" because numbers have to be strictly increasing.In the second sample there are 4 ways: "20152016" = "20152016" "20152016" = "20" + "152016" "20152016" = "201" + "52016" "20152016" = "2015" + "2016" | Java 7 | standard input | [
"dp",
"hashing",
"strings"
] | 1fe6daf718b88cabb2e956e81add3719 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of digits. The second line contains a string of digits and has length equal to n. It's guaranteed that the first digit is not '0'. | 2,000 | Print the number of ways to correctly split the given sequence modulo 109 + 7. | standard output | |
PASSED | 1e3789f2d874a0a86c48d12dc32f5856 | train_004.jsonl | 1451487900 | Limak is a little polar bear. In the snow he found a scroll with the ancient prophecy. Limak doesn't know any ancient languages and thus is unable to understand the prophecy. But he knows digits!One fragment of the prophecy is a sequence of n digits. The first digit isn't zero. Limak thinks that it's a list of some special years. It's hard to see any commas or spaces, so maybe ancient people didn't use them. Now Limak wonders what years are listed there.Limak assumes three things: Years are listed in the strictly increasing order; Every year is a positive integer number; There are no leading zeros. Limak is going to consider all possible ways to split a sequence into numbers (years), satisfying the conditions above. He will do it without any help. However, he asked you to tell him the number of ways to do so. Since this number may be very large, you are only asked to calculate it modulo 109 + 7. | 512 megabytes | //package practice;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class NewYearAndAncientProphecy {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
// System.out.println("n : " + n);
String num = scanner.nextLine();
num = scanner.nextLine();
// System.out.println("num : " + num);
int[][] dp = new int[n + 1][n + 1];
int[][] nxt = new int[n + 1][n + 1];
for (int i = 1; i <= n; i++) {
nxt[i][i] = 1000000;
}
for (int i = n; i >= 1; i--) {
for (int j = n; j > i; j--) {
if (num.charAt(i - 1) != num.charAt(j - 1)) {
nxt[i][j] = 0;
} else {
if (i == n || j == n) {
nxt[i][j] = 1000000;
} else {
nxt[i][j] = nxt[i + 1][j + 1] + 1;
}
}
}
}
// print(nxt);
Set<Integer> zpos = new HashSet<Integer>();
for (int i = 0; i < num.length(); i++) {
if (num.charAt(i) == '0') {
zpos.add(i);
}
}
int MOD = 1000000007;
for (int i = 1; i <= n; i++) {
dp[i][i] = 1;
}
for (int i = 2; i <= n; i++) {
for (int j = 1; j <= i; j++) {
// System.out.println("i : " + i);
// System.out.println("j : " + j);
if (zpos.contains(i - j)) {
dp[i][j] = dp[i][j - 1];
continue;
}
int mxk = Math.min(i - j, j);
if (mxk < j) {
dp[i][j] += dp[i - j][mxk];
if (dp[i][j] >= MOD) {
dp[i][j] -= MOD;
}
} else {
dp[i][j] += dp[i - j][mxk - 1];
if (!zpos.contains(i - 2 * j)) {
int mmpos = nxt[i - 2 * j + 1][i - j + 1];
if (mmpos < j) {
// compare the two chars
if (num.charAt(i - 2 * j + mmpos) < num.charAt(i
- j + mmpos)) {
int tmp = dp[i - j][mxk] - dp[i - j][mxk - 1];
if (tmp < 0) {
tmp += MOD;
}
dp[i][j] += tmp;
if (dp[i][j] >= MOD) {
dp[i][j] -= MOD;
}
}
}
}
/*
* if (!zpos.contains(i - 2 * j)) { String p =
* num.substring(i - 2 * j, i - j); String s =
* num.substring(i - j, i); if (s.compareTo(p) > 0) { int
* tmp = dp[i - j][mxk] - dp[i - j][mxk - 1]; if (tmp < 0) {
* tmp += MOD; } dp[i][j] += tmp; if (dp[i][j] >= MOD) {
* dp[i][j] -= MOD; } } }
*/
}
dp[i][j] += dp[i][j - 1];
if (dp[i][j] >= MOD) {
dp[i][j] -= MOD;
}
}
}
// System.out.println("dp : ");
// print(dp);
System.out.println(dp[n][n]);
scanner.close();
}
public static void print(int[][] dp) {
for (int i = 1; i < dp.length; i++) {
for (int j = 1; j < dp[0].length; j++) {
System.out.print(dp[i][j] + " ");
}
System.out.println();
}
}
}
| Java | ["6\n123434", "8\n20152016"] | 2.5 seconds | ["8", "4"] | NoteIn the first sample there are 8 ways to split the sequence: "123434" = "123434" (maybe the given sequence is just one big number) "123434" = "1" + "23434" "123434" = "12" + "3434" "123434" = "123" + "434" "123434" = "1" + "23" + "434" "123434" = "1" + "2" + "3434" "123434" = "1" + "2" + "3" + "434" "123434" = "1" + "2" + "3" + "4" + "34" Note that we don't count a split "123434" = "12" + "34" + "34" because numbers have to be strictly increasing.In the second sample there are 4 ways: "20152016" = "20152016" "20152016" = "20" + "152016" "20152016" = "201" + "52016" "20152016" = "2015" + "2016" | Java 7 | standard input | [
"dp",
"hashing",
"strings"
] | 1fe6daf718b88cabb2e956e81add3719 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of digits. The second line contains a string of digits and has length equal to n. It's guaranteed that the first digit is not '0'. | 2,000 | Print the number of ways to correctly split the given sequence modulo 109 + 7. | standard output | |
PASSED | 37e1d92b34972a8b7f9d71dde81dc550 | train_004.jsonl | 1451487900 | Limak is a little polar bear. In the snow he found a scroll with the ancient prophecy. Limak doesn't know any ancient languages and thus is unable to understand the prophecy. But he knows digits!One fragment of the prophecy is a sequence of n digits. The first digit isn't zero. Limak thinks that it's a list of some special years. It's hard to see any commas or spaces, so maybe ancient people didn't use them. Now Limak wonders what years are listed there.Limak assumes three things: Years are listed in the strictly increasing order; Every year is a positive integer number; There are no leading zeros. Limak is going to consider all possible ways to split a sequence into numbers (years), satisfying the conditions above. He will do it without any help. However, he asked you to tell him the number of ways to do so. Since this number may be very large, you are only asked to calculate it modulo 109 + 7. | 512 megabytes | import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.MathContext;
import javax.swing.plaf.synth.SynthSeparatorUI;
import org.xml.sax.HandlerBase;
import java.util.*;
public class Main {
static long [] len;
static double[] count;
static int n,m;
static ArrayList<Integer>[] next;
static int mod=(int)1e9+7;
static HashMap<Integer, Integer> map = new HashMap<>();
public static void main(String[] args) {
FasterScanner s = new FasterScanner();
PrintWriter out=new PrintWriter(System.out);
int n=s.nextInt();
char[] in = s.nextLine().toCharArray();
int [] a = new int[n];
for(int i=0;i<n;i++)
a[i]=in[i]-'0';
int eqdp [][] = new int[n+1][n+1];
for(int i=n-1;i>=0;i--){
for(int j=n-1;j>=0;j--){
if(a[i]==a[j])
eqdp[i][j]=1+eqdp[i+1][j+1];
}
}
long dp[][] = new long[n+1][n+1];
for(int i=0;i<=n;i++)
dp[n][i]=1;
for(int i=n-1;i>=0;i--){
for(int j=i-1;j>=0;j--){
dp[i][j]=dp[i+1][j];
if(a[i]==0){
continue;
}
int len=i-j;
if(eqdp[i][j]>=len){
if(i+len+1<=n)
dp[i][j]+=dp[i+len+1][i];
}
else if(i+eqdp[i][j]<n){
if(a[i+eqdp[i][j]] < a[j+eqdp[i][j]]){
if(i+len+1<=n)
dp[i][j]+=dp[i+len+1][i];
}
else{
if(i+len<=n)
dp[i][j]+=dp[i+len][i];
}
}
if(dp[i][j]>mod)
dp[i][j]-=mod;
}
}
// for(int i=0;i<n;i++)
// System.out.println(Arrays.toString(dp[i]));
System.out.println(dp[1][0]);
out.close();
}
static class Pair<A extends Comparable<A> , B extends Comparable<B>>implements Comparable<Pair>{
A a;
B b;
public Pair(A a ,B b){ this.a =a; this.b = b; }
public int compareTo(Pair o) {
int res = a.compareTo((A) (o.a));
if(res == 0)
res = b.compareTo((B)(o.b));
return res;
}
}
static class Node
{
int id=0;
char ch;
boolean done=false;
Node l,r;
int parent=0;
Node(char ch){ this.ch=ch;}
}
static int gcd (long m, long n){
long x;
long y;
while(m%n != 0){
x = n;
y = m%n;
m = x;
n = y;
}
return (int) n;
}
public static class st {
int n;
long[] val;
int[] index;
void build(long [] t) { // build the tree
this.n=t.length;
val = new long[2*n];
index = new int[2*n];
for(int i=0;i<n;i++){
val[n+i] = t[i];
index[n+i] = i;
}
for(int i=n-1;i>=0;i--){
if(val[2*i]>val[2*i+1]){
val[i] = val[2*i];
index[i]= index[2*i];
}
else{
val[i] = val[2*i+1];
index[i]= index[2*i+1];
}
}
}
int query(int l, int r) { // sum on interval [l, r)
int res=0;
long max=0;
for (l += n, r += n; l < r; l >>= 1, r >>= 1) {
if ((l&1)!=0) {
if(val[l]>max){
max=val[l];
res = index[l];
}
l++;
}
if ((r&1)!=0){
--r;
if(val[r]>max){
max=val[r];
res = index[r];
}
}
}
return res;
}
}
public static class FasterScanner {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = System.in.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
} | Java | ["6\n123434", "8\n20152016"] | 2.5 seconds | ["8", "4"] | NoteIn the first sample there are 8 ways to split the sequence: "123434" = "123434" (maybe the given sequence is just one big number) "123434" = "1" + "23434" "123434" = "12" + "3434" "123434" = "123" + "434" "123434" = "1" + "23" + "434" "123434" = "1" + "2" + "3434" "123434" = "1" + "2" + "3" + "434" "123434" = "1" + "2" + "3" + "4" + "34" Note that we don't count a split "123434" = "12" + "34" + "34" because numbers have to be strictly increasing.In the second sample there are 4 ways: "20152016" = "20152016" "20152016" = "20" + "152016" "20152016" = "201" + "52016" "20152016" = "2015" + "2016" | Java 7 | standard input | [
"dp",
"hashing",
"strings"
] | 1fe6daf718b88cabb2e956e81add3719 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of digits. The second line contains a string of digits and has length equal to n. It's guaranteed that the first digit is not '0'. | 2,000 | Print the number of ways to correctly split the given sequence modulo 109 + 7. | standard output | |
PASSED | 25c7942005121227b196fbf17c83c625 | train_004.jsonl | 1451487900 | Limak is a little polar bear. In the snow he found a scroll with the ancient prophecy. Limak doesn't know any ancient languages and thus is unable to understand the prophecy. But he knows digits!One fragment of the prophecy is a sequence of n digits. The first digit isn't zero. Limak thinks that it's a list of some special years. It's hard to see any commas or spaces, so maybe ancient people didn't use them. Now Limak wonders what years are listed there.Limak assumes three things: Years are listed in the strictly increasing order; Every year is a positive integer number; There are no leading zeros. Limak is going to consider all possible ways to split a sequence into numbers (years), satisfying the conditions above. He will do it without any help. However, he asked you to tell him the number of ways to do so. Since this number may be very large, you are only asked to calculate it modulo 109 + 7. | 512 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.TreeSet;
public class D {
int MOD = (int)(1e9+7);
int n;
String s;
int[] d;
int[] eq;
public void setInput(){
n = 5000;
d = new int[n];
StringBuilder sb = new StringBuilder();
for(int i=0; i<n; i++){
d[i] = 9;
sb.append("9");
}
s = sb.toString();
}
public void readInput() throws IOException{
Scanner sc = new Scanner(System.in);
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
n = sc.nextInt();
sc.nextLine();
s = sc.nextLine();
d = new int[n];
for(int i=0; i<n; i++){
d[i] = s.charAt(i)-'0';
}
}
public int comp(int a1, int len1, int a2, int len2){
if (len1>len2)
return 1;
if (len2>len1)
return -1;
for(int i=0; i<len1; i++){
if (d[a1+i]>d[a2+i])
return 1;
if (d[a1+i]<d[a2+i])
return -1;
}
return 0;
}
public int islarger(int a, int len){
int x1 = a;
int x2 = a+len;
while(x1<a+len && x2<a+2*len && x2 < n){
if (d[x1]>d[x2])
return 1;
if (d[x1]<d[x2])
return -1;
int dx = 1;//Math.min(eq[x1], eq[x2]);
x1 += dx;
x2 += dx;
}
// if (a>=0)
// return 0;
// if (a+2*len>n)
// return 1;
// for(int i=0; i<len; i++){
// if (d[a+i]>d[a+len+i])
// return 1;
// if (d[a+i]<d[a+len+i])
// return -1;
// }
return 0;
}
public void solve(){
int dp[][] = new int[n+2][n+2];
int neq[][] = new int[n+2][n+2];
for(int l=1; l<=n-1; l++){
for(int i=n-l-1; i>=0; i--){
if (d[i]==d[i+l])
neq[i][l] = neq[i+1][l]+1;
else
neq[i][l] = 0;
}
}
for(int i=n-1; i>=0; i--){
for(int len = n-i; len>0; len--){
// if (i==0){
// i=i+1-1;
// }
if(i+len==n){
dp[i][len] = 1;
continue;
}
else{
dp[i][len] = dp[i][len+1];
if(d[i+len]==0)
continue;
int nr = neq[i][len];
// if (islarger(i,len)>=0)
if (nr>=len || i+len+nr>=n || d[i+nr]>d[i+len+nr])
dp[i][len] += dp[i+len][len+1];
else// if (i + 2*len <= n)
dp[i][len] += dp[i+len][len];
if (dp[i][len] > MOD)
dp[i][len] -= MOD;
}
}
}
System.out.println(dp[0][1]);
}
public static void main(String[] args) throws IOException {
D a = new D();
a.readInput();
//a.setInput();
double ss = System.currentTimeMillis();
a.solve();
double ee = System.currentTimeMillis();
//System.out.println(ee-ss);
}
}
| Java | ["6\n123434", "8\n20152016"] | 2.5 seconds | ["8", "4"] | NoteIn the first sample there are 8 ways to split the sequence: "123434" = "123434" (maybe the given sequence is just one big number) "123434" = "1" + "23434" "123434" = "12" + "3434" "123434" = "123" + "434" "123434" = "1" + "23" + "434" "123434" = "1" + "2" + "3434" "123434" = "1" + "2" + "3" + "434" "123434" = "1" + "2" + "3" + "4" + "34" Note that we don't count a split "123434" = "12" + "34" + "34" because numbers have to be strictly increasing.In the second sample there are 4 ways: "20152016" = "20152016" "20152016" = "20" + "152016" "20152016" = "201" + "52016" "20152016" = "2015" + "2016" | Java 7 | standard input | [
"dp",
"hashing",
"strings"
] | 1fe6daf718b88cabb2e956e81add3719 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of digits. The second line contains a string of digits and has length equal to n. It's guaranteed that the first digit is not '0'. | 2,000 | Print the number of ways to correctly split the given sequence modulo 109 + 7. | standard output | |
PASSED | bc034e04955efe9779aa8baec56e6c32 | train_004.jsonl | 1451487900 | Limak is a little polar bear. In the snow he found a scroll with the ancient prophecy. Limak doesn't know any ancient languages and thus is unable to understand the prophecy. But he knows digits!One fragment of the prophecy is a sequence of n digits. The first digit isn't zero. Limak thinks that it's a list of some special years. It's hard to see any commas or spaces, so maybe ancient people didn't use them. Now Limak wonders what years are listed there.Limak assumes three things: Years are listed in the strictly increasing order; Every year is a positive integer number; There are no leading zeros. Limak is going to consider all possible ways to split a sequence into numbers (years), satisfying the conditions above. He will do it without any help. However, he asked you to tell him the number of ways to do so. Since this number may be very large, you are only asked to calculate it modulo 109 + 7. | 512 megabytes |
import java.util.Arrays;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.TreeSet;
import java.io.IOException;
import java.io.PrintWriter;
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.InputMismatchException;
import java.util.LinkedList;
import java.util.Map;
import java.util.PriorityQueue;
public class G_B_2015_4 {
static int mod=1000000007;
public static void main(String args[]){
Scanner s=new Scanner(System.in);
PrintWriter out=new PrintWriter(System.out);
int n=s.nextInt();
s.nextLine();
String inp=s.nextLine();
long[][] dp=new long[n][n+1];
int[][] a=new int[n][n+1];
int[][] b=new int[n][n+1];
for(int i=0;i<a.length;i++)
Arrays.fill(b[i],-2);
for(int ii=1;ii<=n;ii++){
if(n-2*ii>=0){
int t=n-2*ii;
int t1=n-ii;
int idx=-1;
for(int i=0;i<ii;i++){
if(inp.charAt(t+i)!=inp.charAt(t1+i)){
idx=i;
if(inp.charAt(t+i)>inp.charAt(t1+i)){
b[t][ii]=1;
}
else{
b[t][ii]=-1;
}
break;
}
}
a[t][ii]=idx;
if(idx==-1)
b[t][ii]=0;
}
for(int i=n-2*ii-1;i>=0;i--){
if(inp.charAt(i)==inp.charAt(i+ii)){
if(a[i+1][ii]==-1 || a[i+1][ii]==ii-1)
a[i][ii]=-1;
else
a[i][ii]=a[i+1][ii]+1;
}
else{
a[i][ii]=0;
}
if(a[i][ii]==-1)
b[i][ii]=0;
else if(inp.charAt(i+a[i][ii])>inp.charAt(i+ii+a[i][ii]))
b[i][ii]=1;
else
b[i][ii]=-1;
}
}
for(int i=0;i<n;i++){
if(inp.charAt(i)!='0')
dp[i][n-i]=1;
}
for(int ii=n-1;ii>0;ii--){
for(int i=n-ii-1;i>=0;i--){
if(inp.charAt(i)=='0' || b[i][ii]==-2)
dp[i][ii]=0;
else if(b[i][ii]==-1){
dp[i][ii]=dp[i+ii][ii];
}
else{
dp[i][ii]=dp[i+ii][ii+1];
}
dp[i][ii]+=dp[i][ii+1];
dp[i][ii]%=mod;
}
}
System.out.println(dp[0][1]);
out.close();
}
public static class FasterScanner {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = System.in.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
public static class disjointSet {
private int[] parent; // parent[i] = parent of i
private byte[] rank; // rank[i] = rank of subtree rooted at i (never more than 31)
private int count; // number of components
public disjointSet(int N) {
if (N < 0) throw new IllegalArgumentException();
count = N;
parent = new int[N];
rank = new byte[N];
for (int i = 0; i < N; i++) {
parent[i] = i;
rank[i] = 0;
}
}
public int find(int p) {
if (p < 0 || p >= parent.length) throw new IndexOutOfBoundsException();
while (p != parent[p]) {
parent[p] = parent[parent[p]]; // path compression by halving
p = parent[p];
}
return p;
}
public int count() {
return count;
}
public boolean connected(int p, int q) {
return find(p) == find(q);
}
public boolean union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ) return false;
// make root of smaller rank point to root of larger rank
if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;
else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;
else {
parent[rootQ] = rootP;
rank[rootP]++;
}
count--;
return true;
}
}
}
| Java | ["6\n123434", "8\n20152016"] | 2.5 seconds | ["8", "4"] | NoteIn the first sample there are 8 ways to split the sequence: "123434" = "123434" (maybe the given sequence is just one big number) "123434" = "1" + "23434" "123434" = "12" + "3434" "123434" = "123" + "434" "123434" = "1" + "23" + "434" "123434" = "1" + "2" + "3434" "123434" = "1" + "2" + "3" + "434" "123434" = "1" + "2" + "3" + "4" + "34" Note that we don't count a split "123434" = "12" + "34" + "34" because numbers have to be strictly increasing.In the second sample there are 4 ways: "20152016" = "20152016" "20152016" = "20" + "152016" "20152016" = "201" + "52016" "20152016" = "2015" + "2016" | Java 7 | standard input | [
"dp",
"hashing",
"strings"
] | 1fe6daf718b88cabb2e956e81add3719 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of digits. The second line contains a string of digits and has length equal to n. It's guaranteed that the first digit is not '0'. | 2,000 | Print the number of ways to correctly split the given sequence modulo 109 + 7. | standard output | |
PASSED | 0463437a0900042f8ab21c5c8d472560 | train_004.jsonl | 1451487900 | Limak is a little polar bear. In the snow he found a scroll with the ancient prophecy. Limak doesn't know any ancient languages and thus is unable to understand the prophecy. But he knows digits!One fragment of the prophecy is a sequence of n digits. The first digit isn't zero. Limak thinks that it's a list of some special years. It's hard to see any commas or spaces, so maybe ancient people didn't use them. Now Limak wonders what years are listed there.Limak assumes three things: Years are listed in the strictly increasing order; Every year is a positive integer number; There are no leading zeros. Limak is going to consider all possible ways to split a sequence into numbers (years), satisfying the conditions above. He will do it without any help. However, he asked you to tell him the number of ways to do so. Since this number may be very large, you are only asked to calculate it modulo 109 + 7. | 512 megabytes | import java.io.*;
import java.util.*;
public class D611 {
static long mod = (long)1e9+7;
public static void main(String[] args) throws IOException {
input.init(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = input.nextInt();
char[] s = input.next().toCharArray();
int[][] dp = new int[n][n];
int[][] csum = new int[n][n];
for(int i = 0; i<n; i++) dp[i][0] = csum[i][0] = 1;
int[][] maxSame = new int[n][n];
for(int j = n-1; j>=0; j--)
for(int i = 0; i<j; i++)
{
maxSame[i][j] = s[i] == s[j] ? (1 + (j == n-1 ? 0 : maxSame[i+1][j+1])) : 0;
}
for(int i = 1; i<n; i++)
{
for(int j = 1; j<=i; j++)
{
if(s[j] == '0')
{
csum[i][j] = csum[i][j-1];
continue;
}
int len = i - j + 1;
dp[i][j] = csum[j-1][j-1] - (j-len >= 0 ? csum[j-1][j-len] : 0);
if(dp[i][j] < 0) dp[i][j] += mod;
if(j-len >= 0)
{
int k = maxSame[j-len][j];
boolean less = k<len && j+k < n && s[j-len+k] < s[j+k];
if(less)
{
dp[i][j] = (dp[i][j] + dp[j-1][j-len]);
if(dp[i][j] >= mod) dp[i][j] -= mod;
}
}
csum[i][j] = (csum[i][j-1] + dp[i][j]);
if(csum[i][j] >= mod) csum[i][j] -= mod;
}
}
long res = 0;
for(int i = 0; i<n; i++) res += dp[n-1][i];
out.println(res%mod);
out.close();
}
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 | ["6\n123434", "8\n20152016"] | 2.5 seconds | ["8", "4"] | NoteIn the first sample there are 8 ways to split the sequence: "123434" = "123434" (maybe the given sequence is just one big number) "123434" = "1" + "23434" "123434" = "12" + "3434" "123434" = "123" + "434" "123434" = "1" + "23" + "434" "123434" = "1" + "2" + "3434" "123434" = "1" + "2" + "3" + "434" "123434" = "1" + "2" + "3" + "4" + "34" Note that we don't count a split "123434" = "12" + "34" + "34" because numbers have to be strictly increasing.In the second sample there are 4 ways: "20152016" = "20152016" "20152016" = "20" + "152016" "20152016" = "201" + "52016" "20152016" = "2015" + "2016" | Java 7 | standard input | [
"dp",
"hashing",
"strings"
] | 1fe6daf718b88cabb2e956e81add3719 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of digits. The second line contains a string of digits and has length equal to n. It's guaranteed that the first digit is not '0'. | 2,000 | Print the number of ways to correctly split the given sequence modulo 109 + 7. | standard output | |
PASSED | fab52d5f5e17d97a5d9507a82f67a702 | train_004.jsonl | 1451487900 | Limak is a little polar bear. In the snow he found a scroll with the ancient prophecy. Limak doesn't know any ancient languages and thus is unable to understand the prophecy. But he knows digits!One fragment of the prophecy is a sequence of n digits. The first digit isn't zero. Limak thinks that it's a list of some special years. It's hard to see any commas or spaces, so maybe ancient people didn't use them. Now Limak wonders what years are listed there.Limak assumes three things: Years are listed in the strictly increasing order; Every year is a positive integer number; There are no leading zeros. Limak is going to consider all possible ways to split a sequence into numbers (years), satisfying the conditions above. He will do it without any help. However, he asked you to tell him the number of ways to do so. Since this number may be very large, you are only asked to calculate it modulo 109 + 7. | 512 megabytes | import java.io.*;
import java.util.*;
public class Solution {
private BufferedReader in;
private StringTokenizer line;
private PrintWriter out;
private int n;
private char[] a;
private int[] hashes;
private int mod = 1000000007;
private long[] ppow;
private long hash(int i, int len) {
return ((hashes[i + len - 1] - (i == 0 ? 0 : hashes[i - 1]) + mod) * ppow[n - i]) % mod;
}
private boolean compare(int i1, int i2, int len) {
if (a[i1] != a[i2]) {
return a[i1] < a[i2];
}
if (hash(i1, len) == hash(i2, len)) {
return false;
}
int l = 0, r = len + 1;
while (l + 1 < r) {
int mid = (l + r) / 2;
if (hash(i1, mid) == hash(i2, mid)) {
l = mid;
} else {
r = mid;
}
}
l++;
while (l + 1 <= len && hash(i1, l) == hash(i2, l)) {
l++;
}
return a[i1 + l - 1] < a[i2 + l - 1];
}
public void solve() throws IOException {
n = nextInt();
a = nextToken().toCharArray();
{
hashes = new int[n];
ppow = new long[n + 1];
ppow[0] = 1;
long p = 13;
for (int i = 0; i < n; i++) {
ppow[i + 1] = ((p * ppow[i]) % mod);
hashes[i] = (int) (((i == 0 ? 0 : hashes[i - 1]) + ((a[i] - '0' + 1) * ppow[i + 1])) % mod);
}
}
int[][] b = new int[n][n];
int[][] bn = new int[n][n];
int mm = 1000000007;
for (int i = 0; i < n; i++) {
b[i][0] = 1;
bn[i][0] = 1;
for (int j = 1; j <= i; j++) {
if (a[j] != '0') {
int len = i - j + 1;
b[i][j] = (bn[i - 1][j] + (j - len >= 0 && compare(j - len, j, len) ? b[i - len][j - len] : 0)) % mm;
bn[i][j] = (bn[i - 1][j] + (j - len >= 0 ? b[i - len][j - len] : 0)) % mm;
}
}
}
int res = 0;
for (int i = 0; i < n; i++) {
res = (res + b[n - 1][i]) % mm;
}
out.println(res);
}
public static void main(String[] args) throws IOException {
new Solution().run(args);
}
public void run(String[] args) throws IOException {
if (args.length > 0 && "DEBUG_MODE".equals(args[0])) {
in = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
} else {
in = new BufferedReader(new InputStreamReader(System.in));
}
out = new PrintWriter(System.out);
// int t = nextInt();
int t = 1;
for (int i = 0; i < t; i++) {
solve();
}
in.close();
out.flush();
out.close();
}
private int[] nextIntArray(int n) throws IOException {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = nextInt();
}
return res;
}
private long[] nextLongArray(int n) throws IOException {
long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = nextInt();
}
return res;
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private String nextToken() throws IOException {
while (line == null || !line.hasMoreTokens()) {
line = new StringTokenizer(in.readLine());
}
return line.nextToken();
}
private static class Pii {
private int key;
private int value;
public Pii(int key, int value) {
this.key = key;
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pii pii = (Pii) o;
if (key != pii.key) return false;
return value == pii.value;
}
@Override
public int hashCode() {
int result = key;
result = 31 * result + value;
return result;
}
}
private static class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
if (key != null ? !key.equals(pair.key) : pair.key != null) return false;
return !(value != null ? !value.equals(pair.value) : pair.value != null);
}
@Override
public int hashCode() {
int result = key != null ? key.hashCode() : 0;
result = 31 * result + (value != null ? value.hashCode() : 0);
return result;
}
}
}
| Java | ["6\n123434", "8\n20152016"] | 2.5 seconds | ["8", "4"] | NoteIn the first sample there are 8 ways to split the sequence: "123434" = "123434" (maybe the given sequence is just one big number) "123434" = "1" + "23434" "123434" = "12" + "3434" "123434" = "123" + "434" "123434" = "1" + "23" + "434" "123434" = "1" + "2" + "3434" "123434" = "1" + "2" + "3" + "434" "123434" = "1" + "2" + "3" + "4" + "34" Note that we don't count a split "123434" = "12" + "34" + "34" because numbers have to be strictly increasing.In the second sample there are 4 ways: "20152016" = "20152016" "20152016" = "20" + "152016" "20152016" = "201" + "52016" "20152016" = "2015" + "2016" | Java 7 | standard input | [
"dp",
"hashing",
"strings"
] | 1fe6daf718b88cabb2e956e81add3719 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of digits. The second line contains a string of digits and has length equal to n. It's guaranteed that the first digit is not '0'. | 2,000 | Print the number of ways to correctly split the given sequence modulo 109 + 7. | standard output | |
PASSED | 7cb50002c6309c3ee7e6d9a50fa26168 | train_004.jsonl | 1451487900 | Limak is a little polar bear. In the snow he found a scroll with the ancient prophecy. Limak doesn't know any ancient languages and thus is unable to understand the prophecy. But he knows digits!One fragment of the prophecy is a sequence of n digits. The first digit isn't zero. Limak thinks that it's a list of some special years. It's hard to see any commas or spaces, so maybe ancient people didn't use them. Now Limak wonders what years are listed there.Limak assumes three things: Years are listed in the strictly increasing order; Every year is a positive integer number; There are no leading zeros. Limak is going to consider all possible ways to split a sequence into numbers (years), satisfying the conditions above. He will do it without any help. However, he asked you to tell him the number of ways to do so. Since this number may be very large, you are only asked to calculate it modulo 109 + 7. | 512 megabytes | import java.io.InputStreamReader;
import java.io.IOException;
import java.util.InputMismatchException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
QuickScanner in = new QuickScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
final int MOD=1000000007;
int n;
String str;
int dp[][];
int lcp[][];
int sum[][];
public void solve(int testNumber, QuickScanner in, PrintWriter out) {
n=in.nextInt();
str=in.next();
dp=new int[n][n];
for(int i=0;i<n;i++)
dp[i][n-1]=1;
lcp=new int[n+1][n+1];
sum=new int[n][n+1];
for(int i=n-1;i>=0;i--)
for(int j=n-1;j>=0;j--)
{
if(str.charAt(i) != str.charAt(j))
lcp[i][j]=0;
else
lcp[i][j]=1+lcp[i+1][j+1];
}
for(int l=n-2;l>=0;l--)
{
for(int r = l; r + 1 < n; r++)
{
if(str.charAt(r + 1) == '0')
continue;
int len = r - l + 1;
if(r + len >= n)
continue;
//preserve length
if(fast_compare(l, r, r + 1, r + len) < 0)
dp[l][r] = (dp[l][r] + dp[r + 1][r + len]) % MOD;
/*for(int nLen = len + 1; r + nLen < n; nLen++)
{
dp[l][r] = (dp[l][r] + dp[r + 1][r + nLen]) % MOD;
}*/
/*for(int nLen = r+ len + 1; nLen < n; nLen++)
{
dp[l][r] = (dp[l][r] + dp[r + 1][nLen]) % MOD;
}*/
int s=((sum[r+1][n]-sum[r+1][r+len+1])%MOD+MOD)%MOD;
dp[l][r]=(dp[l][r]+s)%MOD;
}
for(int r = 0 ; r<n;r++)
sum[l][r+1]=(sum[l][r]+dp[l][r])%MOD;
}
int res=0;
for(int i=0;i<n;i++)
res=(res+dp[0][i])%MOD;
out.println(res);
}
private int fast_compare(int l1, int r1, int l2, int r2)
{
if(r1-l1!=r2-l2)
throw new RuntimeException();
int len=r1-l1+1;
int eqLen=lcp[l1][l2];
if(eqLen>=len)
return 0;
else
return Character.compare(str.charAt(l1+eqLen), str.charAt(l2+eqLen));
}
}
class QuickScanner {
BufferedReader in;
StringTokenizer token;
String delim;
public QuickScanner(InputStream inputStream)
{
this.in=new BufferedReader(new InputStreamReader(inputStream));
this.delim=" \n\t";
this.token=new StringTokenizer("",delim);
}
public boolean hasNext()
{
while(!token.hasMoreTokens())
{
try {
String s=in.readLine();
if(s==null) return false;
token=new StringTokenizer(s,delim);
} catch (IOException e) {
throw new InputMismatchException();
}
}
return true;
}
public String next()
{
hasNext();
return token.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
}
| Java | ["6\n123434", "8\n20152016"] | 2.5 seconds | ["8", "4"] | NoteIn the first sample there are 8 ways to split the sequence: "123434" = "123434" (maybe the given sequence is just one big number) "123434" = "1" + "23434" "123434" = "12" + "3434" "123434" = "123" + "434" "123434" = "1" + "23" + "434" "123434" = "1" + "2" + "3434" "123434" = "1" + "2" + "3" + "434" "123434" = "1" + "2" + "3" + "4" + "34" Note that we don't count a split "123434" = "12" + "34" + "34" because numbers have to be strictly increasing.In the second sample there are 4 ways: "20152016" = "20152016" "20152016" = "20" + "152016" "20152016" = "201" + "52016" "20152016" = "2015" + "2016" | Java 7 | standard input | [
"dp",
"hashing",
"strings"
] | 1fe6daf718b88cabb2e956e81add3719 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of digits. The second line contains a string of digits and has length equal to n. It's guaranteed that the first digit is not '0'. | 2,000 | Print the number of ways to correctly split the given sequence modulo 109 + 7. | standard output | |
PASSED | 8de7e00509b87def75af470d4bfdcff2 | train_004.jsonl | 1451487900 | Limak is a little polar bear. In the snow he found a scroll with the ancient prophecy. Limak doesn't know any ancient languages and thus is unable to understand the prophecy. But he knows digits!One fragment of the prophecy is a sequence of n digits. The first digit isn't zero. Limak thinks that it's a list of some special years. It's hard to see any commas or spaces, so maybe ancient people didn't use them. Now Limak wonders what years are listed there.Limak assumes three things: Years are listed in the strictly increasing order; Every year is a positive integer number; There are no leading zeros. Limak is going to consider all possible ways to split a sequence into numbers (years), satisfying the conditions above. He will do it without any help. However, he asked you to tell him the number of ways to do so. Since this number may be very large, you are only asked to calculate it modulo 109 + 7. | 512 megabytes | import java.io.*;
import java.util.*;
public class GB2015D
{
public static StringTokenizer st;
public static void nextLine(BufferedReader br) throws IOException
{
st = new StringTokenizer(br.readLine());
}
public static String next()
{
return st.nextToken();
}
public static int nextInt()
{
return Integer.parseInt(st.nextToken());
}
public static long nextLong()
{
return Long.parseLong(st.nextToken());
}
public static double nextDouble()
{
return Double.parseDouble(st.nextToken());
}
static long[][] dp;
static byte[][] G;
static long[][] csum;
static long MOD = 1000000007;
static int[] narr;
static String number;
static int n;
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
nextLine(br);
n = nextInt();
nextLine(br);
number = next();
narr = new int[n];
// dp[i][j] is the number of ways to start from i+j given the last number
// is j digits starting from i
dp = new long[n+1][];
// G[i][j] is 1 if the number at G[j]-G[j+i] is smaller than G[j+i]-G[j+2i]
G = new byte[n][n];
csum = new long[n+1][];
for (int i = 0; i < n; i++)
{
narr[i] = number.charAt(i) - '0';
}
for (int i = 0; i <= n; i++)
{
dp[i] = new long[n-i+1];
}
for (int i = 1; i <= n/2; i++)
{
int start = 0;
for (int j = 0; j + i < n; j++)
{
if (j - i >= start)
{
start = j-i+1;
}
if (narr[j+i] > narr[j])
{
for (int k = start; k <= j; k++)
{
G[i][k] = 1;
}
start = j+1;
}
else if (narr[j+i] < narr[j])
{
start = j+1;
}
}
}
for (int i = 0; i < n+1; i++)
{
Arrays.fill(dp[i], -1);
}
long sum = 0;
for (int i = 0; i < n; i++)
{
csum[i] = new long[n-i+1];
}
for (int i = 0; i < n; i++)
{
dp[i][n-i] = 1;
csum[i][n-i] = 1;
}
for (int i = n-1; i >= 0; i--)
{
for (int j = i; j >= 1; j--)
{
// call requires the sum of all dp[i] to have been done.
solve(i-j, j);
// dp[i-j][j] is now done, update csum
csum[i-j][j] = moda(csum[i-j][j+1], dp[i-j][j]);
}
}
/*
for (int i = 0; i <= n; i++)
{
System.out.println(Arrays.toString(dp[i]));
}
for (int i = n-1; i >= 0; i--)
{
System.out.println("CSUM " + i + ": " + Arrays.toString(csum[i]));
}
*/
System.out.println(csum[0][1]);
}
private static boolean greater(int pos1, int pos2, int len)
{
for (int i = 0; i < len; i++)
{
if (narr[pos1+i] < narr[pos2+i])
{
return true;
}
else if (narr[pos1+i] > narr[pos2+i])
{
return false;
}
}
return false;
}
private static long solve(int pos, int prev)
{
if (pos+prev > n)
{
return 0;
}
if (dp[pos][prev] != -1)
{
return dp[pos][prev];
}
if (pos+prev+prev > n)
{
dp[pos][prev] = 0;
return 0;
}
if (pos+prev == n)
{
dp[pos][prev] = 1;
return 1;
}
if (narr[pos+prev] == 0)
{
dp[pos][prev] = 0;
return 0;
}
int min = prev+1;
if (G[prev][pos] == 1)
{
min = prev;
}
// sum of dp[pos+prev] from min to n-(pos+prev)
//System.out.print("Using csum " + (pos+prev) + "," + min);
if (min < csum[pos+prev].length)
{
//System.out.println(" success");
dp[pos][prev] = csum[pos+prev][min];
}
else
{
//System.out.println(" failed");
dp[pos][prev] = 0;
}
return dp[pos][prev];
}
static long moda(long a, long b)
{
return (a + b) % MOD;
}
static long modm(long a, long b)
{
return ((a % MOD) * (b % MOD)) % MOD;
}
}
| Java | ["6\n123434", "8\n20152016"] | 2.5 seconds | ["8", "4"] | NoteIn the first sample there are 8 ways to split the sequence: "123434" = "123434" (maybe the given sequence is just one big number) "123434" = "1" + "23434" "123434" = "12" + "3434" "123434" = "123" + "434" "123434" = "1" + "23" + "434" "123434" = "1" + "2" + "3434" "123434" = "1" + "2" + "3" + "434" "123434" = "1" + "2" + "3" + "4" + "34" Note that we don't count a split "123434" = "12" + "34" + "34" because numbers have to be strictly increasing.In the second sample there are 4 ways: "20152016" = "20152016" "20152016" = "20" + "152016" "20152016" = "201" + "52016" "20152016" = "2015" + "2016" | Java 7 | standard input | [
"dp",
"hashing",
"strings"
] | 1fe6daf718b88cabb2e956e81add3719 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of digits. The second line contains a string of digits and has length equal to n. It's guaranteed that the first digit is not '0'. | 2,000 | Print the number of ways to correctly split the given sequence modulo 109 + 7. | standard output | |
PASSED | bca9cffcf6590f2ee52d1bbeaff87088 | train_004.jsonl | 1451487900 | Limak is a little polar bear. In the snow he found a scroll with the ancient prophecy. Limak doesn't know any ancient languages and thus is unable to understand the prophecy. But he knows digits!One fragment of the prophecy is a sequence of n digits. The first digit isn't zero. Limak thinks that it's a list of some special years. It's hard to see any commas or spaces, so maybe ancient people didn't use them. Now Limak wonders what years are listed there.Limak assumes three things: Years are listed in the strictly increasing order; Every year is a positive integer number; There are no leading zeros. Limak is going to consider all possible ways to split a sequence into numbers (years), satisfying the conditions above. He will do it without any help. However, he asked you to tell him the number of ways to do so. Since this number may be very large, you are only asked to calculate it modulo 109 + 7. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author George Marcus
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
private static final int MOD = 1000000007;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int N = in.readInt();
char[] A = in.readString().toCharArray();
// N = 5000;
// A = new char[N];
// A[0] = '1';
// for (int i = 1; i < N; i++) {
// if (A[i - 1] == '9') {
// A[i] = '0';
// } else {
// A[i] = (char) (A[i - 1] + 1);
// }
// }
int[][] dp = new int[N + 1][N + 1];
for (int j = 1; j <= N; j++) {
dp[0][j] = 1;
}
int[][] E = new int[N][N];
for (int i = N - 1; i >= 0; i--) {
for (int j = N - 1; j > i; j--) {
if (A[i] == A[j]) {
E[i][j] = 1;
if (j + 1 < N) {
E[i][j] += E[i + 1][j + 1];
}
}
}
}
for (int i = 1; i < N; i++) {
for (int j = 1; j <= i; j++) {
int k = i - j;
if (A[k + 1] != '0') {
// sum dp[k][jj], jj < j
dp[i][j] = dp[k][j - 1];
if (k + 1 >= j) {
int kk = k - j + 1;
int len = E[kk][k + 1];
if (kk + len < k + 1) {
int p1 = kk + len;
int p2 = k + 1 + len;
if (A[p1] < A[p2]) {
dp[i][j] += dp[k][j];
if (dp[i][j] >= MOD) {
dp[i][j] -= MOD;
}
dp[i][j] -= dp[k][j - 1];
if (dp[i][j] < 0) {
dp[i][j] += MOD;
}
}
}
}
}
// sums
dp[i][j] += dp[i][j - 1];
if (dp[i][j] >= MOD) {
dp[i][j] -= MOD;
}
}
dp[i][i + 1] = 1;
for (int j = i + 1; j <= N; j++) {
// sums
dp[i][j] += dp[i][j - 1];
if (dp[i][j] >= MOD) {
dp[i][j] -= MOD;
}
}
}
out.println(dp[N - 1][N]);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
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 | ["6\n123434", "8\n20152016"] | 2.5 seconds | ["8", "4"] | NoteIn the first sample there are 8 ways to split the sequence: "123434" = "123434" (maybe the given sequence is just one big number) "123434" = "1" + "23434" "123434" = "12" + "3434" "123434" = "123" + "434" "123434" = "1" + "23" + "434" "123434" = "1" + "2" + "3434" "123434" = "1" + "2" + "3" + "434" "123434" = "1" + "2" + "3" + "4" + "34" Note that we don't count a split "123434" = "12" + "34" + "34" because numbers have to be strictly increasing.In the second sample there are 4 ways: "20152016" = "20152016" "20152016" = "20" + "152016" "20152016" = "201" + "52016" "20152016" = "2015" + "2016" | Java 7 | standard input | [
"dp",
"hashing",
"strings"
] | 1fe6daf718b88cabb2e956e81add3719 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of digits. The second line contains a string of digits and has length equal to n. It's guaranteed that the first digit is not '0'. | 2,000 | Print the number of ways to correctly split the given sequence modulo 109 + 7. | standard output | |
PASSED | dcf5a3970f4fe29cda7e8a89b291a158 | train_004.jsonl | 1451487900 | Limak is a little polar bear. In the snow he found a scroll with the ancient prophecy. Limak doesn't know any ancient languages and thus is unable to understand the prophecy. But he knows digits!One fragment of the prophecy is a sequence of n digits. The first digit isn't zero. Limak thinks that it's a list of some special years. It's hard to see any commas or spaces, so maybe ancient people didn't use them. Now Limak wonders what years are listed there.Limak assumes three things: Years are listed in the strictly increasing order; Every year is a positive integer number; There are no leading zeros. Limak is going to consider all possible ways to split a sequence into numbers (years), satisfying the conditions above. He will do it without any help. However, he asked you to tell him the number of ways to do so. Since this number may be very large, you are only asked to calculate it modulo 109 + 7. | 512 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class D {
static int MAX_N = 5005;
static long MOD = 1000000007l;
static String s;
// indDif[a][b] gives us the index where s.substring(a) and s.substring(b) differ
// it is used as a helper matrix for determining which string is lexicographically smaller in O(1)
static int [][] indDiff = new int[MAX_N][MAX_N];
// T[a][b] gives us the number of ways (modulo MOD) that we can solve the subproblem s[1...b]
// such that we append at the end s[a..b] as the last year
// the final solution will be sum(T[i][N-1] for i=0..N-1)
static long [][] T = new long[MAX_N][MAX_N];
// SUM_T[a][b] = sum(T[i][b] for i=a...b) % MOD
// we need this table so we can execute calculateMainLookUpTable more efficiently
// check the method for more info
static long [][] SUM_T = new long[MAX_N][MAX_N];
// O(N^2)
static void preprocessStringDiff(int N) {
// indDiff[a][b] will mean that s.substring(a), s.substring(b) don't differ in any index, which is trivially true when a == b
for(int i=0; i<N; i++)
indDiff[i][i] = -1;
// we need to be careful of the order such that when we process indDiff[r][c], indDiff[r+1][c+1] has already been taken care of
for(int c = N-1; c>=0; c--) {
for(int r = c - 1; r >=0; r--) {
if(s.charAt(r) == s.charAt(c)) {
if(r + 1 < N && c + 1 < N) {
if(indDiff[r+1][c+1] == -1) {
indDiff[r][c] = -1;
} else {
indDiff[r][c] = 1 + indDiff[r+1][c+1];
}
} else {
indDiff[r][c] = -1;
}
} else {
indDiff[r][c] = 0;
}
}
}
// symmetric
for(int r = 1; r<N; r++) {
for(int c = 0; c<r; c++) {
indDiff[r][c] = indDiff[c][r];
}
}
}
// here we basically solve the task
// O(N^2)
static void calculateMainLookUpTable(int N) {
// we need to take care of the order, because when we process T[a][b], T[i][a-1] needs to be already processed, for every i <= a-1
for(int step = 0; step<N; step++) {
int a = 0;
int b = step;
while(a < N && b < N) {
if(s.charAt(a) == '0') {
T[a][b] = 0;
SUM_T[a][b] = 0;
if(a+1<=b) {
SUM_T[a][b] = SUM_T[a+1][b];
}
a++;
b++;
continue;
}
if(a == 0) {
T[a][b] = 1;
SUM_T[a][b] = 1;
if(a+1<=b) {
SUM_T[a][b] = (T[a][b] + SUM_T[a+1][b]) % MOD;
}
a++;
b++;
continue;
}
int c = Math.max(0,2 * a - b);
// with this line we have taken care of counting the numbers
// s[c][a-1] which have smaller number of digits of s[a][b]
T[a][b] = SUM_T[c][a-1] % MOD;
// now we need to see weather we can add T[c][a-1] where a - 1 - c == b - a (meaning S[c][a-1] and S[a][b] have the same length
c = 2 * a - b - 1;
if(c >= 0) {
int ind = indDiff[c][a];
if(ind != -1) {
if(a + ind <= b && c + ind <= a-1) {
if(s.charAt(c + ind) < s.charAt(a + ind)) {
T[a][b] = (T[a][b] + T[c][a-1]) % MOD;
}
}
}
}
// we need to update SUM_T
if(a+1<=b) {
SUM_T[a][b] = (T[a][b] + SUM_T[a+1][b] ) % MOD;
} else {
SUM_T[a][b] = T[a][b];
}
a++;
b++;
}
}
}
public static void main(String [] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
s = br.readLine();
preprocessStringDiff(N);
calculateMainLookUpTable(N);
long sol = 0;
for(int i=0; i<N; i++) {
sol = (sol + T[i][N-1]) % MOD;
}
System.out.println(sol);
}
} | Java | ["6\n123434", "8\n20152016"] | 2.5 seconds | ["8", "4"] | NoteIn the first sample there are 8 ways to split the sequence: "123434" = "123434" (maybe the given sequence is just one big number) "123434" = "1" + "23434" "123434" = "12" + "3434" "123434" = "123" + "434" "123434" = "1" + "23" + "434" "123434" = "1" + "2" + "3434" "123434" = "1" + "2" + "3" + "434" "123434" = "1" + "2" + "3" + "4" + "34" Note that we don't count a split "123434" = "12" + "34" + "34" because numbers have to be strictly increasing.In the second sample there are 4 ways: "20152016" = "20152016" "20152016" = "20" + "152016" "20152016" = "201" + "52016" "20152016" = "2015" + "2016" | Java 7 | standard input | [
"dp",
"hashing",
"strings"
] | 1fe6daf718b88cabb2e956e81add3719 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of digits. The second line contains a string of digits and has length equal to n. It's guaranteed that the first digit is not '0'. | 2,000 | Print the number of ways to correctly split the given sequence modulo 109 + 7. | standard output | |
PASSED | 20599b6951fe80bc95590a55ae9043e4 | train_004.jsonl | 1451487900 | Limak is a little polar bear. In the snow he found a scroll with the ancient prophecy. Limak doesn't know any ancient languages and thus is unable to understand the prophecy. But he knows digits!One fragment of the prophecy is a sequence of n digits. The first digit isn't zero. Limak thinks that it's a list of some special years. It's hard to see any commas or spaces, so maybe ancient people didn't use them. Now Limak wonders what years are listed there.Limak assumes three things: Years are listed in the strictly increasing order; Every year is a positive integer number; There are no leading zeros. Limak is going to consider all possible ways to split a sequence into numbers (years), satisfying the conditions above. He will do it without any help. However, he asked you to tell him the number of ways to do so. Since this number may be very large, you are only asked to calculate it modulo 109 + 7. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
static final int MODULO = (int) (1e9 + 7);
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
String s = in.next();
int[] numEq = new int[n + 1];
int[] nNumEq = new int[n + 1];
int[][] ways = new int[n][];
for (int i = n - 1; i >= 0; --i) {
ways[i] = new int[n - i + 1];
Arrays.fill(nNumEq, 0);
for (int j = i + 1; j < n; ++j) {
if (s.charAt(j) == s.charAt(i)) {
nNumEq[j] = numEq[j + 1] + 1;
}
}
int[] tmp = numEq;
numEq = nNumEq;
nNumEq = tmp;
if (s.charAt(i) != '0') {
for (int len = n - i; len >= 1; --len) {
if (len == n - i) {
ways[i][len] = 1;
} else {
ways[i][len] = ways[i][len + 1];
}
if (i + 2 * len <= n) {
int cnt = numEq[i + len];
boolean canSame = false;
if (cnt < len && s.charAt(i + cnt) < s.charAt(i + len + cnt)) {
canSame = true;
}
if (canSame) {
ways[i][len] += ways[i + len][len];
} else if (i + 2 * len + 1 <= n) {
ways[i][len] += ways[i + len][len + 1];
}
if (ways[i][len] >= MODULO) {
ways[i][len] -= MODULO;
}
}
}
}
}
out.println(ways[0][1]);
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["6\n123434", "8\n20152016"] | 2.5 seconds | ["8", "4"] | NoteIn the first sample there are 8 ways to split the sequence: "123434" = "123434" (maybe the given sequence is just one big number) "123434" = "1" + "23434" "123434" = "12" + "3434" "123434" = "123" + "434" "123434" = "1" + "23" + "434" "123434" = "1" + "2" + "3434" "123434" = "1" + "2" + "3" + "434" "123434" = "1" + "2" + "3" + "4" + "34" Note that we don't count a split "123434" = "12" + "34" + "34" because numbers have to be strictly increasing.In the second sample there are 4 ways: "20152016" = "20152016" "20152016" = "20" + "152016" "20152016" = "201" + "52016" "20152016" = "2015" + "2016" | Java 7 | standard input | [
"dp",
"hashing",
"strings"
] | 1fe6daf718b88cabb2e956e81add3719 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of digits. The second line contains a string of digits and has length equal to n. It's guaranteed that the first digit is not '0'. | 2,000 | Print the number of ways to correctly split the given sequence modulo 109 + 7. | standard output | |
PASSED | d9ab8866454e785d876d8218509f7fc0 | train_004.jsonl | 1451487900 | Limak is a little polar bear. In the snow he found a scroll with the ancient prophecy. Limak doesn't know any ancient languages and thus is unable to understand the prophecy. But he knows digits!One fragment of the prophecy is a sequence of n digits. The first digit isn't zero. Limak thinks that it's a list of some special years. It's hard to see any commas or spaces, so maybe ancient people didn't use them. Now Limak wonders what years are listed there.Limak assumes three things: Years are listed in the strictly increasing order; Every year is a positive integer number; There are no leading zeros. Limak is going to consider all possible ways to split a sequence into numbers (years), satisfying the conditions above. He will do it without any help. However, he asked you to tell him the number of ways to do so. Since this number may be very large, you are only asked to calculate it modulo 109 + 7. | 512 megabytes | import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.SortedSet;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main
{
private final int MOD = (int)(1e9 + 7);
public void foo()
{
MyScanner scan = new MyScanner();
int n = scan.nextInt();
char[] ch = scan.next().toCharArray();
boolean[][] cmp = new boolean[n + 1][n + 1];
int[][] cmpLen = new int[n + 1][n + 1];
for(int i = 0;i < n;++i)
{
cmp[i][n] = true;
}
for(int i = n - 1;i >= 0;--i)
{
for(int j = i + 1;j < n;++j)
{
if(ch[i] < ch[j])
{
cmp[i][j] = false;
cmpLen[i][j] = 0;
}
else if(ch[i] > ch[j])
{
cmp[i][j] = true;
cmpLen[i][j] = 0;
}
else
{
cmp[i][j] = cmp[i + 1][j + 1];
cmpLen[i][j] = cmpLen[i + 1][j + 1] + 1;
}
}
}
int[][] dp = new int[n][n];
dp[0][0] = 1;
for(int i = 0;i < n;++i)
{
for(int j = i;j < n;++j)
{
if(j >= 1)
{
dp[i][j] = (dp[i][j] + dp[i][j - 1]) % MOD;
}
if(j == n - 1 || '0' == ch[j + 1])
{
continue;
}
int k = j + j - i + 1;
int len = j - i + 1;
if(len <= cmpLen[i][j + 1] || cmp[i][j + 1])
{
++k;
}
if(k < n)
{
dp[j + 1][k] = (dp[j + 1][k] + dp[i][j]) % MOD;
}
}
}
int sum = 0;
for(int i = 0;i < n;++i)
{
sum = (sum + dp[i][n - 1]) % MOD;
}
System.out.println(sum);
}
public static void main(String[] args)
{
new Main().foo();
}
class MyScanner
{
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
BufferedInputStream bis = new BufferedInputStream(System.in);
public int read()
{
if (-1 == numChars)
{
throw new InputMismatchException();
}
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = bis.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
{
return -1;
}
}
return buf[curChar++];
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String next()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c)
{
return ' ' == c || '\n' == c || '\r' == c || '\t' == c || -1 == c;
}
}
} | Java | ["6\n123434", "8\n20152016"] | 2.5 seconds | ["8", "4"] | NoteIn the first sample there are 8 ways to split the sequence: "123434" = "123434" (maybe the given sequence is just one big number) "123434" = "1" + "23434" "123434" = "12" + "3434" "123434" = "123" + "434" "123434" = "1" + "23" + "434" "123434" = "1" + "2" + "3434" "123434" = "1" + "2" + "3" + "434" "123434" = "1" + "2" + "3" + "4" + "34" Note that we don't count a split "123434" = "12" + "34" + "34" because numbers have to be strictly increasing.In the second sample there are 4 ways: "20152016" = "20152016" "20152016" = "20" + "152016" "20152016" = "201" + "52016" "20152016" = "2015" + "2016" | Java 7 | standard input | [
"dp",
"hashing",
"strings"
] | 1fe6daf718b88cabb2e956e81add3719 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of digits. The second line contains a string of digits and has length equal to n. It's guaranteed that the first digit is not '0'. | 2,000 | Print the number of ways to correctly split the given sequence modulo 109 + 7. | standard output | |
PASSED | 816d03ed822f43fd0e3d8ddfaea701f0 | train_004.jsonl | 1451487900 | Limak is a little polar bear. In the snow he found a scroll with the ancient prophecy. Limak doesn't know any ancient languages and thus is unable to understand the prophecy. But he knows digits!One fragment of the prophecy is a sequence of n digits. The first digit isn't zero. Limak thinks that it's a list of some special years. It's hard to see any commas or spaces, so maybe ancient people didn't use them. Now Limak wonders what years are listed there.Limak assumes three things: Years are listed in the strictly increasing order; Every year is a positive integer number; There are no leading zeros. Limak is going to consider all possible ways to split a sequence into numbers (years), satisfying the conditions above. He will do it without any help. However, he asked you to tell him the number of ways to do so. Since this number may be very large, you are only asked to calculate it modulo 109 + 7. | 512 megabytes | import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.SortedSet;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main
{
private final int MOD = (int)(1e9 + 7);
public int mod(int x)
{
if(x >= MOD)
{
x -= MOD;
}
return x;
}
public void foo()
{
MyScanner scan = new MyScanner();
int n = scan.nextInt();
char[] ch = scan.next().toCharArray();
boolean[][] cmp = new boolean[n + 1][n + 1];
int[][] cmpLen = new int[n + 1][n + 1];
for(int i = 0;i < n;++i)
{
cmp[i][n] = true;
}
for(int i = n - 1;i >= 0;--i)
{
for(int j = i + 1;j < n;++j)
{
if(ch[i] < ch[j])
{
cmp[i][j] = false;
cmpLen[i][j] = 0;
}
else if(ch[i] > ch[j])
{
cmp[i][j] = true;
cmpLen[i][j] = 0;
}
else
{
cmp[i][j] = cmp[i + 1][j + 1];
cmpLen[i][j] = cmpLen[i + 1][j + 1] + 1;
}
}
}
int[][] dp = new int[n][n];
dp[0][0] = 1;
for(int i = 0;i < n;++i)
{
for(int j = i;j < n;++j)
{
if(j >= 1)
{
dp[i][j] = mod(dp[i][j] + dp[i][j - 1]);
}
if(j == n - 1 || '0' == ch[j + 1])
{
continue;
}
int k = j + j - i + 1;
int len = j - i + 1;
if(len <= cmpLen[i][j + 1] || cmp[i][j + 1])
{
++k;
}
if(k < n)
{
dp[j + 1][k] = mod(dp[j + 1][k] + dp[i][j]);
}
}
}
int sum = 0;
for(int i = 0;i < n;++i)
{
sum = mod(sum + dp[i][n - 1]);
}
System.out.println(sum);
}
public static void main(String[] args)
{
new Main().foo();
}
class MyScanner
{
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
BufferedInputStream bis = new BufferedInputStream(System.in);
public int read()
{
if (-1 == numChars)
{
throw new InputMismatchException();
}
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = bis.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
{
return -1;
}
}
return buf[curChar++];
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String next()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c)
{
return ' ' == c || '\n' == c || '\r' == c || '\t' == c || -1 == c;
}
}
} | Java | ["6\n123434", "8\n20152016"] | 2.5 seconds | ["8", "4"] | NoteIn the first sample there are 8 ways to split the sequence: "123434" = "123434" (maybe the given sequence is just one big number) "123434" = "1" + "23434" "123434" = "12" + "3434" "123434" = "123" + "434" "123434" = "1" + "23" + "434" "123434" = "1" + "2" + "3434" "123434" = "1" + "2" + "3" + "434" "123434" = "1" + "2" + "3" + "4" + "34" Note that we don't count a split "123434" = "12" + "34" + "34" because numbers have to be strictly increasing.In the second sample there are 4 ways: "20152016" = "20152016" "20152016" = "20" + "152016" "20152016" = "201" + "52016" "20152016" = "2015" + "2016" | Java 7 | standard input | [
"dp",
"hashing",
"strings"
] | 1fe6daf718b88cabb2e956e81add3719 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of digits. The second line contains a string of digits and has length equal to n. It's guaranteed that the first digit is not '0'. | 2,000 | Print the number of ways to correctly split the given sequence modulo 109 + 7. | standard output | |
PASSED | dfa7708706d5a92dad01a84d9b38f550 | train_004.jsonl | 1454835900 | Vitya is studying in the third grade. During the last math lesson all the pupils wrote on arithmetic quiz. Vitya is a clever boy, so he managed to finish all the tasks pretty fast and Oksana Fillipovna gave him a new one, that is much harder.Let's denote a flip operation of an integer as follows: number is considered in decimal notation and then reverted. If there are any leading zeroes afterwards, they are thrown away. For example, if we flip 123 the result is the integer 321, but flipping 130 we obtain 31, and by flipping 31 we come to 13.Oksana Fillipovna picked some number a without leading zeroes, and flipped it to get number ar. Then she summed a and ar, and told Vitya the resulting value n. His goal is to find any valid a.As Oksana Fillipovna picked some small integers as a and ar, Vitya managed to find the answer pretty fast and became interested in finding some general algorithm to deal with this problem. Now, he wants you to write the program that for given n finds any a without leading zeroes, such that a + ar = n or determine that such a doesn't exist. | 256 megabytes | import java.io.*;
import java.util.*;
public class D {
public static void solution(BufferedReader reader, PrintWriter out)
throws IOException {
In in = new In(reader);
String str = in.next();
s = str.toCharArray();
n = s.length;
a = new int[n];
visited = new boolean[n][2][2];
if (dfs(0, n - 1, 0, 0)) {
for (int i = 0; i < n; i++)
out.print(a[i]);
out.println();
return;
}
if (str.charAt(0) == '1' && n > 1) {
s = str.substring(1).toCharArray();
n--;
a = new int[n];
visited = new boolean[n][2][2];
if (dfs(0, n - 1, 1, 0)) {
for (int i = 0; i < n; i++)
out.print(a[i]);
out.println();
return;
}
}
out.println(0);
}
private static int n;
private static char[] s;
private static int[] a;
private static boolean[][][] visited;
private static boolean dfs(int i1, int i2, int c1, int c2) {
if (visited[i1][c1][c2])
return false;
visited[i1][c1][c2] = true;
if (i1 > i2) {
if (c1 != c2)
return false;
return a[0] != 0;
}
else if (i1 == i2)
for (int d = 0; d < 10; d++) {
if ((d + d + c2) % 10 != s[i1] - '0')
continue;
if ((d + d + c2) / 10 != c1)
continue;
a[i1] = d;
return a[0] != 0;
}
else
for (int d1 = 0; d1 < 10; d1++) {
if (i1 == 0 && d1 == 0)
continue;
int d2 = s[i2] - '0' - d1 - c2;
if (d2 < 0)
d2 += 10;
if (d2 < 0 || d2 > 9)
continue;
for (int c = 0; c <= 1; c++) {
if (c1 == 0 && d1 + d2 + c > 9)
continue;
if (c1 == 1 && d1 + d2 + c < 10)
continue;
if ((d1 + d2 + c) % 10 != s[i1] - '0')
continue;
a[i1] = d1;
a[i2] = d2;
if (dfs(i1 + 1, i2 - 1, c, (d1 + d2 + c2) / 10))
return a[0] != 0;
}
}
return false;
}
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(System.out)));
solution(reader, out);
out.close();
}
protected static class In {
private BufferedReader reader;
private StringTokenizer tokenizer = new StringTokenizer("");
public In(BufferedReader reader) {
this.reader = reader;
}
public String next() throws IOException {
while (!tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(reader.readLine());
return tokenizer.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());
}
}
}
| Java | ["4", "11", "5", "33"] | 2 seconds | ["2", "10", "0", "21"] | NoteIn the first sample 4 = 2 + 2, a = 2 is the only possibility.In the second sample 11 = 10 + 1, a = 10 — the only valid solution. Note, that a = 01 is incorrect, because a can't have leading zeroes.It's easy to check that there is no suitable a in the third sample.In the fourth sample 33 = 30 + 3 = 12 + 21, so there are three possibilities for a: a = 30, a = 12, a = 21. Any of these is considered to be correct answer. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"math"
] | fc892e4aac2d60e53f377a582f5ba7d3 | The first line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 2,400 | If there is no such positive integer a without leading zeroes that a + ar = n then print 0. Otherwise, print any valid a. If there are many possible answers, you are allowed to pick any. | standard output | |
PASSED | 605810417aebbfcbbaee9a921361d381 | train_004.jsonl | 1454835900 | Vitya is studying in the third grade. During the last math lesson all the pupils wrote on arithmetic quiz. Vitya is a clever boy, so he managed to finish all the tasks pretty fast and Oksana Fillipovna gave him a new one, that is much harder.Let's denote a flip operation of an integer as follows: number is considered in decimal notation and then reverted. If there are any leading zeroes afterwards, they are thrown away. For example, if we flip 123 the result is the integer 321, but flipping 130 we obtain 31, and by flipping 31 we come to 13.Oksana Fillipovna picked some number a without leading zeroes, and flipped it to get number ar. Then she summed a and ar, and told Vitya the resulting value n. His goal is to find any valid a.As Oksana Fillipovna picked some small integers as a and ar, Vitya managed to find the answer pretty fast and became interested in finding some general algorithm to deal with this problem. Now, he wants you to write the program that for given n finds any a without leading zeroes, such that a + ar = n or determine that such a doesn't exist. | 256 megabytes |
import java.util.*;
import java.io.*;
public class Solutions
{
public static boolean solve(int[] a, int n)
{
int remainder1, remainder2, carry = 0;
if (n % 2 == 0)
{
for (int i = 0; i < n / 2; i++)
{
remainder1 = a[n - 1 - i] % 10;
remainder2 = a[i] % 10;
if(remainder2 == 0) remainder2 = a[i];
if (remainder1 != remainder2)
{
if (!(remainder2==10 && remainder1==0))
{
if (remainder2 != remainder1 + 1) return false;
if (i == (n / 2) - 1 && (a[i] < 10 && a[n-i-1] < 10)) return false;
a[i]--;
a[i + 1] += 10;
}
}
if (a[i] == a[n - i - 1])
{
continue;
}
else
{
int temp = (a[i] / 10) - (a[n - 1 - i] / 10);
if (temp > 1) return false;
a[n - i - 1] += 10;
int j = 1;
while( n - i - j - 1 > i && a[n - i - j - 1] == 0)
{
a[n - i - j - 1] = 9;
j++;
}
if (n - i - j - 1 > i)
{
a[n - i - j - 1]--;
}
else return false;
if (a[i] != a[n-i-1]) return false;
if (a[i] == 19 || a[n-i-1] == 19) return false;
}
}
if (a[0] == 0) return false;
int[] ans = new int[n];
for (int i = 0; i < n / 2; i++)
{
ans[i] = a[i] / 2;
ans[n - i - 1] = a[i] - (a[i] / 2);
}
for (int i = 0; i < n ; i++)
{
System.out.print(ans[n - i - 1]);
}
return true;
}
else
{
for (int i = 0; i < n / 2; i++)
{
remainder1 = a[n - 1 - i] % 10;
remainder2 = a[i] % 10;
if(remainder2 == 0) remainder2 = a[i];
if (remainder1 != remainder2)
{
if (!(remainder2==10 && remainder1==0))
{
if (remainder2 != remainder1 + 1 ) return false;
a[i]--;
a[i + 1] += 10;
}
}
if (a[i] == a[n - i - 1])
{
continue;
}
else
{
int temp = (a[i] / 10) - (a[n - 1 - i] / 10);
if (temp > 1) return false;
int j = 1;
a[n - i - 1] += 10;
while( n - i - j - 1 > i && a[n - i - j - 1] == 0)
{
a[n - i - j - 1] = 9;
j++;
}
if (n - i - j - 1 > i)
{
a[n - i - j - 1]--;
}
else return false;
if (a[i] != a[n-i-1]) return false;
if (a[i] == 19 || a[n-i-1] == 19) return false;
}
}
if (a[n / 2] % 2 == 1) return false;
if (a[0] == 0) return false;
int[] ans = new int[n];
for (int i = 0; i < n / 2; i++)
{
ans[i] = a[i] / 2;
ans[n - i - 1] = a[i] - (a[i] / 2);
}
ans[n / 2] = a[n / 2] / 2;
for (int i = 0; i < n ; i++)
{
System.out.print(ans[n - i - 1]);
}
return true;
}
}
public static void main(String[] args)throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int n = s.length();
int[] a = new int[n];
int[] b = new int[n-1];
for (int i = 0; i < n; i++)
{
a[i] = (int) s.charAt(i) - (int) '0';
}
if (n > 2)
{
for (int i = n - 1; i >= 1; i--)
{
b[i-1] = a[i];
}
b[0] += 10*a[0];
if(!(solve(a,n) || solve(b,n-1))) System.out.print("0");
}
else if(!(solve(a,n))) System.out.print("0");
}
} | Java | ["4", "11", "5", "33"] | 2 seconds | ["2", "10", "0", "21"] | NoteIn the first sample 4 = 2 + 2, a = 2 is the only possibility.In the second sample 11 = 10 + 1, a = 10 — the only valid solution. Note, that a = 01 is incorrect, because a can't have leading zeroes.It's easy to check that there is no suitable a in the third sample.In the fourth sample 33 = 30 + 3 = 12 + 21, so there are three possibilities for a: a = 30, a = 12, a = 21. Any of these is considered to be correct answer. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"math"
] | fc892e4aac2d60e53f377a582f5ba7d3 | The first line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 2,400 | If there is no such positive integer a without leading zeroes that a + ar = n then print 0. Otherwise, print any valid a. If there are many possible answers, you are allowed to pick any. | standard output | |
PASSED | 3d6297bc372a1ce67b460c4dbe401522 | train_004.jsonl | 1454835900 | Vitya is studying in the third grade. During the last math lesson all the pupils wrote on arithmetic quiz. Vitya is a clever boy, so he managed to finish all the tasks pretty fast and Oksana Fillipovna gave him a new one, that is much harder.Let's denote a flip operation of an integer as follows: number is considered in decimal notation and then reverted. If there are any leading zeroes afterwards, they are thrown away. For example, if we flip 123 the result is the integer 321, but flipping 130 we obtain 31, and by flipping 31 we come to 13.Oksana Fillipovna picked some number a without leading zeroes, and flipped it to get number ar. Then she summed a and ar, and told Vitya the resulting value n. His goal is to find any valid a.As Oksana Fillipovna picked some small integers as a and ar, Vitya managed to find the answer pretty fast and became interested in finding some general algorithm to deal with this problem. Now, he wants you to write the program that for given n finds any a without leading zeroes, such that a + ar = n or determine that such a doesn't exist. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
public class CF_342D {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String number = br.readLine();
System.out.println(getChild(number));
}
public static int[] getDigits(String string) {
int[] digits = new int[string.length()];
for(int i=0;i<string.length();i++) {
digits[string.length()-1-i] = string.charAt(i)-'0';
}
return digits;
}
public static String getChild(String string) {
if(string.length() == 1) {
int num = string.charAt(0)-'0';
if(num % 2 == 0) {
return String.valueOf(num/2);
}
return "0";
}
int[] digits = getDigits(string);
String str1 = getChild(digits);
if(str1 == null && digits[digits.length-1] == 1) {
digits[digits.length-1] = 0;
digits[digits.length-2] += 10;
str1 = getChild(digits);
}
return str1 == null ? "0" : str1;
}
public static String getChild(int[] digits) {
digits = digits.clone();
int size = digits.length;
if(digits[size-1] == 0)
size--;
for(int i=size-1;i>=(size+1)/2;i--) {
int i2 = (size-1)-i;
int delta = digits[i] - digits[i2];
if(delta == 11 || delta == 1) {
digits[i]--;
digits[i-1]+=10;
}
delta = digits[i] - digits[i2];
if(delta == 10) {
digits[i2+1]--;
digits[i2] += 10;
}
delta = digits[i] - digits[i2];
if(i == size-1 && digits[i] == 0) {
size--;
}
}
for(int i=size-1;i>=(size+1)/2;i--) {
int i2 = (size-1)-i;
int delta = digits[i] - digits[i2];
if(delta != 0 || digits[i] < 0 || digits[i] > 18)
return null;
}
if(size % 2 == 1 && digits[size/2] % 2 != 0) {
return null;
}
StringBuilder ans = new StringBuilder();
for(int i=0;i<size/2;i++) {
ans.append(digits[i]/2);
digits[i] /= 2;
}
for(int i=size/2;i<size;i++) {
ans.append((digits[i]+1)/2);
}
if(ans.charAt(0) == '0') {
ans = ans.reverse();
}
if(ans.charAt(0) == '0') {
return null;
}
return ans.toString();
}
}
| Java | ["4", "11", "5", "33"] | 2 seconds | ["2", "10", "0", "21"] | NoteIn the first sample 4 = 2 + 2, a = 2 is the only possibility.In the second sample 11 = 10 + 1, a = 10 — the only valid solution. Note, that a = 01 is incorrect, because a can't have leading zeroes.It's easy to check that there is no suitable a in the third sample.In the fourth sample 33 = 30 + 3 = 12 + 21, so there are three possibilities for a: a = 30, a = 12, a = 21. Any of these is considered to be correct answer. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"math"
] | fc892e4aac2d60e53f377a582f5ba7d3 | The first line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 2,400 | If there is no such positive integer a without leading zeroes that a + ar = n then print 0. Otherwise, print any valid a. If there are many possible answers, you are allowed to pick any. | standard output | |
PASSED | ad495ec911698e972b7b0f0114ade84c | train_004.jsonl | 1454835900 | Vitya is studying in the third grade. During the last math lesson all the pupils wrote on arithmetic quiz. Vitya is a clever boy, so he managed to finish all the tasks pretty fast and Oksana Fillipovna gave him a new one, that is much harder.Let's denote a flip operation of an integer as follows: number is considered in decimal notation and then reverted. If there are any leading zeroes afterwards, they are thrown away. For example, if we flip 123 the result is the integer 321, but flipping 130 we obtain 31, and by flipping 31 we come to 13.Oksana Fillipovna picked some number a without leading zeroes, and flipped it to get number ar. Then she summed a and ar, and told Vitya the resulting value n. His goal is to find any valid a.As Oksana Fillipovna picked some small integers as a and ar, Vitya managed to find the answer pretty fast and became interested in finding some general algorithm to deal with this problem. Now, he wants you to write the program that for given n finds any a without leading zeroes, such that a + ar = n or determine that such a doesn't exist. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
int[] res;
int[] n;
int[][][] dp;
public void solve(int testNumber, InputReader in, PrintWriter out) {
String s = in.next();
final int l = s.length();
n = new int[l];
for (int i = 0; i < l; i++) {
int d = s.charAt(i) - '0';
n[i] = d;
}
res = new int[l];
dp = new int[l][2][2];
reset(dp, l, 2, 2);
// try length l
if (calc(0, l - 1, 0, 0, 0, l - 1)) {
print(out, l);
return;
}
// try length l-1
if ((l > 1) && (n[0] == 1)) {
reset(dp, l, 2, 2);
if (calc(1, l - 1, 0, 1, 0, l - 2)) {
print(out, l - 1);
return;
}
}
out.println("0");
}
private void reset(int[][][] dp, int l, int a, int b) {
for (int i = 0; i < l; i++) {
for (int j = 0; j < a; j++) {
for (int k = 0; k < b; k++) {
dp[i][j][k] = -1;
}
}
}
}
private boolean calc(int x, int y, int ci, int co, int l, int r) {
if (x > y) {
if (ci != co) return false;
return true;
}
if (dp[x][ci][co] > -1) return dp[x][ci][co] > 0;
if (x == y) {
for (int i = 0; i < 10; i++) {
int eq = 2 * i + ci;
if ((eq % 10) != n[x]) continue;
if ((eq / 10) != co) continue;
res[l] = i;
dp[x][ci][co] = 1;
return true;
}
dp[x][ci][co] = 0;
return false;
}
for (int a = 0; a < 10; a++) {
if ((l == 0) && (a == 0)) continue;
for (int b = 0; b < 10; b++) {
for (int c1 = 0; c1 < 2; c1++) {
for (int c2 = 0; c2 < 2; c2++) {
int eq = (a + b + ci);
if ((eq % 10) != n[y]) continue;
if ((eq / 10) != c2) continue;
eq = a + b + c1;
if ((eq % 10) != n[x]) continue;
if ((eq / 10) != co) continue;
res[l] = a;
res[r] = b;
if (calc(x + 1, y - 1, c2, c1, l + 1, r - 1)) {
dp[x][ci][co] = 1;
return true;
}
}
}
}
}
dp[x][ci][co] = 0;
return false;
}
private void print(PrintWriter out, int l) {
for (int i = 0; i < l; i++) {
out.print(res[i]);
}
out.println();
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
}
}
| Java | ["4", "11", "5", "33"] | 2 seconds | ["2", "10", "0", "21"] | NoteIn the first sample 4 = 2 + 2, a = 2 is the only possibility.In the second sample 11 = 10 + 1, a = 10 — the only valid solution. Note, that a = 01 is incorrect, because a can't have leading zeroes.It's easy to check that there is no suitable a in the third sample.In the fourth sample 33 = 30 + 3 = 12 + 21, so there are three possibilities for a: a = 30, a = 12, a = 21. Any of these is considered to be correct answer. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"math"
] | fc892e4aac2d60e53f377a582f5ba7d3 | The first line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 2,400 | If there is no such positive integer a without leading zeroes that a + ar = n then print 0. Otherwise, print any valid a. If there are many possible answers, you are allowed to pick any. | standard output | |
PASSED | ced96ffaeeb82e44f0935785befd41fa | train_004.jsonl | 1454835900 | Vitya is studying in the third grade. During the last math lesson all the pupils wrote on arithmetic quiz. Vitya is a clever boy, so he managed to finish all the tasks pretty fast and Oksana Fillipovna gave him a new one, that is much harder.Let's denote a flip operation of an integer as follows: number is considered in decimal notation and then reverted. If there are any leading zeroes afterwards, they are thrown away. For example, if we flip 123 the result is the integer 321, but flipping 130 we obtain 31, and by flipping 31 we come to 13.Oksana Fillipovna picked some number a without leading zeroes, and flipped it to get number ar. Then she summed a and ar, and told Vitya the resulting value n. His goal is to find any valid a.As Oksana Fillipovna picked some small integers as a and ar, Vitya managed to find the answer pretty fast and became interested in finding some general algorithm to deal with this problem. Now, he wants you to write the program that for given n finds any a without leading zeroes, such that a + ar = n or determine that such a doesn't exist. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
int[] res;
int[] n;
public void solve(int testNumber, InputReader in, PrintWriter out) {
String s = in.next();
final int l = s.length();
n = new int[l];
for (int i = 0; i < l; i++) {
int d = s.charAt(i) - '0';
n[i] = d;
}
res = new int[l];
// try length l
if (calc(0, l - 1, 0, 0, 0, l - 1)) {
print(out, l);
return;
}
// try length l-1
if ((l > 1) && (n[0] == 1)) {
if (calc(1, l - 1, 0, 1, 0, l - 2)) {
print(out, l - 1);
return;
}
}
out.println("0");
}
private boolean calc(int x, int y, int ci, int co, int l, int r) {
if (x > y) {
if (ci != co) return false;
return true;
}
if (x == y) {
for (int i = 0; i < 10; i++) {
int eq = 2 * i + ci;
if ((eq % 10) != n[x]) continue;
if ((eq / 10) != co) continue;
res[l] = i;
return true;
}
return false;
}
for (int a = 0; a < 10; a++) {
if ((l == 0) && (a == 0)) continue;
for (int b = 0; b < 10; b++) {
for (int c1 = 0; c1 < 2; c1++) {
for (int c2 = 0; c2 < 2; c2++) {
int eq = (a + b + ci);
if ((eq % 10) != n[y]) continue;
if ((eq / 10) != c2) continue;
eq = a + b + c1;
if ((eq % 10) != n[x]) continue;
if ((eq / 10) != co) continue;
res[l] = a;
res[r] = b;
if (calc(x + 1, y - 1, c2, c1, l + 1, r - 1))
return true;
else return false;
}
}
}
}
return false;
}
private void print(PrintWriter out, int l) {
for (int i = 0; i < l; i++) {
out.print(res[i]);
}
out.println();
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
}
}
| Java | ["4", "11", "5", "33"] | 2 seconds | ["2", "10", "0", "21"] | NoteIn the first sample 4 = 2 + 2, a = 2 is the only possibility.In the second sample 11 = 10 + 1, a = 10 — the only valid solution. Note, that a = 01 is incorrect, because a can't have leading zeroes.It's easy to check that there is no suitable a in the third sample.In the fourth sample 33 = 30 + 3 = 12 + 21, so there are three possibilities for a: a = 30, a = 12, a = 21. Any of these is considered to be correct answer. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"math"
] | fc892e4aac2d60e53f377a582f5ba7d3 | The first line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 2,400 | If there is no such positive integer a without leading zeroes that a + ar = n then print 0. Otherwise, print any valid a. If there are many possible answers, you are allowed to pick any. | standard output | |
PASSED | 9dc1d551a322ff2aa52b64064d250238 | train_004.jsonl | 1454835900 | Vitya is studying in the third grade. During the last math lesson all the pupils wrote on arithmetic quiz. Vitya is a clever boy, so he managed to finish all the tasks pretty fast and Oksana Fillipovna gave him a new one, that is much harder.Let's denote a flip operation of an integer as follows: number is considered in decimal notation and then reverted. If there are any leading zeroes afterwards, they are thrown away. For example, if we flip 123 the result is the integer 321, but flipping 130 we obtain 31, and by flipping 31 we come to 13.Oksana Fillipovna picked some number a without leading zeroes, and flipped it to get number ar. Then she summed a and ar, and told Vitya the resulting value n. His goal is to find any valid a.As Oksana Fillipovna picked some small integers as a and ar, Vitya managed to find the answer pretty fast and became interested in finding some general algorithm to deal with this problem. Now, he wants you to write the program that for given n finds any a without leading zeroes, such that a + ar = n or determine that such a doesn't exist. | 256 megabytes | import java.io.*;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
Reader in = new Reader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
char[] s = in.next().toCharArray();
try {
int[] ans = solve(s);
for (int an : ans) {
out.print(an);
}
} catch (Exception e) {
System.err.println(e.getMessage());
out.println(0);
}
out.flush();
in.close();
out.close();
}
private static int[] solve(char[] s) throws Exception {
int[] ans;
try {
int[] a = new int[s.length];
for (int i = 0; i < s.length; i++) {
a[i] = s[i] - '0';
}
ans = build(a);
if (ans[0] == 0) {
throw new Exception("have leading zero");
}
} catch (Exception e) {
System.err.println(e.getMessage());
ans = build2(s);
if (ans[0] == 0) {
throw new Exception("have leading zero");
}
}
return ans;
}
private static int[] build2(char[] s) throws Exception {
int[] a = new int[s.length - 1];
for (int i = 1; i < s.length; i++) {
a[i - 1] = s[i] - '0';
}
if (s[0] == '1') {
a[0] += 10;
} else {
throw new Exception("second plan have to start with 1");
}
return build(a);
}
private static int[] build(int[] s) throws Exception {
int[] ans = new int[s.length];
int half = (s.length + 1) / 2;
for (int left = 0; left < half; left++) {
int right = s.length - 1 - left;
if (left == right) {
if (s[left] % 2 != 0) {
throw new Exception("center is odd");
} else if (s[left] > 18) {
throw new Exception("18x");
}
ans[left] = s[left] / 2;
} else {
if (s[right] < 0) {
s[right] += 10;
s[right - 1]--;
}
if (s[left] == s[right] + 11 || s[left] == s[right] + 1) {
s[left]--;
s[left + 1] += 10;
}
if (s[left] > 18) {
throw new Exception("18x");
}
if (s[left] == s[right]) {
ans[right] = s[left] / 2;
ans[left] = s[left] - ans[right];
} else if (left + 1 != right && s[left] == s[right] + 10) {
ans[right] = s[left] / 2;
ans[left] = s[left] - ans[right];
s[right - 1]--;
} else {
throw new Exception("miss match s[" + left + "]=" + s[left] + "; s[" + right + "]=" + s[right] + ";");
}
}
}
return ans;
}
private static String debug(char left, char right, boolean upBefore, boolean needUp, Node node) {
return left + " " + right + "; before: " + upBefore + "; need: " + needUp + " => " + node.a + " " + node.b;
}
static class Node {
int a, b;
public Node(int a, int b) {
this.a = a;
this.b = b;
}
}
static class Reader {
BufferedReader reader;
StringTokenizer st;
Reader(InputStreamReader stream) {
reader = new BufferedReader(stream);
st = null;
}
void close() throws IOException {
reader.close();
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
String nextLine() throws IOException {
return reader.readLine();
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["4", "11", "5", "33"] | 2 seconds | ["2", "10", "0", "21"] | NoteIn the first sample 4 = 2 + 2, a = 2 is the only possibility.In the second sample 11 = 10 + 1, a = 10 — the only valid solution. Note, that a = 01 is incorrect, because a can't have leading zeroes.It's easy to check that there is no suitable a in the third sample.In the fourth sample 33 = 30 + 3 = 12 + 21, so there are three possibilities for a: a = 30, a = 12, a = 21. Any of these is considered to be correct answer. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"math"
] | fc892e4aac2d60e53f377a582f5ba7d3 | The first line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 2,400 | If there is no such positive integer a without leading zeroes that a + ar = n then print 0. Otherwise, print any valid a. If there are many possible answers, you are allowed to pick any. | standard output | |
PASSED | f28299d72cddd1d1b1fd8b0ab0abdfd5 | train_004.jsonl | 1454835900 | Vitya is studying in the third grade. During the last math lesson all the pupils wrote on arithmetic quiz. Vitya is a clever boy, so he managed to finish all the tasks pretty fast and Oksana Fillipovna gave him a new one, that is much harder.Let's denote a flip operation of an integer as follows: number is considered in decimal notation and then reverted. If there are any leading zeroes afterwards, they are thrown away. For example, if we flip 123 the result is the integer 321, but flipping 130 we obtain 31, and by flipping 31 we come to 13.Oksana Fillipovna picked some number a without leading zeroes, and flipped it to get number ar. Then she summed a and ar, and told Vitya the resulting value n. His goal is to find any valid a.As Oksana Fillipovna picked some small integers as a and ar, Vitya managed to find the answer pretty fast and became interested in finding some general algorithm to deal with this problem. Now, he wants you to write the program that for given n finds any a without leading zeroes, such that a + ar = n or determine that such a doesn't exist. | 256 megabytes |
import java.util.Scanner;
public class Solution {
static int[] A;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s = in.next();
if (s.equals("1")) {
System.out.println(0);
return;
}
A = new int[s.length()];
for (int i = 0; i < A.length; i++) {
A[i] = s.charAt(i) - '0';
}
if (A[0] == 1) {
int[] Atemp = A.clone();
solution = new int[A.length];
solution[0] = 0;
if (isPossible(1, A.length - 1, true)) {
printSolution();
return;
}
A = Atemp;
}
solution = new int[A.length];
if (isPossible(0, A.length - 1, false)) {
printSolution();
} else {
System.out.println("0");
}
}
static int[] solution;
public static void printSolution() {
boolean zeroes = true;
for (int i = 0; i < solution.length; i++) {
if (solution[i] != 0) {
zeroes = false;
}
if (!zeroes) {
System.out.print(solution[i]);
}
}
System.out.println();
}
public static boolean isPossible(int front, int end, boolean carry1) {
if (front + 1 == end) {
if (!carry1) {
solution[end] = A[front] / 2;
solution[front] = A[front] - A[front] / 2;
return A[front] == A[end];
}
if (carry1) {
solution[end] = A[end] / 2 + 5;
solution[front] = A[end] - A[end] / 2 + 5;
return (A[front] - 1) == A[end];
}
} else if (front == end) {
solution[front] = ((carry1 ? 10 : 0) + A[front]) / 2;
return (A[front] % 2 == 0);
} else {
if (carry1 && A[end] != 9) {
A[end - 1]--;
int index = end - 1;
while (index >= front && A[index] == -1) {
A[index] = 9;
index--;
A[index]--;
}
if (index < front) {
return false;
}
}
if ((A[end] + 1) % 10 == A[front]) {
if (A[end] == 9 && !carry1) {
return false;
}
solution[end] = A[end] / 2;
solution[front] = A[end] - A[end] / 2;
if (A[end] == 0 && front == 0) {
//System.out.println("ASAHAHJKAS");
return false;
}
if (carry1 && A[end] != 9) {
solution[end] += 5;
solution[front] += 5;
}
boolean weirdCase = false;
/*if(A[front]==0){
weirdCase = true;
}*/
//System.out.println(A[2] + " " + A[3]);
return isPossible(front + 1, end - 1, !weirdCase);
} else if (A[front] == A[end]) {
solution[end] = A[end] / 2;
solution[front] = A[end] - A[end] / 2;
if (carry1) {
solution[end] += 5;
solution[front] += 5;
}
return isPossible(front + 1, end - 1, false);
} else {
return false;
}
}
return false;
}
}
| Java | ["4", "11", "5", "33"] | 2 seconds | ["2", "10", "0", "21"] | NoteIn the first sample 4 = 2 + 2, a = 2 is the only possibility.In the second sample 11 = 10 + 1, a = 10 — the only valid solution. Note, that a = 01 is incorrect, because a can't have leading zeroes.It's easy to check that there is no suitable a in the third sample.In the fourth sample 33 = 30 + 3 = 12 + 21, so there are three possibilities for a: a = 30, a = 12, a = 21. Any of these is considered to be correct answer. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"math"
] | fc892e4aac2d60e53f377a582f5ba7d3 | The first line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 2,400 | If there is no such positive integer a without leading zeroes that a + ar = n then print 0. Otherwise, print any valid a. If there are many possible answers, you are allowed to pick any. | standard output | |
PASSED | 727c596ee78b60c005cfdf7b06eaf510 | train_004.jsonl | 1454835900 | Vitya is studying in the third grade. During the last math lesson all the pupils wrote on arithmetic quiz. Vitya is a clever boy, so he managed to finish all the tasks pretty fast and Oksana Fillipovna gave him a new one, that is much harder.Let's denote a flip operation of an integer as follows: number is considered in decimal notation and then reverted. If there are any leading zeroes afterwards, they are thrown away. For example, if we flip 123 the result is the integer 321, but flipping 130 we obtain 31, and by flipping 31 we come to 13.Oksana Fillipovna picked some number a without leading zeroes, and flipped it to get number ar. Then she summed a and ar, and told Vitya the resulting value n. His goal is to find any valid a.As Oksana Fillipovna picked some small integers as a and ar, Vitya managed to find the answer pretty fast and became interested in finding some general algorithm to deal with this problem. Now, he wants you to write the program that for given n finds any a without leading zeroes, such that a + ar = n or determine that such a doesn't exist. | 256 megabytes | // practice with rainboy
import java.io.*;
import java.util.*;
public class CF625D extends PrintWriter {
CF625D() { super(System.out, true); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF625D o = new CF625D(); o.main(); o.flush();
}
boolean solve(byte[] cc, byte[] aa, int n) {
for (int i = 0, j = n - 1; i < j; i++, j--) {
if (cc[i] == cc[j] + 1 || cc[i] == cc[j] + 11) {
cc[i]--;
cc[i + 1] += 10;
}
if (cc[i] == cc[j] + 10) {
int h = j - 1;
while (h > i && cc[h] == 0) {
cc[h] = 9;
h--;
}
if (h == i)
return false;
cc[h]--;
cc[j] += 10;
}
if (cc[i] != cc[j] || cc[i] > 18)
return false;
aa[i] = (byte) Math.min(cc[i], 9);
aa[j] = (byte) (cc[i] - aa[i]);
}
if (n % 2 == 1) {
if (cc[n / 2] % 2 != 0 || cc[n / 2] > 18)
return false;
aa[n / 2] = (byte) (cc[n / 2] / 2);
}
return aa[0] != 0;
}
void main() {
byte[] cc = sc.next().getBytes();
int n = cc.length;
for (int i = 0; i < n; i++)
cc[i] -= '0';
byte[] cc_ = null;
if (n > 1) {
cc_ = new byte[n - 1];
for (int i = 1; i < n; i++)
cc_[i - 1] = cc[i];
cc_[0] += cc[0] * 10;
}
byte[] aa = new byte[n];
if (solve(cc, aa, n)) {
for (int i = 0; i < n; i++)
aa[i] += '0';
println(new String(aa));
return;
}
if (n > 1 && solve(cc_, aa, n - 1)) {
for (int i = 0; i < n - 1; i++)
aa[i] += '0';
println(new String(aa, 0, n - 1));
return;
}
println(0);
}
}
| Java | ["4", "11", "5", "33"] | 2 seconds | ["2", "10", "0", "21"] | NoteIn the first sample 4 = 2 + 2, a = 2 is the only possibility.In the second sample 11 = 10 + 1, a = 10 — the only valid solution. Note, that a = 01 is incorrect, because a can't have leading zeroes.It's easy to check that there is no suitable a in the third sample.In the fourth sample 33 = 30 + 3 = 12 + 21, so there are three possibilities for a: a = 30, a = 12, a = 21. Any of these is considered to be correct answer. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"math"
] | fc892e4aac2d60e53f377a582f5ba7d3 | The first line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 2,400 | If there is no such positive integer a without leading zeroes that a + ar = n then print 0. Otherwise, print any valid a. If there are many possible answers, you are allowed to pick any. | standard output | |
PASSED | 14900d19385c6283458a097e4d990671 | train_004.jsonl | 1454835900 | Vitya is studying in the third grade. During the last math lesson all the pupils wrote on arithmetic quiz. Vitya is a clever boy, so he managed to finish all the tasks pretty fast and Oksana Fillipovna gave him a new one, that is much harder.Let's denote a flip operation of an integer as follows: number is considered in decimal notation and then reverted. If there are any leading zeroes afterwards, they are thrown away. For example, if we flip 123 the result is the integer 321, but flipping 130 we obtain 31, and by flipping 31 we come to 13.Oksana Fillipovna picked some number a without leading zeroes, and flipped it to get number ar. Then she summed a and ar, and told Vitya the resulting value n. His goal is to find any valid a.As Oksana Fillipovna picked some small integers as a and ar, Vitya managed to find the answer pretty fast and became interested in finding some general algorithm to deal with this problem. Now, he wants you to write the program that for given n finds any a without leading zeroes, such that a + ar = n or determine that such a doesn't exist. | 256 megabytes | import java.io.*;
import java.util.*;
public class D {
FastScanner in;
PrintWriter out;
char[] a;
char[] c;
int n;
HashMap<Long, Boolean> mem = new HashMap<>();
long code(int l, int r, int to, int from) {
return ((l * 1L * n + r) * 2 + to) * 2 + from;
}
boolean ans(long id, boolean x) {
mem.put(id, x);
return x;
}
boolean can(int l, int r, int to, int from) {
long id = code(l, r, to, from);
if (mem.containsKey(id)) {
return mem.get(id);
}
if (r < l) {
return ans(id, to == from);
}
if (l == r) {
for (int x = 0; x < 10; x++) {
int d = x + x + from;
c[r] = (char) (x + '0');
if (d % 10 == a[l] - '0' && d / 10 == to) {
return ans(id, true);
}
}
return ans(id, false);
}
for (int y = 9; y >= 0; y--) {
for (int x = 0; x < 10; x++) {
c[r] = (char) (x + '0');
c[l] = (char) (y + '0');
int d = x + y + from;
if (d % 10 == a[r] - '0') {
int from2 = d / 10;
for (int to2 = 0; to2 < 2; to2++) {
int t = x + y + to2;
if (t % 10 == a[l] - '0' && t / 10 == to) {
if (can(l + 1, r - 1, to2, from2)) {
return ans(id, true);
}
}
}
}
}
}
return ans(id, false);
}
void solve() {
a = in.next().toCharArray();
n = a.length;
c = new char[n];
StringBuffer ans = new StringBuffer();
if (can(0, n - 1, 0, 0) && c[0] != '0') {
for (int i = 0; i < n; i++) {
ans.append(c[i]);
}
} else if (a[0] == '1' && can(1, n - 1, 1, 0) && c[1] != '0') {
for (int i = 1; i < n; i++) {
ans.append(c[i]);
}
}
if (ans.length() == 0) {
ans.append(0);
}
out.println(ans.toString());
}
void run() {
in = new FastScanner();
out = new PrintWriter(System.out);
solve();
out.close();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
public static void main(String[] args) {
new D().run();
}
} | Java | ["4", "11", "5", "33"] | 2 seconds | ["2", "10", "0", "21"] | NoteIn the first sample 4 = 2 + 2, a = 2 is the only possibility.In the second sample 11 = 10 + 1, a = 10 — the only valid solution. Note, that a = 01 is incorrect, because a can't have leading zeroes.It's easy to check that there is no suitable a in the third sample.In the fourth sample 33 = 30 + 3 = 12 + 21, so there are three possibilities for a: a = 30, a = 12, a = 21. Any of these is considered to be correct answer. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"math"
] | fc892e4aac2d60e53f377a582f5ba7d3 | The first line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 2,400 | If there is no such positive integer a without leading zeroes that a + ar = n then print 0. Otherwise, print any valid a. If there are many possible answers, you are allowed to pick any. | standard output | |
PASSED | 88c1125df3516931713eabc1c06ff4d6 | train_004.jsonl | 1454835900 | Vitya is studying in the third grade. During the last math lesson all the pupils wrote on arithmetic quiz. Vitya is a clever boy, so he managed to finish all the tasks pretty fast and Oksana Fillipovna gave him a new one, that is much harder.Let's denote a flip operation of an integer as follows: number is considered in decimal notation and then reverted. If there are any leading zeroes afterwards, they are thrown away. For example, if we flip 123 the result is the integer 321, but flipping 130 we obtain 31, and by flipping 31 we come to 13.Oksana Fillipovna picked some number a without leading zeroes, and flipped it to get number ar. Then she summed a and ar, and told Vitya the resulting value n. His goal is to find any valid a.As Oksana Fillipovna picked some small integers as a and ar, Vitya managed to find the answer pretty fast and became interested in finding some general algorithm to deal with this problem. Now, he wants you to write the program that for given n finds any a without leading zeroes, such that a + ar = n or determine that such a doesn't exist. | 256 megabytes | import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.StringTokenizer;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* 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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
int[] sol;
boolean[][] dp;
PrintWriter out;
public void solve(int testNumber, InputReader in, PrintWriter out) {
String s = in.next();
this.out = out;
int[] a = new int[s.length()];
for (int i=0; i<s.length(); i++){
a[i] = s.charAt(i) - '0';
}
sol = new int[a.length];
dp = new boolean[a.length][4];
if (find(0, 0, a, a.length)){
return;
}
if (a[0] == 1) {
for (int i = 0; i < a.length - 1; i++) {
a[i] = a[i + 1];
}
sol = new int[a.length-1];
dp = new boolean[a.length-1][4];
if (find(0, 2, a, a.length-1)){
return;
}
}
out.println(0);
}
private boolean find(int index, int config, int[] a, int n) {
int left = index;
int right = n-1-index;
int conf1 = config & 2;
int conf2 = config & 1;
if (left > right){
if (config == 0 || config == 3){
printSol(n);
return true;
}
return false;
}
if (left == right){
int sum = a[left];
if (conf1 != 0){
sum += 10;
}
if (conf2 != 0){
sum--;
}
if (sum % 2 == 0){
sol[left] = sum/2;
printSol(n);
return true;
}
return false;
}
if (dp[index][config]){
return false;
}
int sumLeft = a[index];
if (conf1!=0){
sumLeft += 10;
}
int sumRight = a[right];
if (conf2 !=0){
sumRight--;
}
// 0 0
if (sumRight >= 0 && sumRight == sumLeft){
int nr1 = sumLeft/2;
int nr2 = sumLeft-nr1;
sol[index] = nr2;
sol[n-1-index] = nr1;
if (sol[index] < 10 && sol[0] != 0 && find(index+1, 0, a, n)){
return true;
}
}
// 0 1
if (sumLeft == sumRight+10){
int nr1 = sumLeft / 2;
int nr2 = sumLeft -nr1;
sol[index] = nr2;
sol[n-1-index] = nr1;
if (sol[index] < 10 &&sol[0] != 0 &&find(index+1, 1, a, n)){
return true;
}
}
// 1 0
if (sumLeft-1 == sumRight && sumRight >= 0){
int nr1 = sumRight / 2;
int nr2 = sumRight -nr1;
sol[index] = nr2;
sol[n-1-index] = nr1;
if (sol[index] < 10 &&sol[0] != 0 && find(index+1, 2, a, n)){
return true;
}
}
// 1 1
if (sumLeft-1 == sumRight+10 && sumLeft-1 >= 0){
int nr1 = (sumRight+10) / 2;
int nr2 = sumRight+10 -nr1;
sol[index] = nr2;
sol[n-1-index] = nr1;
if (sol[index] < 10 &&sol[0] != 0 &&find(index+1, 3, a, n)){
return true;
}
}
dp[index][config] = true;
return false;
}
private void printSol(int n) {
for (int i=0; i<n; i++){
out.print(sol[i]);
}
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream){
reader = new BufferedReader(new InputStreamReader(stream));
}
public String next(){
while (tokenizer == null || !tokenizer.hasMoreTokens()){
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException("FATAL ERROR", e);
}
}
return tokenizer.nextToken();
}
}
| Java | ["4", "11", "5", "33"] | 2 seconds | ["2", "10", "0", "21"] | NoteIn the first sample 4 = 2 + 2, a = 2 is the only possibility.In the second sample 11 = 10 + 1, a = 10 — the only valid solution. Note, that a = 01 is incorrect, because a can't have leading zeroes.It's easy to check that there is no suitable a in the third sample.In the fourth sample 33 = 30 + 3 = 12 + 21, so there are three possibilities for a: a = 30, a = 12, a = 21. Any of these is considered to be correct answer. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"math"
] | fc892e4aac2d60e53f377a582f5ba7d3 | The first line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 2,400 | If there is no such positive integer a without leading zeroes that a + ar = n then print 0. Otherwise, print any valid a. If there are many possible answers, you are allowed to pick any. | standard output | |
PASSED | 72745f89a7ecd0a7f6f18fcad707b78e | train_004.jsonl | 1583246100 | Kuroni is very angry at the other setters for using him as a theme! As a punishment, he forced them to solve the following problem:You have an array $$$a$$$ consisting of $$$n$$$ positive integers. An operation consists of choosing an element and either adding $$$1$$$ to it or subtracting $$$1$$$ from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not $$$1$$$. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment! | 256 megabytes | import java.util.*;
import java.io.*;
import java.text.*;
public class Main{
//SOLUTION BEGIN
//Into the Hardware Mode
void pre() throws Exception{}
void solve(int TC)throws Exception {
int n = ni();
long[] a = new long[n];
for(int i = 0; i< n; i++)a[i] = nl();
TreeSet<Long> set = new TreeSet<>();
Random r = new Random();
for(int IT = 0; IT < 20; IT++){
long x = a[r.nextInt(n)];
add(set, x);
add(set, x+1);
add(set, x-1);
}
long ans = n+1;
for(long l:set){
if(l < 2)continue;
long cur = 0;
for(int i = 0; i< n; i++){
if(a[i] < l)cur += l-a[i];
else cur += Math.min(a[i]%l, l-a[i]%l);
}
ans = Math.min(ans,cur);
}
pn(ans);
}
void add(TreeSet<Long> set, long x){
for(long j = 2; j*j <= x; j++){
if(x%j != 0)continue;
while(x%j == 0)x /= j;
set.add(j);
}
if(x > 1)set.add(x);
}
//SOLUTION END
void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
void exit(boolean b){if(!b)System.exit(0);}
// long IINF = (long)1e15;
final int INF = (int)1e9+2, MX = (int)2e6+5;
DecimalFormat df = new DecimalFormat("0.00000000000");
double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-8;
static boolean multipleTC = false, memory = false, fileIO = false;
FastReader in;PrintWriter out;
void run() throws Exception{
long ct = System.currentTimeMillis();
if (fileIO) {
in = new FastReader("");
out = new PrintWriter("");
} else {
in = new FastReader();
out = new PrintWriter(System.out);
}
//Solution Credits: Taranpreet Singh
int T = (multipleTC) ? ni() : 1;
pre();
for (int t = 1; t <= T; t++) solve(t);
out.flush();
out.close();
System.err.println(System.currentTimeMillis() - ct);
}
public static void main(String[] args) throws Exception{
if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start();
else new Main().run();
}
int[][] make(int n, int[] from, int[] to, boolean f){
int[][] g = new int[n][];int[]cnt = new int[n];
for(int i:from)cnt[i]++;if(f)for(int i:to)cnt[i]++;
for(int i = 0; i< n; i++)g[i] = new int[cnt[i]];
for(int i = 0; i< from.length; i++){
g[from[i]][--cnt[from[i]]] = to[i];
if(f)g[to[i]][--cnt[to[i]]] = from[i];
}
return g;
}
int find(int[] set, int u){return set[u] = (set[u] == u?u:find(set, set[u]));}
int digit(long s){int ans = 0;while(s>0){s/=10;ans++;}return ans;}
long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));}
void p(Object o){out.print(o);}
void pn(Object o){out.println(o);}
void pni(Object o){out.println(o);out.flush();}
String n()throws Exception{return in.next();}
String nln()throws Exception{return in.nextLine();}
int ni()throws Exception{return Integer.parseInt(in.next());}
long nl()throws Exception{return Long.parseLong(in.next());}
double nd()throws Exception{return Double.parseDouble(in.next());}
class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception{
br = new BufferedReader(new FileReader(s));
}
String next() throws Exception{
while (st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}catch (IOException e){
throw new Exception(e.toString());
}
}
return st.nextToken();
}
String nextLine() throws Exception{
String str;
try{
str = br.readLine();
}catch (IOException e){
throw new Exception(e.toString());
}
return str;
}
}
} | Java | ["3\n6 2 4", "5\n9 8 7 3 1"] | 2.5 seconds | ["0", "4"] | NoteIn the first example, the first array is already good, since the greatest common divisor of all the elements is $$$2$$$.In the second example, we may apply the following operations: Add $$$1$$$ to the second element, making it equal to $$$9$$$. Subtract $$$1$$$ from the third element, making it equal to $$$6$$$. Add $$$1$$$ to the fifth element, making it equal to $$$2$$$. Add $$$1$$$ to the fifth element again, making it equal to $$$3$$$. The greatest common divisor of all elements will then be equal to $$$3$$$, so the array will be good. It can be shown that no sequence of three or less operations can make the array good. | Java 8 | standard input | [
"number theory",
"probabilities",
"math"
] | 40a32523f982e24fba2c785fc6a27881 | The first line contains an integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. ($$$1 \le a_i \le 10^{12}$$$) — the elements of the array. | 2,500 | Print a single integer — the minimum number of operations required to make the array good. | standard output | |
PASSED | 270f535afaeef88b21d03d443d41f821 | train_004.jsonl | 1583246100 | Kuroni is very angry at the other setters for using him as a theme! As a punishment, he forced them to solve the following problem:You have an array $$$a$$$ consisting of $$$n$$$ positive integers. An operation consists of choosing an element and either adding $$$1$$$ to it or subtracting $$$1$$$ from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not $$$1$$$. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment! | 256 megabytes | import java.io.*;
import java.util.*;
public class F {
public static void main (String[] args) { new F(); }
public F() {
FastScanner fs = new FastScanner();
fs = new FastScanner("testdata.out");
System.err.println("");
int n = fs.nextInt();
int odds = 0;
long[] a = new long[n];
boolean fuckthis = false;
for(int i = 0; i < n; i++) {
a[i] = fs.nextLong();
if(a[i]%2 == 1) odds++;
}
long[] b = a; int m = n;
// if(fuckthis) {
// System.out.println(m);
// }
Random rand = new Random();
int iters = 30;
TreeSet<Long> toTest = new TreeSet<>();
while(iters-->0) {
int idx = rand.nextInt(m);
for(long x = b[idx]-1; x <= b[idx]+1; x++) {
if(x < 2) continue;
long[] pf = pf(x);
for(long p : pf) toTest.add(p);
}
}
long res = odds;
for(long p : toTest) {
long ret = 0;
for(int i = 0; i < n; i++) {
long rem = a[i]%p;
if(a[i] < p) ret += p-a[i];
else ret += Math.min(rem, p-rem);
}
if(ret < res) res = ret;
}
System.out.println(res);
}
long[] pf(long N) {
long[] res = new long[12];
int ptr = 0;
for(long i = 2; i*i <= N; i++) {
if(N%i != 0) continue;
while(N%i == 0) N /= i;
res[ptr++] = i;
}
if(N > 1) res[ptr++] = N;
res = Arrays.copyOfRange(res, 0, ptr);
return res;
}
class FastScanner {
public int BS = 1<<16;
public char NC = (char)0;
byte[] buf = new byte[BS];
int bId = 0, size = 0;
char c = NC;
double num = 1;
BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
public char nextChar(){
while(bId==size) {
try {
size = in.read(buf);
}catch(Exception e) {
return NC;
}
if(size==-1)return NC;
bId=0;
}
return (char)buf[bId++];
}
public int nextInt() {
return (int)nextLong();
}
public long nextLong() {
num=1;
boolean neg = false;
if(c==NC)c=nextChar();
for(;(c<'0' || c>'9'); c = nextChar()) {
if(c=='-')neg=true;
}
long res = 0;
for(; c>='0' && c <='9'; c=nextChar()) {
res = (res<<3)+(res<<1)+c-'0';
num*=10;
}
return neg?-res:res;
}
public double nextDouble() {
double cur = nextLong();
return c!='.' ? cur:cur+nextLong()/num;
}
public String next() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c>32) {
res.append(c);
c=nextChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c!='\n') {
res.append(c);
c=nextChar();
}
return res.toString();
}
public boolean hasNext() {
if(c>32)return true;
while(true) {
c=nextChar();
if(c==NC)return false;
else if(c>32)return true;
}
}
public int[] nextIntArray(int n) {
int[] res = new int[n];
for(int i = 0; i < n; i++) res[i] = nextInt();
return res;
}
}
} | Java | ["3\n6 2 4", "5\n9 8 7 3 1"] | 2.5 seconds | ["0", "4"] | NoteIn the first example, the first array is already good, since the greatest common divisor of all the elements is $$$2$$$.In the second example, we may apply the following operations: Add $$$1$$$ to the second element, making it equal to $$$9$$$. Subtract $$$1$$$ from the third element, making it equal to $$$6$$$. Add $$$1$$$ to the fifth element, making it equal to $$$2$$$. Add $$$1$$$ to the fifth element again, making it equal to $$$3$$$. The greatest common divisor of all elements will then be equal to $$$3$$$, so the array will be good. It can be shown that no sequence of three or less operations can make the array good. | Java 8 | standard input | [
"number theory",
"probabilities",
"math"
] | 40a32523f982e24fba2c785fc6a27881 | The first line contains an integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. ($$$1 \le a_i \le 10^{12}$$$) — the elements of the array. | 2,500 | Print a single integer — the minimum number of operations required to make the array good. | standard output | |
PASSED | 2d6aa51cd7d2e914003222c6f015e2bb | train_004.jsonl | 1583246100 | Kuroni is very angry at the other setters for using him as a theme! As a punishment, he forced them to solve the following problem:You have an array $$$a$$$ consisting of $$$n$$$ positive integers. An operation consists of choosing an element and either adding $$$1$$$ to it or subtracting $$$1$$$ from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not $$$1$$$. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment! | 256 megabytes | /*
If you want to aim high, aim high
Don't let that studying and grades consume you
Just live life young
******************************
If I'm the sun, you're the moon
Because when I go up, you go down
*******************************
I'm working for the day I will surpass you
https://www.a2oj.com/Ladder16.html
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class F2
{
public static void main(String omkar[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
long[] arr = new long[N];
st = new StringTokenizer(infile.readLine());
for(int i=0; i < N; i++)
arr[i] = Long.parseLong(st.nextToken());
sort(arr);
long res = 0;
for(long x: arr)
res += x%2;
int T = 10;
while(T-->0)
{
int dex = (int)(Math.random()*N);
for(int barg=0; barg < 3; barg++)
{
long val = arr[dex];
if(barg == 0)
val--;
else if(barg == 1)
val++;
if(val > 1)
{
ArrayList<Long> ls = findDiv(val);
for(long p: ls)
res = Math.min(res, find(arr, N, p));
}
}
}
System.out.println(res);
}
public static ArrayList<Long> findDiv(long t)
{
ArrayList<Long> ls = new ArrayList<Long>();
long N = t;
if(N%2 == 0)
{
ls.add(2L);
while(N%2 == 0)
N /= 2;
}
for(int i=3; i <= (int)(Math.sqrt(t+0.00001)); i++)
if(N%i == 0)
{
ls.add((long)i);
while(N%i == 0)
N /= i;
}
if(N > 1)
ls.add(N);
return ls;
}
public static long find(long a[], int n, long k)
{
long res = 0L;
for (int i = 0; i < n; ++i)
{
if(a[i] != 1 && a[i] > k)
res = res+Math.min(a[i]%k, k-a[i]%k);
else
res = res+k-a[i];
}
return res;
}
public static void sort(long[] arr)
{
//stable heap sort
PriorityQueue<Long> pq = new PriorityQueue<Long>();
for(long a: arr)
pq.add(a);
for(int i=0; i < arr.length; i++)
arr[i] = pq.poll();
}
} | Java | ["3\n6 2 4", "5\n9 8 7 3 1"] | 2.5 seconds | ["0", "4"] | NoteIn the first example, the first array is already good, since the greatest common divisor of all the elements is $$$2$$$.In the second example, we may apply the following operations: Add $$$1$$$ to the second element, making it equal to $$$9$$$. Subtract $$$1$$$ from the third element, making it equal to $$$6$$$. Add $$$1$$$ to the fifth element, making it equal to $$$2$$$. Add $$$1$$$ to the fifth element again, making it equal to $$$3$$$. The greatest common divisor of all elements will then be equal to $$$3$$$, so the array will be good. It can be shown that no sequence of three or less operations can make the array good. | Java 8 | standard input | [
"number theory",
"probabilities",
"math"
] | 40a32523f982e24fba2c785fc6a27881 | The first line contains an integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. ($$$1 \le a_i \le 10^{12}$$$) — the elements of the array. | 2,500 | Print a single integer — the minimum number of operations required to make the array good. | standard output | |
PASSED | 35851e53b11684d809cfc7b4a03a1b0b | train_004.jsonl | 1583246100 | Kuroni is very angry at the other setters for using him as a theme! As a punishment, he forced them to solve the following problem:You have an array $$$a$$$ consisting of $$$n$$$ positive integers. An operation consists of choosing an element and either adding $$$1$$$ to it or subtracting $$$1$$$ from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not $$$1$$$. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment! | 256 megabytes | /*
If you want to aim high, aim high
Don't let that studying and grades consume you
Just live life young
******************************
If I'm the sun, you're the moon
Because when I go up, you go down
*******************************
I'm working for the day I will surpass you
https://www.a2oj.com/Ladder16.html
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class F2
{
public static void main(String omkar[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
long[] arr = new long[N];
st = new StringTokenizer(infile.readLine());
for(int i=0; i < N; i++)
arr[i] = Long.parseLong(st.nextToken());
sort(arr);
long res = 0;
for(long x: arr)
res += x%2;
int T = 20;
while(T-->0)
{
int dex = (int)(Math.random()*N);
for(int barg=0; barg < 3; barg++)
{
long val = arr[dex];
if(barg == 0)
val--;
else if(barg == 1)
val++;
if(val > 1)
{
ArrayList<Long> ls = findDiv(val);
for(long p: ls)
res = Math.min(res, find(arr, N, p));
}
}
}
System.out.println(res);
}
public static ArrayList<Long> findDiv(long t)
{
ArrayList<Long> ls = new ArrayList<Long>();
long N = t;
if(N%2 == 0)
{
ls.add(2L);
while(N%2 == 0)
N /= 2;
}
for(int i=3; i <= (int)(Math.sqrt(t+0.00001)); i++)
if(N%i == 0)
{
ls.add((long)i);
while(N%i == 0)
N /= i;
}
if(N > 1)
ls.add(N);
return ls;
}
public static long find(long a[], int n, long k)
{
long res = 0L;
for (int i = 0; i < n; ++i)
{
if(a[i] != 1 && a[i] > k)
res = res+Math.min(a[i]%k, k-a[i]%k);
else
res = res+k-a[i];
}
return res;
}
public static void sort(long[] arr)
{
//stable heap sort
PriorityQueue<Long> pq = new PriorityQueue<Long>();
for(long a: arr)
pq.add(a);
for(int i=0; i < arr.length; i++)
arr[i] = pq.poll();
}
} | Java | ["3\n6 2 4", "5\n9 8 7 3 1"] | 2.5 seconds | ["0", "4"] | NoteIn the first example, the first array is already good, since the greatest common divisor of all the elements is $$$2$$$.In the second example, we may apply the following operations: Add $$$1$$$ to the second element, making it equal to $$$9$$$. Subtract $$$1$$$ from the third element, making it equal to $$$6$$$. Add $$$1$$$ to the fifth element, making it equal to $$$2$$$. Add $$$1$$$ to the fifth element again, making it equal to $$$3$$$. The greatest common divisor of all elements will then be equal to $$$3$$$, so the array will be good. It can be shown that no sequence of three or less operations can make the array good. | Java 8 | standard input | [
"number theory",
"probabilities",
"math"
] | 40a32523f982e24fba2c785fc6a27881 | The first line contains an integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. ($$$1 \le a_i \le 10^{12}$$$) — the elements of the array. | 2,500 | Print a single integer — the minimum number of operations required to make the array good. | standard output | |
PASSED | 0847805825874d018e7eab7fb89ac302 | train_004.jsonl | 1583246100 | Kuroni is very angry at the other setters for using him as a theme! As a punishment, he forced them to solve the following problem:You have an array $$$a$$$ consisting of $$$n$$$ positive integers. An operation consists of choosing an element and either adding $$$1$$$ to it or subtracting $$$1$$$ from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not $$$1$$$. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment! | 256 megabytes | /*
javac ozonF.java && java ozonF
*/
// but it's random Mike Q.Q
import java.io.*;
import java.math.*;
import java.util.*;
public class ozonF {
public static void main(String[] args) { new ozonF(); }
FS in = new FS();
PrintWriter out = new PrintWriter(System.out);
int n;
long ans;
long[] a;
ozonF() {
n = in.nextInt();
ans = 0;
a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextLong();
ans += (a[i] & 1);
}
int ptr;
long cur;
long[] stk = new long[64];
Random r = new Random();
for (int it = 0; it < 35; it++) {
int x = r.nextInt(n);
for (int j = -1; j <= 1; j++) {
ptr = 0;
long y = a[x] + j;
long z = y;
if (y < 2) continue;
for (long i = 2; i * i <= z; i++)
if (y % i == 0) {
stk[ptr++] = i;
while (y % i == 0)
y /= i;
}
if (y != 1)
stk[ptr++] = y;
while (ptr > 0) {
ptr--;
cur = 0;
y = stk[ptr];
for (int i = 0; i < n; i++) {
if (a[i] < y)
cur += y - a[i];
else
cur += min(a[i] % y, y - (a[i] % y));
}
ans = min(ans, cur);
}
}
}
out.println(ans);
out.close();
}
int abs(int x) { if (x < 0) return -x; return x; }
long abs(long x) { if (x < 0) return -x; return x; }
int max(int x, int y) { if (x < y) return y; return x; }
int min(int x, int y) { if (x > y) return y; return x; }
long max(long x, long y) { if (x < y) return y; return x; }
long min(long x, long y) { if (x > y) return y; return x; }
int gcd(int x, int y) { while (y > 0) { x = y^(x^(y = x)); y %= x; } return x; }
long gcd(long x, long y) { while (y > 0) { x = y^(x^(y = x)); y %= x; } return x; }
long lcm(int x, int y) { return ((long) x) * (y / gcd(x, y)); }
long lcm(long x, long y) { return x * (y / gcd(x, y)); }
class FS {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens()) {
try { st = new StringTokenizer(br.readLine()); }
catch (Exception e) {}
} return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble() { return Double.parseDouble(next()); }
}
}
| Java | ["3\n6 2 4", "5\n9 8 7 3 1"] | 2.5 seconds | ["0", "4"] | NoteIn the first example, the first array is already good, since the greatest common divisor of all the elements is $$$2$$$.In the second example, we may apply the following operations: Add $$$1$$$ to the second element, making it equal to $$$9$$$. Subtract $$$1$$$ from the third element, making it equal to $$$6$$$. Add $$$1$$$ to the fifth element, making it equal to $$$2$$$. Add $$$1$$$ to the fifth element again, making it equal to $$$3$$$. The greatest common divisor of all elements will then be equal to $$$3$$$, so the array will be good. It can be shown that no sequence of three or less operations can make the array good. | Java 8 | standard input | [
"number theory",
"probabilities",
"math"
] | 40a32523f982e24fba2c785fc6a27881 | The first line contains an integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. ($$$1 \le a_i \le 10^{12}$$$) — the elements of the array. | 2,500 | Print a single integer — the minimum number of operations required to make the array good. | standard output | |
PASSED | 92e215e19fd4b3fa99887930f2ade251 | train_004.jsonl | 1583246100 | Kuroni is very angry at the other setters for using him as a theme! As a punishment, he forced them to solve the following problem:You have an array $$$a$$$ consisting of $$$n$$$ positive integers. An operation consists of choosing an element and either adding $$$1$$$ to it or subtracting $$$1$$$ from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not $$$1$$$. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment! | 256 megabytes | /*
javac ozonF.java && java ozonF
*/
// but it's random Mike Q.Q
import java.io.*;
import java.math.*;
import java.util.*;
public class ozonF {
public static void main(String[] args) { new ozonF(); }
FS in = new FS();
PrintWriter out = new PrintWriter(System.out);
int n;
long ans;
long[] a;
ozonF() {
n = in.nextInt();
ans = 0;
a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextLong();
ans += (a[i] & 1);
}
int ptr;
long cur;
long[] stk = new long[64];
Random r = new Random();
for (int it = 0; it < 20; it++) {
int x = r.nextInt(n);
for (int j = -1; j <= 1; j++) {
ptr = 0;
long y = a[x] + j;
long z = y;
if (y < 2) continue;
for (long i = 2; i * i <= z; i++)
if (y % i == 0) {
stk[ptr++] = i;
while (y % i == 0)
y /= i;
}
if (y != 1)
stk[ptr++] = y;
while (ptr > 0) {
ptr--;
cur = 0;
y = stk[ptr];
for (int i = 0; i < n; i++) {
if (a[i] < y)
cur += y - a[i];
else
cur += min(a[i] % y, y - (a[i] % y));
}
ans = min(ans, cur);
}
}
}
out.println(ans);
out.close();
}
int abs(int x) { if (x < 0) return -x; return x; }
long abs(long x) { if (x < 0) return -x; return x; }
int max(int x, int y) { if (x < y) return y; return x; }
int min(int x, int y) { if (x > y) return y; return x; }
long max(long x, long y) { if (x < y) return y; return x; }
long min(long x, long y) { if (x > y) return y; return x; }
int gcd(int x, int y) { while (y > 0) { x = y^(x^(y = x)); y %= x; } return x; }
long gcd(long x, long y) { while (y > 0) { x = y^(x^(y = x)); y %= x; } return x; }
long lcm(int x, int y) { return ((long) x) * (y / gcd(x, y)); }
long lcm(long x, long y) { return x * (y / gcd(x, y)); }
class FS {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens()) {
try { st = new StringTokenizer(br.readLine()); }
catch (Exception e) {}
} return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble() { return Double.parseDouble(next()); }
}
}
| Java | ["3\n6 2 4", "5\n9 8 7 3 1"] | 2.5 seconds | ["0", "4"] | NoteIn the first example, the first array is already good, since the greatest common divisor of all the elements is $$$2$$$.In the second example, we may apply the following operations: Add $$$1$$$ to the second element, making it equal to $$$9$$$. Subtract $$$1$$$ from the third element, making it equal to $$$6$$$. Add $$$1$$$ to the fifth element, making it equal to $$$2$$$. Add $$$1$$$ to the fifth element again, making it equal to $$$3$$$. The greatest common divisor of all elements will then be equal to $$$3$$$, so the array will be good. It can be shown that no sequence of three or less operations can make the array good. | Java 8 | standard input | [
"number theory",
"probabilities",
"math"
] | 40a32523f982e24fba2c785fc6a27881 | The first line contains an integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. ($$$1 \le a_i \le 10^{12}$$$) — the elements of the array. | 2,500 | Print a single integer — the minimum number of operations required to make the array good. | standard output | |
PASSED | a42fa74da7af81f38a52248b004cde72 | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes | import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n =s.nextInt();
int k = s.nextInt();
if(k%2==0){
System.out.println("YES");
int hotels =k;
for(int i=0;i<4;i++){
for(int j=0;j<n;j++){
if(i==1 && j>0 && hotels>k/2){
System.out.print("#");
hotels--;
}
else if(i==2 && j>0 && hotels>0){
System.out.print("#");
hotels--;
}
else{
System.out.print(".");
}
}
System.out.println();
}
}
else {
System.out.println("YES");
int hotels =k;
int h1;
if(k>=n-2){
h1 = n-2;
}else{
h1 = k;
}
// System.out.println(h1);
for(int i=0;i<4;i++){
for(int j=0;j<n;j++){
if(i==1 && j>=(n/2)-(h1/2) && j<=(n/2)+(h1/2)){
System.out.print("#");
hotels--;
continue;
}if((i==2 && j>=1 && j<1+(hotels/2) && hotels>0) || (j>=n-1-(hotels/2) && j<n-1 && i==2 && hotels>0)){
System.out.print("#");
}else{
System.out.print(".");
}
}
// System.out.println(hotels);
System.out.println();
}
}
}
}
| Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | f161312fce7732bf7395b6eb081aa0df | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes | import java.util.Scanner;
import java.util.Arrays;
public class Solution
{
public static void main(String[] args)
{
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
int k=scan.nextInt();
char[] array = new char[n];
Arrays.fill(array, '.');
if(k<=2*(n-2))
{
System.out.println("YES");
// for(int i=0;i<n;i++)
// System.out.print('.');
System.out.println(String.valueOf(array));
// System.out.println();
for(int j=1;j<3;j++)
{
Arrays.fill(array, '.');
if(k>0)
{
// System.out.println("K VAlue : "+k);
for(int i=1;i<n/2 && k>1;i++)
{
array[i]=array[n-1-i]='#';
k-=2;
}
if(k>0)
{
array[n/2]='#';
k--;
}
}
System.out.println(String.valueOf(array));
}
for(int i=0;i<n;i++)
System.out.print('.');
System.out.println();
}
else
{
System.out.println("NO");
}
}
} | Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | 039a71c95cc444677937d86f07e326a4 | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes |
import java.util.*;
import java.io.*;
public class B
{
public static void main(String[] args) throws Exception
{
PrintWriter out = new PrintWriter(System.out);
new B(new FastScanner(System.in), out);
out.close();
}
public B(FastScanner in, PrintWriter out)
{
int N = in.nextInt();
int K = in.nextInt();
char[][] grid = new char[4][N];
for (int i=0; i<4; i++)
for (int j=0; j<N; j++)
grid[i][j] = '.';
if (K % 2 == 0)
{
int col = 1;
for (int k=0; k<K; k+=2)
{
grid[1][col] = grid[2][col] = '#';
col++;
}
}
else if (N <= K)
{
for (int x=1; x<=N-2; x++)
grid[1][x] = '#';
grid[2][1] = grid[2][N-2] = '#';
K -= N;
for (int k=0; k<K; k++)
grid[2][k+2] = '#';
}
else if (K == N-2)
{
for (int x=1; x<=N-2; x++)
grid[1][x] = '#';
}
else if (K >= 5)
{
K -= 2;
for (int x=1; x<=K; x++)
{
grid[1][x] = '#';
}
grid[2][1] = grid[2][K] = '#';
}
else if (K == 1)
{
int m = N/2;
grid[2][m] = '#';
}
else if (K == 3)
{
int m = N/2;
grid[2][m] = '#';
grid[1][m-1] = '#';
grid[1][m+1] = '#';
}
else
{
out.println("NO");
return;
}
out.println("YES");
for (char[] cur : grid)
out.println(new String(cur));
}
}
class FastScanner{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastScanner(InputStream stream)
{
this.stream = stream;
}
int read()
{
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars){
curChar = 0;
try{
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
boolean isSpaceChar(int c)
{
return c==' '||c=='\n'||c=='\r'||c=='\t'||c==-1;
}
boolean isEndline(int c)
{
return c=='\n'||c=='\r'||c==-1;
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String next(){
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do{
res.appendCodePoint(c);
c = read();
}while(!isSpaceChar(c));
return res.toString();
}
String nextLine(){
int c = read();
while (isEndline(c))
c = read();
StringBuilder res = new StringBuilder();
do{
res.appendCodePoint(c);
c = read();
}while(!isEndline(c));
return res.toString();
}
}
| Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | 368a40c9accda8affab4e77a6985b0d8 | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.io.InputStream;
/**
* @author Jenish
*/
public class Main {
public static void main(String[] ARGS) {
new Thread(null, new Runnable() {
public void run() {
new Main().solve();
}
}, "1", 1 << 26).start();
}
void solve() {
InputStream IS = System.in;
OutputStream OS = System.out;
ScanReader in = new ScanReader(IS);
PrintWriter out = new PrintWriter(OS);
BMarlin bmarlin = new BMarlin();
bmarlin.solve(1, in, out);
out.close();
}
static class BMarlin {
public void solve(int testNumber, ScanReader in, PrintWriter out) {
int n = in.scanInt();
int k = in.scanInt();
char arr[][] = new char[4][n];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = '.';
}
}
if (k % 2 == 0) {
int row = 1;
int x1 = 1;
int y1 = n - 1 - 1;
while (k > 0) {
if (row > 2) {
break;
}
if (x1 < y1) {
arr[row][x1] = '#';
arr[row][y1] = '#';
x1++;
y1--;
k--;
k--;
} else {
x1 = 1;
y1 = n - 1 - 1;
row++;
}
}
if (k == 0) {
out.println("YES");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < n; j++) {
out.print(arr[i][j]);
}
out.println();
}
} else {
if (k == 2) {
arr[1][n / 2] = '#';
arr[2][n / 2] = '#';
out.println("YES");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < n; j++) {
out.print(arr[i][j]);
}
out.println();
}
} else {
out.println("NO");
return;
}
}
} else {
arr[1][n / 2] = '#';
k--;
int row = 1;
int x1 = 1;
int y1 = n - 1 - 1;
while (k > 0) {
if (row > 2) {
break;
}
if (x1 < y1) {
arr[row][x1] = '#';
arr[row][y1] = '#';
x1++;
y1--;
k--;
k--;
} else {
x1 = 1;
y1 = n - 1 - 1;
row++;
}
}
if (k == 0) {
out.println("YES");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < n; j++) {
out.print(arr[i][j]);
}
out.println();
}
} else {
if (k == 1) {
arr[2][n / 2] = '#';
out.println("YES");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < n; j++) {
out.print(arr[i][j]);
}
out.println();
}
} else {
out.println("NO");
return;
}
}
}
}
}
static class ScanReader {
private byte[] buf = new byte[4 * 1024];
private int index;
private BufferedInputStream in;
private int Total_Char;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() {
if (index >= Total_Char) {
index = 0;
try {
Total_Char = in.read(buf);
} catch (Exception e) {
e.printStackTrace();
}
if (Total_Char <= 0) return -1;
}
return buf[index++];
}
public int scanInt() {
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();
}
}
return neg * integer;
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
}
}
| Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | c996b994bf8357d8aad9cd4e925667f7 | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 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();
char [][] p = new char[4][n];
for (int i =0;i<4;i++)
Arrays.fill(p[i], '.');
if (m%2==0 && m>0) {
p[1][n/2]='#';
p[2][n/2]='#';
m-=2;
}else if (m%2!=0) {
p[1][n/2]='#';
m--;
}
//System.out.println(m);
for (int i=1;i<3;i++) {
if(m==0)
break;
int j=1,k=n-2;
while(j<k) {
p[i][j]='#';
m--;
j++;
if (m==0)
break;
p[i][k]='#';
m--;
k--;
if (m==0)
break;
}
}
if(m>0)System.out.println("NO");
else
{
System.out.println("YES");
for (int i =0;i<4;i++) {
for (int j =0;j<n;j++) {
System.out.print(p[i][j]);
}
System.out.println();
}
}
sc.close();
}
}
| Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | a5a951c0bbbf2af155477d5b70a9f90c | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes | import java.io.*;
import java.util.*;
public class R480B {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int r = 4;
int c = scan.nextInt();
int k = scan.nextInt();
int area = (r-2)*(c-2);
if(k % 2 == 1){
if(c % 2 == 0){
out.println("NO");
out.flush();
return;
}
}
if(area >= k){
if(k % 2 == 0){
out.println("YES");
for(int i = 0; i < c; i++) out.print('.');
out.println();
int count = 1;
out.print('.');
for(int i = 0; i < k/2; i++){
out.print('#');
count++;
}
while(count < c){
out.print('.');
count++;
}
out.println();
count = 1;
out.print('.');
for(int i = 0; i < k/2; i++){
out.print('#');
count++;
}
while(count < c){
out.print('.');
count++;
}
out.println();
for(int i = 0; i < c; i++) out.print('.');
out.println();
}
else if(k % 2 == 1){
out.println("YES");
for(int i = 0; i < c; i++) out.print('.');
out.println();
char[] arr1 = new char[c];
char[] arr2 = new char[c];
Arrays.fill(arr1, '.');
Arrays.fill(arr2, '.');
int idx = c/2;
int bonus = 1;
arr1[idx] = '#';
k--;
while(idx-bonus > 0 && k > 0){
arr1[idx+bonus] = '#';
arr1[idx-bonus] = '#';
k-=2;
bonus++;
}
bonus--;
while(k > 0){
arr2[idx+bonus] = '#';
arr2[idx-bonus] = '#';
k-=2;
bonus--;
}
for(int i = 0; i < c; i++) out.print(arr1[i]);
out.println();
for(int i = 0; i < c; i++) out.print(arr2[i]);
out.println();
for(int i = 0; i < c; i++) out.print('.');
out.println();
}
else out.println("NO");
}
else{
out.println("NO");
}
out.flush();
}
}
| Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | a0096e9d3876d7ed01322daf0770de66 | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes |
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
public class CF {
public static void main(String[] args) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int k = in.nextInt();
if (k % 2 == 0) {
out.println("YES");
for (int i = 0; i < n; i++) {
out.print(".");
}
out.println();
out.print(".");
for (int i = 0; i < k / 2; i++) {
out.print("#");
}
for (int i = 0; i < n - k / 2 - 1; i++) {
out.print(".");
}
out.println();
out.print(".");
for (int i = 0; i < k / 2; i++) {
out.print("#");
}
for (int i = 0; i < n - k / 2 - 1; i++) {
out.print(".");
}
out.println();
for (int i = 0; i < n; i++) {
out.print(".");
}
out.println();
} else {
out.println("YES");
for (int i = 0; i < n; i++) {
out.print(".");
}
out.println();
if (k > n - 2) {
out.print(".");
for (int i = 0; i < n - 2; i++) {
out.print("#");
}
out.println(".");
k %= n - 2;
out.print(".");
for (int i = 0; i < k / 2; i++) {
out.print("#");
}
for (int i = 0; i < n - 2 - k; i++) {
out.print(".");
}
for (int i = 0; i < k / 2; i++) {
out.print("#");
}
out.println(".");
} else {
out.print(".");
for (int i = 0; i < k / 2; i++) {
out.print("#");
}
int m = n - 2 - k;
for (int i = 0; i < m / 2; i++) {
out.print(".");
}
out.print("#");
for (int i = 0; i < m / 2; i++) {
out.print(".");
}
for (int i = 0; i < k/2; i++) {
out.print("#");
}
out.println(".");
for (int i = 0; i < n; i++) {
out.print(".");
}
out.println();
}
for (int i = 0; i < n; i++) {
out.print(".");
}
out.println();
}
out.close();
}
public static void verif(int[] tab, int n, int k, int index, String ch) {
if (index == 255) {
System.out.println(ch);
return;
}
for (int i = 0; i < k; i++) {
if (index + i + 1 <= 255) {
verif(tab, n, k, index + i + 1, ch + " " + (index + i + 1));
}
}
}
public static int upper_bound(int[] tab, int l, int h, long x) {
while (l < h) {
int mid = (l + h) / 2;
if (tab[mid] <= x) {
l = mid + 1;
} else {
h = mid;
}
}
return l;
}
public static int[] radixsort(int[] input) {
// Largest place for a 32-bit int is the 1 billion's place
for (int place = 1; place <= 1000000000; place *= 10) {
// Use counting sort at each digit's place
input = countingSort(input, place);
}
return input;
}
private static int[] countingSort(int[] input, int place) {
int[] out = new int[input.length];
int[] count = new int[10];
for (int i = 0; i < input.length; i++) {
int digit = getDigit(input[i], place);
count[digit] += 1;
}
for (int i = 1; i < count.length; i++) {
count[i] += count[i - 1];
}
for (int i = input.length - 1; i >= 0; i--) {
int digit = getDigit(input[i], place);
out[count[digit] - 1] = input[i];
count[digit]--;
}
return out;
}
private static int getDigit(int value, int digitPlace) {
return ((value / digitPlace) % 10);
}
static class FastScanner {
private BufferedReader in;
private String[] line;
private int index;
private int size;
public FastScanner(InputStream in) throws IOException {
this.in = new BufferedReader(new InputStreamReader(in));
init();
}
public FastScanner(String file) throws FileNotFoundException {
this.in = new BufferedReader(new FileReader(file));
}
private void init() throws IOException {
line = in.readLine().split(" ");
index = 0;
size = line.length;
}
public int nextInt() throws IOException {
if (index == size) {
init();
}
return Integer.parseInt(line[index++]);
}
public long nextLong() throws IOException {
if (index == size) {
init();
}
return Long.parseLong(line[index++]);
}
public float nextFloat() throws IOException {
if (index == size) {
init();
}
return Float.parseFloat(line[index++]);
}
public double nextDouble() throws IOException {
if (index == size) {
init();
}
return Double.parseDouble(line[index++]);
}
public String next() throws IOException {
if (index == size) {
init();
}
return line[index++];
}
public String nextLine() throws IOException {
if (index == size) {
init();
}
StringBuilder sb = new StringBuilder();
for (; index < size; index++) {
sb.append(line[index]).append(" ");
}
return sb.toString();
}
private int[] nextIntArray(int n) throws IOException {
int[] tab = new int[n];
for (int i = 0; i < tab.length; i++) {
tab[i] = nextInt();
}
return tab;
}
private long[] nextLongArray(int n) throws IOException {
long[] tab = new long[n];
for (int i = 0; i < tab.length; i++) {
tab[i] = nextLong();
}
return tab;
}
private double[] nextDoubleArray(int n) throws IOException {
double[] tab = new double[n];
for (int i = 0; i < tab.length; i++) {
tab[i] = nextDouble();
}
return tab;
}
}
}
| Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | dc0dc675649021ed7e241c0531628336 | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes | import java.util.*;
public class que1
{
void solve()
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
char[][] map = new char[4][n];
for(char[] row : map)
Arrays.fill(row, '.');
for(int i = 1; i < 3; i++)
for(int j = 1; j < n / 2 && k > 1; j++, k -= 2)
map[i][j] = map[i][n - 1 - j] = '#';
for(int i = 1; i < 3 && k > 0; i++, k--)
map[i][n / 2] = '#';
System.out.println("YES");
for(char[] row : map)
System.out.println(new String(row));
}
public static void main (String[] args){
new que1().solve();}
} | Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | 8839008d9704e774a85b346356ee8677 | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes | import java.util.*;
import java.io.*;
public class Marlin
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
int[][] ans = new int[4][n];
if(k%2==0)
{
System.out.println("YES");
for(int i=0;i<2;i++)
{
for(int j=0;j<k/2;j++)
ans[i+1][j+1] = '#';
}
for(int i=0;i<4;i++)
{
for(int j=0;j<n;j++)
{
if(ans[i][j]=='#')
System.out.print("#");
else
System.out.print(".");
}
System.out.println("");
}
}
else
{
if(k<=n-2)
{
if(n%2!=0)
{
System.out.println("YES");
ans[1][n/2]='#';
for(int i=n/2;i<n/2+k/2;i++)
{
ans[1][n-i-2]='#';
ans[1][i+1]='#';
}
for(int i=0;i<4;i++)
{
for(int j=0;j<n;j++)
{
if(ans[i][j]=='#')
System.out.print("#");
else
System.out.print(".");
}
System.out.println("");
}
}
else
{
System.out.println("NO");
}
}
else
{
k = k - n + 2;
if(k==1)
System.out.println("NO");
else
{
System.out.println("YES");
for(int i=1;i<n-1;i++)
ans[1][i] = '#';
ans[2][n-2] = '#';
for(int i=1;i<k;i++)
{
ans[2][i] = '#';
}
for(int i=0;i<4;i++)
{
for(int j=0;j<n;j++)
{
if(ans[i][j]=='#')
System.out.print("#");
else
System.out.print(".");
}
System.out.println("");
}
}
}
}
}
}
| Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | 7e30dd0c019268fb62f02087d00c33f3 | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes |
import java.util.*;
import java.io.*;
public class Solution2 {
private void solve() throws IOException {
int n = in.nextInt();
int k = in.nextInt();
if (k % 2 == 0) {
StringBuilder st = new StringBuilder("YES\n");
for (int i = 0; i < n; i++) st.append('.'); st.append('\n');
for (int i = 0; i < 2; i++) {
int a = k / 2;
st.append('.');
for (int j = 0; j < n - 2; j++) {
if (a > 0) {
st.append('#');
a--;
}
else st.append('.');
}
st.append('.');
st.append('\n');
}
for (int i = 0; i < n; i++) st.append('.');
System.out.println(st);
}
else if (k > n - 2) {
StringBuilder st = new StringBuilder("YES\n");
for (int i = 0; i < n; i++) st.append('.'); st.append('\n');
st.append('.');
for (int i = 0; i < n - 2; i++) st.append('#');
st.append('.');
st.append('\n');
st.append('.');
st.append('#');
st.append('.');
k--;
k -= (n - 2);
for (int i = 0; i < n - 5; i++) {
if (k > 1) {
st.append('#');
k--;
}
else st.append('.');
}
st.append('#');
st.append('.');
st.append('\n');
for (int i = 0; i < n; i++) st.append('.');
System.out.println(st);
}
else if (k == n - 2){
StringBuilder st = new StringBuilder("YES\n");
for (int i = 0; i < n; i++) st.append('.'); st.append('\n');
st.append('.');
for (int i = 0; i < n - 2; i++) {
if (k > 0) {
st.append('#');
k--;
}
else st.append('.');
}
st.append('.');
st.append('\n');
for (int i = 0; i < n; i++) st.append('.'); st.append('\n');
for (int i = 0; i < n; i++) st.append('.');
System.out.println(st);
}
else {
StringBuilder st = new StringBuilder("YES\n");
for (int i = 0; i < n; i++) st.append('.'); st.append('\n');
st.append('.');
int a = k / 2;
int p = 0;
for (int i = 0; i < n - 2; i++) {
if (a > 0) {
st.append('#');
a--;
}
else if (i < n / 2 - 1) {
p++;
st.append('.');
}
else if (i == n / 2 - 1) {
st.append('#');
}
else if (i > n / 2 - 1 + p) {
st.append('#');
}
else {
st.append('.');
}
}
st.append('.');
st.append('\n');
for (int i = 0; i < n; i++) st.append('.'); st.append('\n');
for (int i = 0; i < n; i++) st.append('.');
System.out.println(st);
}
}
private PrintWriter out;
private MyScanner in;
private void run() throws IOException {
in = new MyScanner();
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
}
private class MyScanner {
private BufferedReader br;
private StringTokenizer st;
public MyScanner() throws IOException {
this.br = new BufferedReader(new InputStreamReader(System.in));
}
public MyScanner(String fileTitle) throws IOException {
this.br = new BufferedReader(new FileReader(fileTitle));
}
public String nextLine() throws IOException {
String s = br.readLine();
return s == null ? "-1" : s;
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String s = br.readLine();
if (s == null) {
return "-1";
}
st = new StringTokenizer(s);
}
return st.nextToken();
}
public Integer nextInt() throws IOException {
return Integer.parseInt(this.next());
}
public Long nextLong() throws IOException {
return Long.parseLong(this.next());
}
public Double nextDouble() throws IOException {
return Double.parseDouble(this.next());
}
public void close() throws IOException {
this.br.close();
}
}
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.US);
new Solution2().run();
}
}
| Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | 7762dffb72ae69c98c82cb1abf7627fb | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes | // Marcelino Galarza
// May 8th, 2018
import java.util.*;
public class b
{
public static int R = 4;
public static int C;
public static char grid[][];
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
C = in.nextInt();
int hotels = in.nextInt();
grid = new char[R][C];
for (int i = 0; i < R; i++)
Arrays.fill(grid[i], '.');
System.out.println("YES");
for (int i = 1; i < R-1; i++)
{
if (hotels%2==1 && hotels < C-2)
{
grid[i][C/2] = '#';
hotels--;
}
for (int j = 1, x = C-2; j <= x && hotels > 0; j++, x--)
{
grid[i][x] = '#';
grid[i][j] = '#';
if (x == j)
hotels--;
else
hotels-=2;
}
}
for (int i = 0; i < R; i++)
for (int j = 0; j < C; j++)
System.out.print(grid[i][j] + (j == C-1 ? "\n" : ""));
in.close();
}
}
| Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | 86eea34c5464c55bd9ba83e831fd7f1d | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class Main implements Runnable
{
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception {
new Thread(null, new Main(),"Main",1<<26).start();
}
void printEmpty(int n) {
for(int i = 0; i < n; ++i)
System.out.print(".");
System.out.println();
}
public void run() {
InputReader sc = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int n = sc.nextInt();
int k = sc.nextInt();
System.out.println("YES");
if(k == 2 * (n - 2)) {
printEmpty(n);
for(int p = 0; p < 2; ++p) {
System.out.print(".");
for(int i = 0; i < n - 2; ++i)
System.out.print("#");
System.out.println(".");
}
printEmpty(n);
return;
}
char s[][] = new char[4][n];
for(int i = 0; i < 4; ++i) {
for(int j = 0; j < n; ++j)
s[i][j] = '.';
}
if(k % 2 == 1) {
s[1][n / 2] = '#';
k--;
}
for(int i = 1; i < n / 2 && k != 0; ++i) {
s[1][i] = '#';
s[1][n - 1 - i] = '#';
k -= 2;
}
for(int i = 1; i < n / 2 && k != 0; ++i) {
s[2][i] = '#';
s[2][n - 1 - i] = '#';
k -= 2;
}
for(int i = 0; i < 4; ++i)
w.println(s[i]);
w.close();
}
} | Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | dd950b13d7fbf2226295415a78ac9e71 | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes |
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
public class Watermelon {
public static void main(String[] args) throws IOException {
Reader sc=new Reader();
int n=sc.nextInt(),k=sc.nextInt();
char[][] car=new char[4][n];
for(int i=0;i<4;i++)Arrays.fill(car[i],'.');
if(k>2*(n-2)){System.out.println("NO");}
else if(k<2*(n-2)){
System.out.println("YES");
for(int i=0;i<4;i++) {
if(k%2==1){
k-=1;
car[1][(n/2)]='#';
}
for (int j = 1; j < (n)/2 && i == 1 && k > 0; j++) {
car[i][j] = '#';
car[i][n-j-1]='#';
k -= 2;
}
for (int j = 1; j < (n)/2 && i == 2 && k > 0; j++) {
car[i][j] = '#';
car[i][n-j-1]='#';
k -= 2;
}
}
for(int i=0;i<4;i++){
for(int j=0;j<n;j++){
System.out.print(car[i][j]);
}
System.out.println();
}
}
else{
System.out.println("YES");
for(int i=1;i<=2;i++)
for(int j=1;j<n-1;j++)
car[i][j]='#';
for(int i=0;i<4;i++){
for(int j=0;j<n;j++){
System.out.print(car[i][j]);
}
System.out.println();
}
}
}
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();
}
}
} | Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | 9e1dadcaa0a0bf3658ea7fb2797f7601 | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 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.StringTokenizer;
import java.io.IOException;
import java.io.Reader;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Nathaniel Lahn
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
int k = in.nextInt();
//handle n = 3 case separate
char[][] grid = new char[4][n];
for (int i = 0; i < 4; i++) {
Arrays.fill(grid[i], '.');
}
if (k % 2 == 0) {
for (int i = 0; i < k; i++) {
int c = i / (2);
int r = i % (2);
grid[r + 1][c + 1] = '#';
}
} else {//k is odd
if (k <= n - 2) {
int start = (n - 2 - k) / 2 + 1;
for (int i = start; i < start + k; i++) {
grid[1][i] = '#';
}
} else {
//blockade
k -= n - 2;
for (int i = 0; i < n - 2; i++) {
grid[1][i + 1] = '#';
}
k -= 2;
grid[2][1] = '#';
grid[2][n - 2] = '#';
int start = 2;
for (int i = start; i < start + k; i++) {
grid[2][i] = '#';
}
}
}
StringBuilder sb = new StringBuilder();
sb.append("YES\n");
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
sb.append(grid[i][j]);
}
sb.append('\n');
}
out.print(sb);
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(Reader in) {
br = new BufferedReader(in);
}
public FastScanner(InputStream in) {
this(new InputStreamReader(in));
}
public String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | e8d5bba475993385f5631f642640fc25 | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes | import java.io.*;
import java.util.*;
public class B implements Runnable{
public static void main (String[] args) {new Thread(null, new B(), "_cf", 1 << 28).start();}
public void run() {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
System.err.println("Go!");
int m = fs.nextInt();
int n = 4;
int k = fs.nextInt();
char[][] res = new char[n][m];
for(int i = 0; i < n; i++) Arrays.fill(res[i], '.');
if(k % 2 == 1) { res[1][m / 2] = '#'; k--; }
if(m == 3) {
if(k == 2) res[1][m / 2] = res[2][m / 2] = '#';
else if(k == 1) res[1][m / 2] = '#';
}
for(int j = 1; j < 3 && k > 0 && m > 3; j++) {
for(int i = 1; i < m / 2 && k > 0; i++) {
res[j][i] = res[j][m - i - 1] = '#';
k -= 2;
}
}
if(k > 0) {
k--;
res[1][m / 2] = '#';
if(k > 0) res[2][m / 2] = '#';
}
out.println("YES");
for(int i = 0; i < n; i++) out.println(new String(res[i]));
out.close();
}
void fini(char[][] t1) {
System.out.println("YES");
for(int i = 0; i < 4; i++) {
System.out.println(new String(t1[i]));
}
System.exit(0);
}
void sort (int[] a) {
int n = a.length;
for(int i = 0; i < 50; i++) {
Random r = new Random();
int x = r.nextInt(n), y = r.nextInt(n);
int temp = a[x];
a[x] = a[y];
a[y] = temp;
}
Arrays.sort(a);
}
class FastScanner {
public int BS = 1<<16;
public char NC = (char)0;
byte[] buf = new byte[BS];
int bId = 0, size = 0;
char c = NC;
double num = 1;
BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) throws FileNotFoundException {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
public char nextChar(){
while(bId==size) {
try {
size = in.read(buf);
}catch(Exception e) {
return NC;
}
if(size==-1)return NC;
bId=0;
}
return (char)buf[bId++];
}
public int nextInt() {
return (int)nextLong();
}
public long nextLong() {
num=1;
boolean neg = false;
if(c==NC)c=nextChar();
for(;(c<'0' || c>'9'); c = nextChar()) {
if(c=='-')neg=true;
}
long res = 0;
for(; c>='0' && c <='9'; c=nextChar()) {
res = (res<<3)+(res<<1)+c-'0';
num*=10;
}
return neg?-res:res;
}
public double nextDouble() {
double cur = nextLong();
return c!='.' ? cur:cur+nextLong()/num;
}
public String next() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c>32) {
res.append(c);
c=nextChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c!='\n') {
res.append(c);
c=nextChar();
}
return res.toString();
}
public boolean hasNext() {
if(c>32)return true;
while(true) {
c=nextChar();
if(c==NC)return false;
else if(c>32)return true;
}
}
public int[] nextIntArray(int n) {
int[] res = new int[n];
for(int i = 0; i < n; i++) res[i] = nextInt();
return res;
}
}
} | Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | ffa8e9ee3dd775d5b2ea10ed10c7572b | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 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 k = sc.nextInt();
System.out.println("YES");
char[][] city = new char[4][n];
for(int i=0; i<4; i++)
for(int j=0; j<n; j++)
city[i][j] = '.';
if ( k % 2 == 0 ){
for(int i=1; i<k/2+1; i++){
city[1][i] = '#';
city[2][i] = '#';
}
} else{
if ( k == 3 ){
city[1][1] = '#';
city[2][1] = '#';
city[1][(n-2)/2+2] = '#';
} else if ( k == 1 ){
city[1][n/2] = '#';
} else{
int i = 1;
while ( i < k/2){
city[1][i] = '#';
city[2][i] = '#';
i++;
}
city[1][i]='#';
city[1][i+1]='#';
city[2][i+1]='#';
}
}
for(int i=0; i<4; i++)
System.out.println(city[i]);
}
}
| Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | 7d9537ac0ce385228f1de54fed1a3b57 | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.awt.Point;
public class Main {
//static final long MOD = 998244353L;
//static final long INF = -1000000000000000007L;
static final long MOD = 1000000007L;
//static final int INF = 1000000007;
public static void main(String[] args) {
FastScanner sc = new FastScanner();
PrintWriter pw = new PrintWriter(System.out);
int N = sc.ni();
int K = sc.ni();
char[][] grid = new char[4][N];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < N; j++)
grid[i][j] = '.';
}
if (K % 2 == 0) {
for (int j = 1; j <= K/2; j++) {
grid[1][j] = '#';
grid[2][j] = '#';
}
} else {
for (int j = Math.max(N/2-K/2,1); j <= Math.min(N/2+K/2,N-2); j++) {
grid[1][j] = '#';
}
K -= (N-2);
if (K > 0) {
for (int j = 1; j <= K/2; j++)
grid[2][j] = '#';
for (int j = 1; j <= K/2; j++)
grid[2][N-1-j] = '#';
}
}
pw.println("YES");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < N; j++) {
pw.print(grid[i][j]);
}
pw.println();
}
pw.close();
}
public static int[][] sort(int[][] array) {
//Sort an array (immune to quicksort TLE)
Random rgen = new Random();
for (int i = 0; i < array.length; i++) {
int randomPosition = rgen.nextInt(array.length);
int[] temp = array[i];
array[i] = array[randomPosition];
array[randomPosition] = temp;
}
Arrays.sort(array, new Comparator<int[]>() {
@Override
public int compare(int[] arr1, int[] arr2) {
//return arr1[0]-arr2[0]; //ascending order
if (arr1[0] != arr2[0]) {
return arr1[0]-arr2[0];
} else {
return arr1[1]-arr2[1];
}
}
});
return array;
}
public static long[][] sort(long[][] array) {
//Sort an array (immune to quicksort TLE)
Random rgen = new Random();
for (int i = 0; i < array.length; i++) {
int randomPosition = rgen.nextInt(array.length);
long[] temp = array[i];
array[i] = array[randomPosition];
array[randomPosition] = temp;
}
Arrays.sort(array, new Comparator<long[]>() {
@Override
public int compare(long[] arr1, long[] arr2) {
return 0;
}
});
return array;
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int ni() {
return Integer.parseInt(next());
}
long nl() {
return Long.parseLong(next());
}
double nd() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | d5fc44ff91607c24b9d20e526745d54b | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes | import java.lang.*;
import java.io.*;
import java.util.*;
import java.math.*;
import java.net.*;
import static java.lang.Math.*;
public class Solution implements Runnable {
void solve() throws Exception {
int n = sc.nextInt();
int k = sc.nextInt();
out.println("YES");
char[][] c = new char[4][n];
for (int i = 0; i < 4; i++) {
Arrays.fill(c[i], '.');
}
for (int l = 1, r = n - 2; l <= r && k > 0; l++, r--) {
if (k > 1 && l != r) {
c[1][l] = '#';
c[1][r] = '#';
k -= 2;
} else if (l == r) {
c[1][l] = '#';
--k;
}
}
for (int l = 1, r = n - 2; l <= r && k > 0; l++, r--) {
if (k > 1 && l != r) {
c[2][l] = '#';
c[2][r] = '#';
k -= 2;
} else if (l == r) {
c[2][l] = '#';
--k;
}
}
for (int i = 0; i < 4; i++) {
out.println(new String(c[i]));
}
}
BufferedReader in;
PrintWriter out;
FastScanner sc;
final String INPUT_FILE = "";
final String OUTPUT_FILE = "";
static Throwable throwable;
public static void main(String[] args) throws Throwable {
Thread thread = new Thread(null, new Solution(), "", (1 << 26));
thread.start();
thread.join();
thread.run();
if (Solution.throwable != null)
throw Solution.throwable;
}
public void run() {
try {
if (INPUT_FILE.equals("")) {
in = new BufferedReader(new InputStreamReader(System.in));
} else {
in = new BufferedReader(new FileReader(INPUT_FILE));
}
if (OUTPUT_FILE.equals("")) {
out = new PrintWriter(System.out);
} else {
out = new PrintWriter(OUTPUT_FILE);
}
sc = new FastScanner(in);
solve();
} catch (Exception e) {
throwable = e;
} finally {
out.close();
}
}
}
class FastScanner {
BufferedReader reader;
StringTokenizer strTok;
FastScanner(BufferedReader reader) {
this.reader = reader;
}
public String nextToken() throws Exception {
while (strTok == null || !strTok.hasMoreTokens()) {
strTok = new StringTokenizer(reader.readLine());
}
return strTok.nextToken();
}
public int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
public double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
public long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
} | Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | 93f77c78b16f5a490c28cf4374a566d1 | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes | import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Map.Entry;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class B {
public static void main(String[] args) throws IOException {
try (Scanner sc = new Scanner(System.in)) {
final int n = sc.nextInt();
int k = sc.nextInt();
boolean[][] map = new boolean[4][n];
if(k % 2 == 0) {
for(int j = 1; j < n - 1 && k > 0; j++) {
map[1][j] = map[2][j] = true;
k -= 2;
}
}else if(k % 2 != 0){
if(k >= 1) { map[1][n / 2] = true; k--; }
for(int j = 1; j < (n / 2) && k > 0; j++) {
map[1][n / 2 - j] = true; k--;
map[1][n / 2 + j] = true; k--;
}
if(k >= 2) {
if(n - 2 == 1) {
map[2][1] = map[2][n - 2] = true; k -= 1;
}else {
map[2][1] = map[2][n - 2] = true; k -= 2;
}
for(int j = 2; j < n - 2 && k > 0; j++) {
map[2][j] = true; k--;
}
}
}
if(k == 0) {
System.out.println("YES");
for(int i = 0; i < 4; i++) {
for(int j = 0; j < n; j++) {
System.out.print(map[i][j] ? "#" : ".");
}
System.out.println();
}
}else {
System.out.println("NO");
}
}
}
public static class Scanner implements Closeable {
private BufferedReader br;
private StringTokenizer tok;
public Scanner(InputStream is) throws IOException {
br = new BufferedReader(new InputStreamReader(is));
}
private void getLine() throws IOException {
while (!hasNext()) {
tok = new StringTokenizer(br.readLine());
}
}
private boolean hasNext() {
return tok != null && tok.hasMoreTokens();
}
public String next() throws IOException {
getLine();
return tok.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public int[] nextIntArray(int n) throws IOException {
final int[] ret = new int[n];
for (int i = 0; i < n; i++) {
ret[i] = this.nextInt();
}
return ret;
}
public long[] nextLongArray(int n) throws IOException {
final long[] ret = new long[n];
for (int i = 0; i < n; i++) {
ret[i] = this.nextLong();
}
return ret;
}
public void close() throws IOException {
br.close();
}
}
} | Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | 5ef99d36a9006581d9d6e6be6fffa2b8 | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes | import java.util.*;
public class Main {
static void debug(Object... O) {
System.out.println(Arrays.deepToString(O));
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
StringBuilder sb = new StringBuilder();
char[][] F = new char[4][n];
for(int i=0;i<4;i++) {
Arrays.fill(F[i], '.');
}
boolean ans = true;
int mid = n/2;
int left = mid-1,right=mid+1;
boolean first = true, second = true;
while(k > 0) {
if(first && left > 0 && k >= 2) {
F[1][left] = '#';
F[1][right] = '#';
left--;
right++;
k-=2;
//System.out.println("up k "+k);
if(left == 0) {
first = false;
left = mid-1;
right=mid+1;
}
}else if(!first && second && left > 0 && k>=2) {
F[2][left] = '#';
F[2][right] = '#';
left--;
right++;
k-=2;
//System.out.println("down k "+k);
if(left == 0 && k >2) {
ans = false;
break;
}else if(left == 0) {
second = false;
}
}else if(k == 1) {
F[1][mid] ='#';
k--;
}else if(k == 2) {
F[1][mid] = '#';
F[2][mid] = '#';
k-=2;
}
}
if(ans) {
System.out.println("YES");
for(int i=0;i<4;i++) {
for(int j=0;j<n;j++) {
sb.append(F[i][j]);
}
sb.append("\n");
}
System.out.println(sb.toString());
}else {
System.out.println("NO");
}
}
}
| Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | 90312461790dd09cec3dda023395bfb5 | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class CFA {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
private static final long MOD = 1000L * 1000L * 1000L + 7;
private static final int[] dx = {0, -1, 0, 1};
private static final int[] dy = {1, 0, -1, 0};
private static final String yes = "Yes";
private static final String no = "No";
void solve() throws IOException {
int n = nextInt();
int k = nextInt();
char[][] res = new char[4][n];
for (int i = 0; i < 4; i++) {
Arrays.fill(res[i], '.');
}
outln(yes.toUpperCase());
if (k % 2 == 0) {
for (int i = 1; i < 3; i++) {
for (int j = 1; j <= k / 2; j++) {
res[i][j] = '#';
}
}
}
else {
if (k <= n - 2) {
res[1][n / 2] = '#';
for (int i = n / 2 - k / 2; i <= n / 2 + k / 2; i++) {
res[1][i] = '#';
}
}
else {
for (int i = 1; i < 3; i++) {
for (int j = 1; j < n - 1; j++) {
res[i][j] = '#';
}
}
k = 2 * (n - 2) - k;
for (int i = n / 2 - k / 2; i <= n / 2 + k / 2; i++) {
res[2][i] = '.';
}
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < n; j++) {
out(res[i][j]);
}
outln("");
}
}
void shuffle(int[] a) {
int n = a.length;
for(int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int tmp = a[i];
a[i] = a[r];
a[r] = tmp;
}
}
long gcd(long a, long b) {
while(a != 0 && b != 0) {
long c = b;
b = a % b;
a = c;
}
return a + b;
}
private void outln(Object o) {
out.println(o);
}
private void out(Object o) {
out.print(o);
}
public CFA() 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 CFA();
}
public long[] nextLongArr(int n) throws IOException{
long[] res = new long[n];
for(int i = 0; i < n; i++)
res[i] = nextLong();
return res;
}
public int[] nextIntArr(int n) throws IOException {
int[] res = new int[n];
for(int i = 0; i < n; i++)
res[i] = nextInt();
return res;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return null;
}
}
return st.nextToken();
}
public String nextString() {
try {
return br.readLine();
} catch (IOException e) {
eof = true;
return null;
}
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
} | Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | 35aa3aa93ff07be43348732c96b52ab9 | train_004.jsonl | 1470933300 | Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically. | 256 megabytes | import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class C {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int[] cost = na(n);
String[][] ss = new String[n][2];
for(int i = 0;i < n;i++){
String s = ns();
String rs = new String(rev(s.toCharArray()));
ss[i][0] = s;
ss[i][1] = rs;
}
long[][] dp = new long[n][2];
for(int i = 0;i < n;i++){
Arrays.fill(dp[i], Long.MAX_VALUE / 10);
}
dp[0][0] = 0;
dp[0][1] = cost[0];
for(int i = 0;i < n-1;i++){
for(int j = 0;j < 2;j++){
for(int k = 0;k < 2;k++){
if(ss[i][j].compareTo(ss[i+1][k]) <= 0){
dp[i+1][k] = Math.min(dp[i+1][k], dp[i][j] + (k == 1 ? cost[i+1] : 0));
}
}
}
}
long ret = Math.min(dp[n-1][0], dp[n-1][1]);
if(ret >= Long.MAX_VALUE / 10){
out.println(-1);
}else{
out.println(ret);
}
}
public static char[] rev(char[] a)
{
for(int i = 0, j = a.length-1;i < j;i++,j--){
char c = a[i]; a[i] = a[j]; a[j] = c;
}
return a;
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new C().run(); }
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
} | Java | ["2\n1 2\nba\nac", "3\n1 3 1\naa\nba\nac", "2\n5 5\nbbb\naaa", "2\n3 3\naaa\naa"] | 1 second | ["1", "1", "-1", "-1"] | NoteIn the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is - 1.In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is - 1. | Java 11 | standard input | [
"dp",
"strings"
] | 91cfd24b8d608eb379f709f4509ecd2d | The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of strings. The second line contains n integers ci (0 ≤ ci ≤ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string. Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000. | 1,600 | If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent. | standard output | |
PASSED | 421aed181c4a6272e21eca17c6f1349c | train_004.jsonl | 1470933300 | Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically. | 256 megabytes |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class TaskC {
static Long[][]dp;
static int n, m, ans;
static StringBuilder[]s1,s2;
static int[]arr;
static long dp(int isRev ,int idx)
{
if(idx == n)return 0;
if(dp[isRev][idx]!=null) return dp[isRev][idx];
long rev = (long)1e15;
long notRev = (long)1e15;
if(idx == 0)
{
rev = (1l* arr[idx]) + dp(1 , idx + 1);
notRev = dp(0 , idx + 1);
}else{
if(isRev == 1)
{
if(s1[idx].compareTo(s2[idx - 1]) >= 0)
{
notRev = dp(0 , idx + 1);
}
if(s2[idx].compareTo(s2[idx - 1]) >= 0){
rev = 1l*arr[idx] + dp(1 ,idx + 1);
}
}else{
//System.out.println(s1[idx].compareTo(s1[idx - 1])+ " "+s1[idx] + " "+s2[idx - 1]);
if(s1[idx].compareTo(s1[idx - 1]) >= 0)
{
notRev = dp(0 , idx + 1);
}
if(s2[idx].compareTo(s1[idx - 1]) >= 0){
rev = 1l*arr[idx] + dp(1 ,idx + 1);
}
}
}
return dp[isRev][idx] = Math.min(rev , notRev);
}
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
n = sc.nextInt();
arr = new int[n];
s1 = new StringBuilder[n];
s2 = new StringBuilder[n];
for (int i = 0 ; i < n ; i ++)
arr[i] = sc.nextInt();
for (int i = 0 ; i < n ; i ++)
{
StringBuilder a = new StringBuilder(sc.nextLine());
StringBuilder b = new StringBuilder(a);
s1[i] = a;
s2[i] = b.reverse();
}
dp = new Long[2][n + 1];
long ans = dp(0 , 0);
if(ans >= (long) 1e15)
pw.print(-1);
else
pw.print(ans);
pw.close();
}
private static long gcd(long a, long b) {
if( b == 0)
return a;
return gcd(b , a%b);
}
static long lcm(int a, int b)
{
return (a*b)/gcd(a, b);
}
private static int dis(int xa , int ya , int xb , int yb)
{
return (xa-xb)*(xa - xb) + (ya- yb)*(ya-yb);
}
static class Pair implements Comparable<Pair> {
int x,y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
public int compareTo(Pair o) {
if (y == o.y)
return o.x - x;
return y - o.y;
}
public double dis(Pair a){
return (a.x - x)*(a.x - x) + (a.y-y)*(a.y-y);
}
public String toString() {
return x+" "+ y;
}
public boolean overlap(Pair a)
{
if((this.x >= a.x && this.x <= a.y) || (a.x >= this.x && a.x <= this.y)) return true;
return false;
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
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 boolean check() {
if (!st.hasMoreTokens())
return false;
return true;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public double nextDouble() {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() {
try {
return br.ready();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
} | Java | ["2\n1 2\nba\nac", "3\n1 3 1\naa\nba\nac", "2\n5 5\nbbb\naaa", "2\n3 3\naaa\naa"] | 1 second | ["1", "1", "-1", "-1"] | NoteIn the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is - 1.In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is - 1. | Java 11 | standard input | [
"dp",
"strings"
] | 91cfd24b8d608eb379f709f4509ecd2d | The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of strings. The second line contains n integers ci (0 ≤ ci ≤ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string. Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000. | 1,600 | If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent. | standard output | |
PASSED | a8a1acbef04b0fff7c968e5732a3d8fa | train_004.jsonl | 1470933300 | Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically. | 256 megabytes | import java.io.*;
import java.util.*;
/**
* Problem statement here: http://codeforces.com/problemset/problem/706/C
*
* Good luck. This one's a hard problem!
*/
public class FindTheBug6 {
private static int n;
private static int[] energy;
private static String[] words;
private static String[] reversed;
// dp[k][0] is minimum energy needed to store words from k to the end
// dp[k][1] is minimum energy needed to store words from k to the end with words[k] reversed.
private static long[][] dp;
private static void readInput() {
Scanner scan = new Scanner(System.in);
n = scan.nextInt();
energy = new int[n];
words = new String[n];
reversed = new String[n];
for (int i = 0; i < n; i++) {
energy[i] = scan.nextInt();
}
for (int i = 0; i < n; i++) {
words[i] = scan.next();
reversed[i] = new StringBuilder(words[i]).reverse().toString();
}
}
public static void main(String[] args) {
readInput();
dp = new long[n][2];
// Initialize dp to all -1
for (long[] row : dp) {
Arrays.fill(row, -1);
}
// Base case
dp[n - 1][0] = 0;
dp[n - 1][1] = energy[n - 1];
// For every index, for every possible flip of the last two
for (int i = n - 2; i >= 0; i--) {
for (int k = 0; k < 2; k++) {
for (int l = 0; l < 2; l++) {
String cur = k > 0 ? reversed[i] : words[i];
String next = l > 0 ? reversed[i + 1] : words[i + 1];
// cur <= next
if (cur.compareTo(next) <= 0 && dp[i + 1][l] != -1) {
long cost = dp[i + 1][l] + (k > 0 ? energy[i] : 0);
dp[i][k] = dp[i][k] == -1 ? cost : Math.min(dp[i][k], cost);
}
}
}
}
if (dp[0][0] == -1) {
System.out.println(dp[0][1]);
} else if (dp[0][1] == -1) {
System.out.println(dp[0][0]);
} else {
System.out.println(Math.min(dp[0][0], dp[0][1]));
}
}
}
| Java | ["2\n1 2\nba\nac", "3\n1 3 1\naa\nba\nac", "2\n5 5\nbbb\naaa", "2\n3 3\naaa\naa"] | 1 second | ["1", "1", "-1", "-1"] | NoteIn the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is - 1.In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is - 1. | Java 11 | standard input | [
"dp",
"strings"
] | 91cfd24b8d608eb379f709f4509ecd2d | The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of strings. The second line contains n integers ci (0 ≤ ci ≤ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string. Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000. | 1,600 | If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent. | standard output | |
PASSED | 63a4284d1f6ed714896b31b1edab441f | train_004.jsonl | 1470933300 | Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically. | 256 megabytes | import java.io.*;
import java.util.*;
/**
* Problem statement here: http://codeforces.com/problemset/problem/706/C
*
* Good luck. This one's a hard problem!
*/
public class FindTheBug6 {
private static int n;
private static int[] energy;
private static String[] words;
private static String[] reversed;
// dp[k][0] is minimum energy needed to store words from k to the end
// dp[k][1] is minimum energy needed to store words from k to the end with words[k] reversed.
private static long[][] dp;
private static void readInput() {
Scanner scan = new Scanner(System.in);
n = scan.nextInt();
energy = new int[n];
words = new String[n];
reversed = new String[n];
for (int i = 0; i < n; i++) {
energy[i] = scan.nextInt();
}
for (int i = 0; i < n; i++) {
words[i] = scan.next();
reversed[i] = new StringBuilder(words[i]).reverse().toString();
}
}
public static void print(long[][] dp) {
for(int a = 0; a < dp.length; a++) {
for(int b = 0; b < dp[a].length; b++) {
System.out.print(dp[a][b] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
readInput();
dp = new long[n][2];
// Initialize dp to all -1
for (long[] row : dp) {
Arrays.fill(row, Long.MAX_VALUE);
}
// Base case
dp[n - 1][0] = 0;
dp[n - 1][1] = energy[n - 1];
// For every index, for every possible flip of the last two
for (int i = n - 2; i >= 0; i--) {
for (int k = 0; k < 2; k++) {
for (int l = 0; l < 2; l++) {
String cur = k > 0 ? reversed[i] : words[i];
String next = l > 0 ? reversed[i + 1] : words[i + 1];
// cur <= next
if (cur.compareTo(next) <= 0) {
long cost = dp[i+1][l] == Long.MAX_VALUE ? Long.MAX_VALUE : dp[i + 1][l] + (k > 0 ? energy[i] : 0);
dp[i][k] = dp[i][k] == Long.MAX_VALUE ? cost : Math.min(dp[i][k], cost);
}
//System.out.println("cur: " + cur + " next: " + next);
//print(dp);
}
}
}
if (dp[0][0] == Long.MAX_VALUE && dp[0][1] == Long.MAX_VALUE) {
System.out.println(-1);
} else {
System.out.println(Math.min(dp[0][0], dp[0][1]));
}
}
}
| Java | ["2\n1 2\nba\nac", "3\n1 3 1\naa\nba\nac", "2\n5 5\nbbb\naaa", "2\n3 3\naaa\naa"] | 1 second | ["1", "1", "-1", "-1"] | NoteIn the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is - 1.In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is - 1. | Java 11 | standard input | [
"dp",
"strings"
] | 91cfd24b8d608eb379f709f4509ecd2d | The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of strings. The second line contains n integers ci (0 ≤ ci ≤ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string. Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000. | 1,600 | If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent. | standard output | |
PASSED | 3f2b9e82ba924345f32dce05e2ededb3 | train_004.jsonl | 1470933300 | Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically. | 256 megabytes | import java.io.*;
import java.util.*;
/**
* Problem statement here: http://codeforces.com/problemset/problem/706/C
*
* Good luck. This one's a hard problem!
*/
public class FindTheBug6 {
private static int n;
private static int[] energy;
private static String[] words;
private static String[] reversed;
// dp[k][0] is minimum energy needed to store words from k to the end
// dp[k][1] is minimum energy needed to store words from k to the end with words[k] reversed.
private static long[][] dp;
private static void readInput() {
Scanner scan = new Scanner(System.in);
n = scan.nextInt();
energy = new int[n];
words = new String[n];
reversed = new String[n];
for (int i = 0; i < n; i++) {
energy[i] = scan.nextInt();
}
for (int i = 0; i < n; i++) {
words[i] = scan.next();
reversed[i] = new StringBuilder(words[i]).reverse().toString();
}
}
public static void print(long[][] dp) {
for(int a = 0; a < dp.length; a++) {
for(int b = 0; b < dp[a].length; b++) {
System.out.print(dp[a][b] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
readInput();
dp = new long[n][2];
// Initialize dp to all -1
for (long[] row : dp) {
Arrays.fill(row, Long.MAX_VALUE);
}
// Base case
dp[n - 1][0] = 0;
dp[n - 1][1] = energy[n - 1];
// For every index, for every possible flip of the last two
for (int i = n - 2; i >= 0; i--) {
for (int k = 0; k < 2; k++) {
for (int l = 0; l < 2; l++) {
String cur = k > 0 ? reversed[i] : words[i];
String next = l > 0 ? reversed[i + 1] : words[i + 1];
// cur <= next
if (cur.compareTo(next) <= 0) {
long cost = dp[i+1][l] == Long.MAX_VALUE ? Long.MAX_VALUE : dp[i + 1][l] + (k > 0 ? energy[i] : 0);
dp[i][k] = dp[i][k] == Long.MAX_VALUE ? cost : Math.min(dp[i][k], cost);
}
//System.out.println("cur: " + cur + " next: " + next);
//print(dp);
}
}
}
if (dp[0][0] == Long.MAX_VALUE && dp[0][1] == Long.MAX_VALUE) {
System.out.println(-1);
} else if(dp[0][0] == Long.MAX_VALUE){
System.out.println(dp[0][1]);
} else if (dp[0][1] == Long.MAX_VALUE) {
System.out.println(dp[0][0]);
} else {
System.out.println(Math.min(dp[0][0], dp[0][1]));
}
}
}
| Java | ["2\n1 2\nba\nac", "3\n1 3 1\naa\nba\nac", "2\n5 5\nbbb\naaa", "2\n3 3\naaa\naa"] | 1 second | ["1", "1", "-1", "-1"] | NoteIn the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is - 1.In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is - 1. | Java 11 | standard input | [
"dp",
"strings"
] | 91cfd24b8d608eb379f709f4509ecd2d | The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of strings. The second line contains n integers ci (0 ≤ ci ≤ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string. Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000. | 1,600 | If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent. | standard output | |
PASSED | 8912858eac601fca960c92fb85c7bd45 | train_004.jsonl | 1470933300 | Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically. | 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
{
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(b.readLine());
long[] c = new long[n];
String[] temp = b.readLine().split(" ");
String[] strs = new String[n];
for (int i = 0; i < n; i++) {
strs[i] = b.readLine();
c[i] = Long.parseLong(temp[i]);
}
// Ideone m = new Ideone();
System.out.println(mininum(strs, c, n));
}
static public String reverse(String s) {
return new StringBuilder(s).reverse().toString();
}
static public long mininum(String[] strs, long[] c, int n) {
long[][] dp = new long[n+1][2];
dp[0][0] = 0; dp[0][1] = c[0];
for (int i = 1; i < n; i++) {
dp[i][0] = Long.MAX_VALUE/2;
dp[i][1] = Long.MAX_VALUE/2;
if (strs[i-1].compareTo(strs[i]) <= 0)
dp[i][0] = Math.min(dp[i][0], dp[i-1][0]); // strs[i] not reversed, strs[i-1] not reversed
if (reverse(strs[i-1]).compareTo(strs[i]) <= 0)
dp[i][0] = Math.min(dp[i][0], dp[i-1][1]); // strs[i] not reversed, strs[i-1] reversed
if (strs[i-1].compareTo(reverse(strs[i])) <= 0)
dp[i][1] = Math.min(dp[i][1], dp[i-1][0] + c[i]); // strs[i] reversed, strs[i-1] not reversed
if (reverse(strs[i-1]).compareTo(reverse(strs[i])) <= 0)
dp[i][1] = Math.min(dp[i][1], dp[i-1][1] + c[i]); // strs[i] reversed, strs[i-1] reversed
}
long res = Math.min(dp[n-1][0], dp[n-1][1]);
if (res < Long.MAX_VALUE/2)
return res;
else
return -1;
}
} | Java | ["2\n1 2\nba\nac", "3\n1 3 1\naa\nba\nac", "2\n5 5\nbbb\naaa", "2\n3 3\naaa\naa"] | 1 second | ["1", "1", "-1", "-1"] | NoteIn the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is - 1.In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is - 1. | Java 11 | standard input | [
"dp",
"strings"
] | 91cfd24b8d608eb379f709f4509ecd2d | The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of strings. The second line contains n integers ci (0 ≤ ci ≤ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string. Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000. | 1,600 | If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent. | standard output | |
PASSED | eac06bccf25cf6ad0d4c1acc6668a0fe | train_004.jsonl | 1470933300 | Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically. | 256 megabytes | import java.io.*;
import java.util.*;
import java.lang.Math;
public class dp {
public static void main (String [] args) throws IOException {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int N = Integer.parseInt(f.readLine());
StringTokenizer s = new StringTokenizer(f.readLine());
int[] array = new int[N];
for(int i = 0; i < N; i++){
array[i] = Integer.parseInt(s.nextToken());
}
String[] str = new String[N];
for(int i = 0; i < N; i++){
str[i] = f.readLine();
}
long[][] dp = new long[N][2];
for(int i = 1; i < N; i++){
dp[i][0] = 10000000000000000L;
dp[i][1] = 10000000000000000L;
}
dp[0][0] = 0;
dp[0][1] = array[0];
for(int i = 1; i < N; i++){
// do not reverse
if(str[i].compareTo(str[i-1]) >= 0){
dp[i][0] = Math.min(dp[i][0], dp[i-1][0]);
}
if(str[i].compareTo(reverse1(str[i-1])) >= 0){
dp[i][0] = Math.min(dp[i][0], dp[i-1][1]);
}
boolean flag = false;
if(reverse1(str[i]).compareTo(str[i-1]) >= 0){
dp[i][1] = Math.min(dp[i][1], dp[i-1][0]);
flag = true;
}
if(reverse1(str[i]).compareTo(reverse1(str[i-1])) >= 0){
dp[i][1] = Math.min(dp[i][1], dp[i-1][1]);
flag = true;
}
if(flag){
dp[i][1] += array[i];
}
}
long aaa = Math.min(dp[N - 1][0], dp[N - 1][1]);
if(aaa == 10000000000000000L){
out.println(-1);
}else{
out.println(aaa);
}
out.close();
}
public static String reverse1(String str){
return new StringBuffer(str).reverse().toString();
}
}
| Java | ["2\n1 2\nba\nac", "3\n1 3 1\naa\nba\nac", "2\n5 5\nbbb\naaa", "2\n3 3\naaa\naa"] | 1 second | ["1", "1", "-1", "-1"] | NoteIn the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is - 1.In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is - 1. | Java 11 | standard input | [
"dp",
"strings"
] | 91cfd24b8d608eb379f709f4509ecd2d | The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of strings. The second line contains n integers ci (0 ≤ ci ≤ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string. Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000. | 1,600 | If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent. | standard output | |
PASSED | c218285b5545527943f72e1a32dd7a2e | train_004.jsonl | 1470933300 | Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically. | 256 megabytes | //package com.company;
import java.util.*;
import java.io.IOException;
public class Main {
public static void main(String args[]) throws IOException {
Scanner in = new Scanner(System.in);
// int t = in.nextInt();
int t=1;
for (int jay = 0; jay < t; jay++) {
int n = in.nextInt();
int[] arr = new int[n];
long sum = 0;
for(int i=0;i<n;i++){
arr[i] = in.nextInt();
sum+=arr[i];
}
String[] s = new String[n];
for(int i=0;i<n;i++){
s[i] = in.next();
}
long[][] dp = new long[n][2];
for(long[] d:dp) Arrays.fill(d,sum+1);
dp[0][0] = 0;
dp[0][1] = arr[0];
for(int i=1;i<n;i++){
if(s[i-1].compareTo(s[i])<=0){
dp[i][0] = Math.min(dp[i-1][0],dp[i][0]);
}
if( rev(s[i-1]).compareTo(s[i])<=0 ){
dp[i][0] = Math.min(dp[i][0],dp[i-1][1]);
}
if( s[i-1].compareTo(rev(s[i]))<=0){
dp[i][1] = Math.min(dp[i-1][0]+arr[i],dp[i][1]);
}
if( rev(s[i-1]).compareTo(rev(s[i]))<=0 ){
dp[i][1] = Math.min(dp[i][1],dp[i-1][1]+arr[i]);
}
}
long ans = Math.min(dp[n-1][0],dp[n-1][1]);
if(ans==sum+1){
System.out.println(-1);
} else System.out.println(ans);
}
}
private static String rev(String s){
return new StringBuffer(s).reverse().toString();
}
private static boolean isPrime(double n) {
// no two power
double x = Math.sqrt(n);
int i=3;
int c=0;
while(i<=x){
if(n%i==0) c+=1;
if(c>=1) return false;
i+=2;
}
if(c==0) return true;
return false;
}
public static void showArr(int[] arr){
int n=arr.length;
for(int i=0;i<n;i++){
System.out.print(arr[i]+" ");
}
}
public static long gcd(long x, long y) {
if (x == 0)
return y;
return gcd(y % x, x);
}
public static boolean twoPow (long n)
{
return n!=0 && ((n&(n-1)) == 0);
}
} | Java | ["2\n1 2\nba\nac", "3\n1 3 1\naa\nba\nac", "2\n5 5\nbbb\naaa", "2\n3 3\naaa\naa"] | 1 second | ["1", "1", "-1", "-1"] | NoteIn the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is - 1.In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is - 1. | Java 11 | standard input | [
"dp",
"strings"
] | 91cfd24b8d608eb379f709f4509ecd2d | The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of strings. The second line contains n integers ci (0 ≤ ci ≤ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string. Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000. | 1,600 | If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent. | standard output | |
PASSED | 0abef6daefe3853d9273f3a4d78a8e41 | train_004.jsonl | 1470933300 | Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically. | 256 megabytes |
import java.io.*;
import java.util.*;
import java.math.*;
public class Main_ut {
InputStream is;
PrintWriter out;
long mod = (long) (1e9 + 7), inf = (long) (3e18);
boolean isV(String a, String b) {
int n = Math.min(a.length(), b.length());
for (int i = 0; i < n; i++) {
char ac = a.charAt(i);
char bc = b.charAt(i);
if (ac < bc)
return true;
if (ac > bc)
return false;
}
return a.length() <= b.length();
}
void solve() {
int n = ni();
long a[] = new long[n];
for (int i = 0; i < n; i++)
a[i] = nl();
String s[] = new String[n];
String rev[] = new String[n];
for (int i = 0; i < n; i++) {
s[i] = ns();
rev[i] = new StringBuilder(s[i]).reverse().toString();
}
long dp[][] = new long[n][2];
dp[0][0] = 0;
dp[0][1] = a[0];
for (int i = 1; i < n; i++) {
dp[i][0] = inf;
dp[i][1] = inf;
if (isV(s[i - 1], s[i]))
dp[i][0] = dp[i - 1][0];
if (isV(rev[i - 1], s[i]))
dp[i][0] = Math.min(dp[i][0], dp[i - 1][1]);
if (isV(s[i - 1], rev[i]))
dp[i][1] = Math.min(dp[i][1], dp[i - 1][0] + a[i]);
if (isV(rev[i - 1], rev[i]))
dp[i][1] = Math.min(dp[i][1], dp[i - 1][1] + a[i]);
}
long ans = Math.min(dp[n - 1][0], dp[n - 1][1]);
out.println(ans == inf ? -1 : ans);
}
long mp(long b, long e) {
long r = 1;
while (e > 0) {
if ((e & 1) == 1)
r = (r * b) % mod;
b = (b * b) % mod;
e >>= 1;
}
return r;
}
// ---------- I/O Template ----------
public static void main(String[] args) {
new Main_ut().run();
}
void run() {
is = System.in;
out = new PrintWriter(System.out);
solve();
out.flush();
}
byte input[] = new byte[1024];
int len = 0, ptr = 0;
int readByte() {
if (ptr >= len) {
ptr = 0;
try {
len = is.read(input);
} catch (IOException e) {
throw new InputMismatchException();
}
if (len <= 0) {
return -1;
}
}
return input[ptr++];
}
boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
int skip() {
int b = readByte();
while (b != -1 && isSpaceChar(b)) {
b = readByte();
}
return b;
}
char nc() {
return (char) skip();
}
String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
String nLine() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b) && b != ' ')) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
int ni() {
int n = 0, b = readByte();
boolean minus = false;
while (b != -1 && !((b >= '0' && b <= '9') || b == '-')) {
b = readByte();
}
if (b == '-') {
minus = true;
b = readByte();
}
if (b == -1) {
return -1;
} // no input
while (b >= '0' && b <= '9') {
n = n * 10 + (b - '0');
b = readByte();
}
return minus ? -n : n;
}
long nl() {
long n = 0L;
int b = readByte();
boolean minus = false;
while (b != -1 && !((b >= '0' && b <= '9') || b == '-')) {
b = readByte();
}
if (b == '-') {
minus = true;
b = readByte();
}
while (b >= '0' && b <= '9') {
n = n * 10 + (b - '0');
b = readByte();
}
return minus ? -n : n;
}
double nd() {
return Double.parseDouble(ns());
}
float nf() {
return Float.parseFloat(ns());
}
int[] na(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}
char[] ns(int n) {
char c[] = new char[n];
int i, b = skip();
for (i = 0; i < n; i++) {
if (isSpaceChar(b)) {
break;
}
c[i] = (char) b;
b = readByte();
}
return i == n ? c : Arrays.copyOf(c, i);
}
} | Java | ["2\n1 2\nba\nac", "3\n1 3 1\naa\nba\nac", "2\n5 5\nbbb\naaa", "2\n3 3\naaa\naa"] | 1 second | ["1", "1", "-1", "-1"] | NoteIn the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is - 1.In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is - 1. | Java 11 | standard input | [
"dp",
"strings"
] | 91cfd24b8d608eb379f709f4509ecd2d | The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of strings. The second line contains n integers ci (0 ≤ ci ≤ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string. Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000. | 1,600 | If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent. | standard output | |
PASSED | d6396a3ba1b3431c7f03fa9c1614c17d | train_004.jsonl | 1470933300 | Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically. | 256 megabytes | import java.io.*;
import java.util.*;
/**
* Problem statement here: http://codeforces.com/problemset/problem/706/C
*
* Good luck. This one's a hard problem!
*/
public class FindTheBug6 {
private static int n;
private static int[] energy;
private static String[] words;
private static String[] reversed;
// dp[k][0] is minimum energy needed to store words from k to the end
// dp[k][1] is minimum energy needed to store words from k to the end with words[k] reversed.
private static long[][] dp;
private static void readInput() {
Scanner scan = new Scanner(System.in);
n = scan.nextInt();
energy = new int[n];
words = new String[n];
reversed = new String[n];
for (int i = 0; i < n; i++) {
energy[i] = scan.nextInt();
}
for (int i = 0; i < n; i++) {
words[i] = scan.next();
reversed[i] = new StringBuilder(words[i]).reverse().toString();
}
}
public static void main(String[] args) {
readInput();
dp = new long[n][2];
// Initialize dp to all -1
for (long[] row : dp) {
Arrays.fill(row, -1);
}
// Base case
dp[n - 1][0] = 0;
dp[n - 1][1] = energy[n - 1];
// For every index, for every possible flip of the last two
for (int i = n - 2; i >= 0; i--) {
for (int k = 0; k < 2; k++) {
for (int l = 0; l < 2; l++) {
// printDP(dp);
// System.out.println("_________");
String cur = k > 0 ? reversed[i] : words[i];
String next = l > 0 ? reversed[i + 1] : words[i + 1];
// cur <= next
if (cur.compareTo(next) <= 0 && dp[i+1][l] != -1) {
long cost = dp[i + 1][l] + (k > 0 ? energy[i] : 0);
// System.out.println("cost is " + cost);
dp[i][k] = dp[i][k] == -1 ? cost : Math.min(dp[i][k], cost);
}
}
}
}
// printDP(dp);
// System.out.println("________");
if (dp[0][0] == -1) {
// System.out.println("test");
System.out.println(dp[0][1]);
} else if (dp[0][1] == -1) {
System.out.println(dp[0][0]);
} else {
System.out.println(Math.min(dp[0][0], dp[0][1]));
}
}
// static void printDP(long[][] arr) {
// for(int i = 0; i < arr.length; i++) {
// System.out.println(Arrays.toString(arr[i]));
// }
// }
}
| Java | ["2\n1 2\nba\nac", "3\n1 3 1\naa\nba\nac", "2\n5 5\nbbb\naaa", "2\n3 3\naaa\naa"] | 1 second | ["1", "1", "-1", "-1"] | NoteIn the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is - 1.In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is - 1. | Java 11 | standard input | [
"dp",
"strings"
] | 91cfd24b8d608eb379f709f4509ecd2d | The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of strings. The second line contains n integers ci (0 ≤ ci ≤ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string. Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000. | 1,600 | If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent. | standard output | |
PASSED | b4216745135349340a9022bf370bf81c | train_004.jsonl | 1470933300 | Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically. | 256 megabytes |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import static java.lang.Math.min;
public class Temp {
static List<String> strings;
static double[][] memo;
static int[] cost;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
memo = new double[n][2];
for (double[] arr : memo) {
Arrays.fill(arr, -1);
}
cost = new int[n];
for (int i = 0; i < n; i++) {
cost[i] = sc.nextInt();
}
strings = new ArrayList<>();
for (int i = 0; i < n; i++) {
String s = sc.next();
if (s.equals(new StringBuilder(s).reverse().toString())) cost[i] = 0;
strings.add(s);
}
double ans = min(get(0, 0), cost[0] + get(0, 1));
if (ans == Double.MAX_VALUE) ans = -1;
System.out.println((long) ans);
}
private static double get(int idx, int rev) {
if (memo[idx][rev] != -1) return memo[idx][rev];
else {
if (idx >= memo.length - 1) {
memo[idx][rev] = 0;
return 0;
} else {
String cur = strings.get(idx + 1);
String las;
if (rev == 1) {
las = (new StringBuilder(strings.get(idx)).reverse().toString());
} else {
las = strings.get(idx);
}
if (las.compareTo(cur) > 0 && las.compareTo((new StringBuilder(cur)).reverse().toString()) > 0) {
memo[idx][rev] = Double.MAX_VALUE;
return memo[idx][rev];
} else if (las.compareTo(cur) > 0) {
memo[idx][rev] = cost[idx + 1] + get(idx + 1, 1);
return memo[idx][rev];
} else if (las.compareTo((new StringBuilder(cur)).reverse().toString()) > 0) {
memo[idx][rev] = get(idx + 1, 0);
return memo[idx][rev];
} else {
memo[idx][rev] = min(get(idx + 1, 0), cost[idx + 1] + get(idx + 1, 1));
return memo[idx][rev];
}
}
}
}
}
| Java | ["2\n1 2\nba\nac", "3\n1 3 1\naa\nba\nac", "2\n5 5\nbbb\naaa", "2\n3 3\naaa\naa"] | 1 second | ["1", "1", "-1", "-1"] | NoteIn the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is - 1.In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is - 1. | Java 11 | standard input | [
"dp",
"strings"
] | 91cfd24b8d608eb379f709f4509ecd2d | The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of strings. The second line contains n integers ci (0 ≤ ci ≤ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string. Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000. | 1,600 | If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent. | standard output | |
PASSED | 4fb43b10520ccce5a5fe852686634162 | train_004.jsonl | 1470933300 | Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically. | 256 megabytes | import java.io.*;
import java.util.*;
/**
* Problem statement here: http://codeforces.com/problemset/problem/706/C
*
* Good luck. This one's a hard problem!
*/
public class FindTheBug6 {
private static int n;
private static int[] energy;
private static String[] words;
private static String[] reversed;
// dp[k][0] is minimum energy needed to store words from k to the end
// dp[k][1] is minimum energy needed to store words from k to the end with words[k] reversed.
private static long[][] dp;
private static void readInput() {
Scanner scan = new Scanner(System.in);
n = scan.nextInt();
energy = new int[n];
words = new String[n];
reversed = new String[n];
for (int i = 0; i < n; i++) {
energy[i] = scan.nextInt();
}
for (int i = 0; i < n; i++) {
words[i] = scan.next();
reversed[i] = new StringBuilder(words[i]).reverse().toString();
}
}
public static void main(String[] args) {
readInput();
dp = new long[n][2];
// Initialize dp to all -1
for (long[] row : dp) {
Arrays.fill(row, -1);
}
// Base case
dp[n - 1][0] = 0;
dp[n - 1][1] = energy[n - 1];
// For every index, for every possible flip of the last two
for (int i = n - 2; i >= 0; i--) {
for (int k = 0; k < 2; k++) {
for (int l = 0; l < 2; l++) {
String cur = k > 0 ? reversed[i] : words[i];
String next = l > 0 ? reversed[i + 1] : words[i + 1];
// cur <= next
if (cur.compareTo(next) <= 0 && dp[i + 1][l] != -1) {
long cost = dp[i + 1][l] + (k > 0 ? energy[i] : 0);
dp[i][k] = dp[i][k] == -1 ? cost : Math.min(dp[i][k], cost);
}
}
}
}
if (dp[0][0] == -1) {
System.out.println(dp[0][1]);
} else if (dp[0][1] == -1) {
System.out.println(dp[0][0]);
} else {
System.out.println(Math.min(dp[0][0], dp[0][1]));
}
}
}
| Java | ["2\n1 2\nba\nac", "3\n1 3 1\naa\nba\nac", "2\n5 5\nbbb\naaa", "2\n3 3\naaa\naa"] | 1 second | ["1", "1", "-1", "-1"] | NoteIn the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is - 1.In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is - 1. | Java 11 | standard input | [
"dp",
"strings"
] | 91cfd24b8d608eb379f709f4509ecd2d | The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of strings. The second line contains n integers ci (0 ≤ ci ≤ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string. Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000. | 1,600 | If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent. | standard output | |
PASSED | 4216ce3e785f174a3cf6b04538f86d43 | train_004.jsonl | 1470933300 | Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main{
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
public static void main(String sp[])throws IOException{
Scanner sc = new Scanner(System.in);
//FastReader sc = new FastReader();
int n = sc.nextInt();
long cost[] = new long[n];
for(int i=0;i<n;i++)
cost[i] = sc.nextLong();
ArrayList<String> org = new ArrayList<>();
ArrayList<String> rev = new ArrayList<>();
for(int i=0;i<n;i++){
String st = sc.next();
org.add(st);
rev.add(new StringBuilder(st).reverse().toString());
}
long dp[][] = new long[2][n];
boolean mark[][] = new boolean[2][n];
for(int i=0;i<2;i++){
for(int j=0;j<n;j++)
dp[i][j] = Long.MAX_VALUE;
}
dp[0][0] = 0;
dp[1][0] = cost[0];
mark[0][0] = true;
mark[1][0] = true;
for(int i=1;i<n;i++){
if(mark[0][i-1]==true){
if(com(org.get(i),org.get(i-1))==1){
dp[0][i] = dp[0][i-1];
mark[0][i] = true;
}
if(com(rev.get(i),org.get(i-1))==1){
dp[1][i] = dp[0][i-1]+cost[i];
mark[1][i] = true;
}
}
if(mark[1][i-1]==true){
if(com(org.get(i),rev.get(i-1))==1){
dp[0][i] = Math.min(dp[1][i-1] , dp[0][i]);
mark[0][i] = true;
}
if(com(rev.get(i),rev.get(i-1))==1){
dp[1][i] = Math.min(dp[1][i-1]+cost[i], dp[1][i]);
mark[1][i] = true;
}
}
if(mark[0][i]==false && mark[1][i]==false){
System.out.println("-1");
return;
}
}
long min = Long.MAX_VALUE;
if(mark[0][n-1]==true)
min = Math.min(min, dp[0][n-1]);
if(mark[1][n-1]==true)
min = Math.min(min, dp[1][n-1]);
System.out.println(min);
}
public static int com(String s1,String s2){
if(s1.equals(s2))
return 1;
else{
int res = s1.compareTo(s2);
if(res>0)
return 1;
else return -1;
}
}
public static ArrayList<Integer> factor(int n){
int sqrt = (int)Math.sqrt(n);
ArrayList<Integer> al = new ArrayList<>();
for(int i=1;i<=sqrt;i++){
if(n%i!=0)
continue;
int first = i;
int second = n/i;
al.add(i);
if(first==second){
continue;
}
al.add(n/i);
}
return al;
}
public static int power(int x, int y)
{
int temp;
if( y == 0)
return 1;
temp = power(x, y/2);
if (y%2 == 0)
return temp*temp;
else
return x*temp*temp;
}
public static ArrayList<Integer> comp(){
ArrayList<Integer> al = new ArrayList<>();
int n = (int)2e5;
boolean arr[] = new boolean[n+1];
int sqrt = (int)Math.sqrt(n);
for(int i=2;i<=sqrt;i++){
if(arr[i]==false){
for(int j=i*i;j<=n;j+=i){
arr[j]=true;
}
}
}
for(int i=2;i<=n;i++){
if(arr[i]==false)
al.add(i);
}
return al;
}
/*public static class pair{
int x;
int y;
}
public static class comp implements Comparator<pair>{
public int compare(pair o1, pair o2){
if(o1.x==o2.x){
return o1.y-o2.y;
}
return o1.x-o2.x;
}
}*/
static HashMap<Integer,Integer> visited = new HashMap<>();
static class Node{
int node;
int d;
ArrayList<Integer> al = new ArrayList<>();
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static class FastReader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public FastReader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastReader(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();
}
}
} | Java | ["2\n1 2\nba\nac", "3\n1 3 1\naa\nba\nac", "2\n5 5\nbbb\naaa", "2\n3 3\naaa\naa"] | 1 second | ["1", "1", "-1", "-1"] | NoteIn the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is - 1.In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is - 1. | Java 11 | standard input | [
"dp",
"strings"
] | 91cfd24b8d608eb379f709f4509ecd2d | The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of strings. The second line contains n integers ci (0 ≤ ci ≤ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string. Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000. | 1,600 | If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent. | standard output | |
PASSED | 8c6ba391ecdd68e3aded2ea20d40ef33 | train_004.jsonl | 1470933300 | Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically. | 256 megabytes | import java.io.*;
import java.util.*;
/**
* Problem statement here: http://codeforces.com/problemset/problem/706/C
*
* Good luck. This one's a hard problem!
*/
public class FindTheBug6 {
private static int n;
private static int[] energy;
private static String[] words;
private static String[] reversed;
// dp[k][0] is minimum energy needed to store words from k to the end
// dp[k][1] is minimum energy needed to store words from k to the end with words[k] reversed.
private static long[][] dp;
private static void readInput() {
Scanner scan = new Scanner(System.in);
n = scan.nextInt();
energy = new int[n];
words = new String[n];
reversed = new String[n];
for (int i = 0; i < n; i++) {
energy[i] = scan.nextInt();
}
for (int i = 0; i < n; i++) {
words[i] = scan.next();
reversed[i] = new StringBuilder(words[i]).reverse().toString();
}
}
public static void main(String[] args) {
readInput();
dp = new long[n][2];
// Initialize dp to all -1
for (long[] row : dp) {
Arrays.fill(row, -1);
}
// Base case
dp[n - 1][0] = 0;
dp[n - 1][1] = energy[n - 1];
// For every index, for every possible flip of the last two
for (int i = n - 2; i >= 0; i--) {
for (int k = 0; k < 2; k++) {
for (int l = 0; l < 2; l++) {
String cur = k > 0 ? reversed[i] : words[i];
String next = l > 0 ? reversed[i + 1] : words[i + 1];
// cur <= next
if (cur.compareTo(next) <= 0) {
if(dp[i + 1][l] != (long) -1){
long cost = dp[i + 1][l] + (k > 0 ? energy[i] : 0);
dp[i][k] = dp[i][k] == -1 ? cost : Math.min(dp[i][k], cost);
}
}
}
}
}
if (dp[0][0] == -1) {
System.out.println(dp[0][1]);
} else if (dp[0][1] == -1) {
System.out.println(dp[0][0]);
} else {
System.out.println(Math.min(dp[0][0], dp[0][1]));
}
}
}
| Java | ["2\n1 2\nba\nac", "3\n1 3 1\naa\nba\nac", "2\n5 5\nbbb\naaa", "2\n3 3\naaa\naa"] | 1 second | ["1", "1", "-1", "-1"] | NoteIn the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is - 1.In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is - 1. | Java 11 | standard input | [
"dp",
"strings"
] | 91cfd24b8d608eb379f709f4509ecd2d | The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of strings. The second line contains n integers ci (0 ≤ ci ≤ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string. Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000. | 1,600 | If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent. | standard output | |
PASSED | ee0173978e089209d5c71c6a93e78933 | train_004.jsonl | 1470933300 | Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically. | 256 megabytes | import java.io.*;
import java.util.*;
/**
* Problem statement here: http://codeforces.com/problemset/problem/706/C
*
* Good luck. This one's a hard problem!
*/
public class FindTheBug6 {
private static int n;
private static int[] energy;
private static String[] words;
private static String[] reversed;
// dp[k][0] is minimum energy needed to store words from k to the end
// dp[k][1] is minimum energy needed to store words from k to the end with words[k] reversed.
private static long[][] dp;
private static void readInput() {
Scanner scan = new Scanner(System.in);
n = scan.nextInt();
energy = new int[n];
words = new String[n];
reversed = new String[n];
for (int i = 0; i < n; i++) {
energy[i] = scan.nextInt();
}
for (int i = 0; i < n; i++) {
words[i] = scan.next();
reversed[i] = new StringBuilder(words[i]).reverse().toString();
}
}
public static void main(String[] args) {
readInput();
dp = new long[n][2];
// Initialize dp to all -1
for (long[] row : dp) {
Arrays.fill(row, -1);
}
// Base case
dp[n - 1][0] = 0;
dp[n - 1][1] = energy[n - 1];
// For every index, for every possible flip of the last two
for (int i = n - 2; i >= 0; i--) {
for (int k = 0; k < 2; k++) {
for (int l = 0; l < 2; l++) {
String cur = k > 0 ? reversed[i] : words[i];
String next = l > 0 ? reversed[i + 1] : words[i + 1];
// cur <= next
if (cur.compareTo(next) <= 0 && dp[i + 1][l] >= 0) {
long cost = dp[i + 1][l] + (k > 0 ? energy[i] : 0);
dp[i][k] = dp[i][k] == -1 ? cost : Math.min(dp[i][k], cost);
}
}
}
}
if (dp[0][0] == -1) {
System.out.println(dp[0][1]);
} else if (dp[0][1] == -1) {
System.out.println(dp[0][0]);
} else {
System.out.println(Math.min(dp[0][0], dp[0][1]));
}
}
}
| Java | ["2\n1 2\nba\nac", "3\n1 3 1\naa\nba\nac", "2\n5 5\nbbb\naaa", "2\n3 3\naaa\naa"] | 1 second | ["1", "1", "-1", "-1"] | NoteIn the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is - 1.In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is - 1. | Java 11 | standard input | [
"dp",
"strings"
] | 91cfd24b8d608eb379f709f4509ecd2d | The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of strings. The second line contains n integers ci (0 ≤ ci ≤ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string. Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000. | 1,600 | If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent. | standard output | |
PASSED | cc19251fee267af5ecee9e9b2ba2c22b | train_004.jsonl | 1470933300 | Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically. | 256 megabytes | // package cp;
import java.io.*;
import java.math.*;
import java.util.*;
public class Cf_three {
long gcd(long a,long b) {if(b==0)return a;else return gcd(b,a%b);}
void swap(long a,long b) {long temp=a;a=b;b=temp;}
StringBuilder sb=new StringBuilder();
BigInteger RES=new BigInteger("0");
// StringBuilder temp=new StringBuilder(str[i-1]);
// String rev=temp.reverse().toString(); convert sb to string
// if(str[i].compareTo(rev)>=0)minn=0;-compare two Strings
//(Initialize as string) - (a.add(b)) - (array initialized with null and not 0)
Integer[] ARR=new Integer[5];
//Integer sort-TLE-Initialize object elements i.e a[0].
void divisor(long n,int start) {
int cnt=0;for(int i=start;i<=Math.sqrt(n);i++) {
if(n%i==0) {if(i==n/i)cnt++;else cnt+=2;}}}
int f(int n,char[] arr,String ab) {
int cnt=0;
String s="";
for (int i = 0; i < arr.length; i++) {
s=s+arr[i];
}
for (int i = 0; i < (n-7+1); i++) {
String temp=s.substring(i,i+7);
if(temp.equals(ab)) {
cnt++;
}
}
return cnt;
}
public static void main(String[] args) throws IOException {
PrintWriter out = new PrintWriter(System.out);
Readers.init(System.in);
Cf_three obj=new Cf_three();
int n=Readers.nextInt();
long[] c=new long[n+1];
for (int i = 1; i <=n; i++) {
c[i]=Readers.nextLong();
}
String[] str=new String[n+1];
for (int i = 1; i<=n; i++) {
str[i]=Readers.next();
}
long[][] dp=new long[n+1][2];
//dp[i][j]-ith line and j for reversing
dp[1][0]=0;//not reversed
dp[1][1]=c[1];//reversed
for (int i = 2; i <=n; i++) {
for (int j = 0; j < 2; j++) {
StringBuilder temp=new StringBuilder(str[i-1]);
String rev=temp.reverse().toString();
StringBuilder temp2=new StringBuilder(str[i]);
String cur_rev=temp2.reverse().toString();
// if(j==0 && (dp[i-1][0]!=Long.MAX_VALUE || dp[i-1][1]!=Long.MAX_VALUE)) {
if(j==0) {
if(str[i].compareTo(str[i-1])>=0) {
dp[i][0]=dp[i-1][0];
}
else dp[i][0]=(long)1e16;
if(str[i].compareTo(rev)>=0) {
dp[i][0]=Math.min(dp[i][0],dp[i-1][1]);
}
else dp[i][0]=Math.min(dp[i][0],(long)1e16);
}
// if(j==1 && (dp[i-1][1]!=Long.MAX_VALUE || dp[i-1][0]!=Long.MAX_VALUE)) {
if(j==1) {
if(cur_rev.compareTo(str[i-1])>=0) {
dp[i][1]=dp[i-1][0]+c[i];
}
// else dp[i][1]=Long.MAX_VALUE;
else dp[i][1]=(long)1e16;
if(cur_rev.compareTo(rev)>=0) {
dp[i][1]=Math.min(dp[i][1], dp[i-1][1]+c[i]);
}
else dp[i][1]=Math.min(dp[i][1],(long)1e16);
}
}
}
// System.out.println(Long.MAX_VALUE+10000000);
// System.out.println(Arrays.deepToString(dp));
// for (int i = 0; i <=n; i++) {
// for (int j = 0; j <2; j++) {
// System.out.print(dp[i][j]+" ");
// }
// System.out.println();
// }
if(Math.min(dp[n][0], dp[n][1])>=(long)1e16)System.out.println(-1);
else System.out.println(Math.min(dp[n][0], dp[n][1]));
out.flush();
}
}
class Readers {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
static long nextLong() throws IOException{
return Long.parseLong(next());
}
} | Java | ["2\n1 2\nba\nac", "3\n1 3 1\naa\nba\nac", "2\n5 5\nbbb\naaa", "2\n3 3\naaa\naa"] | 1 second | ["1", "1", "-1", "-1"] | NoteIn the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is - 1.In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is - 1. | Java 11 | standard input | [
"dp",
"strings"
] | 91cfd24b8d608eb379f709f4509ecd2d | The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of strings. The second line contains n integers ci (0 ≤ ci ≤ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string. Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000. | 1,600 | If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent. | standard output | |
PASSED | aa52936b2ac58329a253a3f8a44e57dc | train_004.jsonl | 1470933300 | Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically. | 256 megabytes | // package cp;
import java.io.*;
import java.math.*;
import java.util.*;
public class Cf_three {
long gcd(long a,long b) {if(b==0)return a;else return gcd(b,a%b);}
void swap(long a,long b) {long temp=a;a=b;b=temp;}
StringBuilder sb=new StringBuilder();
BigInteger RES=new BigInteger("0");
// StringBuilder temp=new StringBuilder(str[i-1]);
// String rev=temp.reverse().toString(); convert sb to string
// if(str[i].compareTo(rev)>=0)minn=0;-compare two Strings
//(Initialize as string) - (a.add(b)) - (array initialized with null and not 0)
Integer[] ARR=new Integer[5];
//Integer sort-TLE-Initialize object elements i.e a[0].
void divisor(long n,int start) {
int cnt=0;for(int i=start;i<=Math.sqrt(n);i++) {
if(n%i==0) {if(i==n/i)cnt++;else cnt+=2;}}}
int f(int n,char[] arr,String ab) {
int cnt=0;
String s="";
for (int i = 0; i < arr.length; i++) {
s=s+arr[i];
}
for (int i = 0; i < (n-7+1); i++) {
String temp=s.substring(i,i+7);
if(temp.equals(ab)) {
cnt++;
}
}
return cnt;
}
public static void main(String[] args) throws IOException {
PrintWriter out = new PrintWriter(System.out);
Readers.init(System.in);
Cf_three obj=new Cf_three();
int n=Readers.nextInt();
long[] c=new long[n+1];
for (int i = 1; i <=n; i++) {
c[i]=Readers.nextLong();
}
String[] str=new String[n+1];
for (int i = 1; i<=n; i++) {
str[i]=Readers.next();
}
long[][] dp=new long[n+1][2];
dp[1][0]=0;//not reversed
dp[1][1]=c[1];//reversed
for (int i = 2; i <=n; i++) {
for (int j = 0; j < 2; j++) {
StringBuilder temp=new StringBuilder(str[i-1]);
String rev=temp.reverse().toString();
StringBuilder temp2=new StringBuilder(str[i]);
String cur_rev=temp2.reverse().toString();
if(j==0) {
if(str[i].compareTo(str[i-1])>=0)dp[i][0]=dp[i-1][0];
else dp[i][0]=(long)1e16;
if(str[i].compareTo(rev)>=0)dp[i][0]=Math.min(dp[i][0],dp[i-1][1]);
else dp[i][0]=Math.min(dp[i][0],(long)1e16);
}
if(j==1) {
if(cur_rev.compareTo(str[i-1])>=0)dp[i][1]=dp[i-1][0]+c[i];
else dp[i][1]=(long)1e16;
if(cur_rev.compareTo(rev)>=0)dp[i][1]=Math.min(dp[i][1], dp[i-1][1]+c[i]);
else dp[i][1]=Math.min(dp[i][1],(long)1e16);
}
}
}
if(Math.min(dp[n][0], dp[n][1])>=(long)1e16)System.out.println(-1);
else System.out.println(Math.min(dp[n][0], dp[n][1]));
out.flush();
}
}
class Readers {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
static long nextLong() throws IOException{
return Long.parseLong(next());
}
} | Java | ["2\n1 2\nba\nac", "3\n1 3 1\naa\nba\nac", "2\n5 5\nbbb\naaa", "2\n3 3\naaa\naa"] | 1 second | ["1", "1", "-1", "-1"] | NoteIn the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is - 1.In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is - 1. | Java 11 | standard input | [
"dp",
"strings"
] | 91cfd24b8d608eb379f709f4509ecd2d | The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of strings. The second line contains n integers ci (0 ≤ ci ≤ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string. Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000. | 1,600 | If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent. | standard output | |
PASSED | bdeb669efa36a21b9b9de9fda02c071b | train_004.jsonl | 1470933300 | Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically. | 256 megabytes |
import java.util.*;
public class Solution {
static int mod= (int) (1e9+7);
static long INF = (long) 1e14 + 1;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n=input.nextInt();
long c[]=new long[n];
for (int i = 0; i <n ; i++) {
c[i]=input.nextLong();
}
String st[]=new String[n],rev[]=new String[n];
for (int i = 0; i <n ; i++) {
st[i]=input.next();
rev[i]=new StringBuilder(st[i]).reverse()+"";
}
long dp[][]=new long[n+1][2];
// 0=same 1=flip
dp[0][0]=0; dp[0][1]=c[0];
int flag=0;
for (int i = 1; i <n ; i++) {
dp[i][0]=INF; dp[i][1]=INF;
flag=0;
//IF BOTH REVERSE ARE STRING 1 1
if (rev[i].compareTo(rev[i-1])>=0) {
dp[i][1]=Math.min(dp[i][1],dp[i-1][1]+c[i]);
flag=1;
}
//current string rev not prev 0 1
if (rev[i].compareTo(st[i-1])>=0) {
dp[i][1]=Math.min(dp[i][1],dp[i-1][0]+c[i]);
flag=1;
}
// 1 0
if (st[i].compareTo(rev[i-1])>=0) {
dp[i][0]=Math.min(dp[i][0],dp[i-1][1]);
flag=1;
}
// 0 0
if (st[i].compareTo(st[i-1])>=0) {
dp[i][0]=Math.min(dp[i][0],dp[i-1][0]);
flag=1;
}
if (flag==0) break;
}
if (flag==0||Math.min(dp[n-1][0],dp[n-1][1])==INF){
System.out.println(-1);
}else {
System.out.println(Math.min(dp[n-1][0],dp[n-1][1]));
}
}
} | Java | ["2\n1 2\nba\nac", "3\n1 3 1\naa\nba\nac", "2\n5 5\nbbb\naaa", "2\n3 3\naaa\naa"] | 1 second | ["1", "1", "-1", "-1"] | NoteIn the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is - 1.In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is - 1. | Java 11 | standard input | [
"dp",
"strings"
] | 91cfd24b8d608eb379f709f4509ecd2d | The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of strings. The second line contains n integers ci (0 ≤ ci ≤ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string. Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000. | 1,600 | If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent. | standard output | |
PASSED | 1e79b8453dfe5a760d3261c5a3470649 | train_004.jsonl | 1560090900 | Authors guessed an array $$$a$$$ consisting of $$$n$$$ integers; each integer is not less than $$$2$$$ and not greater than $$$2 \cdot 10^5$$$. You don't know the array $$$a$$$, but you know the array $$$b$$$ which is formed from it with the following sequence of operations: Firstly, let the array $$$b$$$ be equal to the array $$$a$$$; Secondly, for each $$$i$$$ from $$$1$$$ to $$$n$$$: if $$$a_i$$$ is a prime number, then one integer $$$p_{a_i}$$$ is appended to array $$$b$$$, where $$$p$$$ is an infinite sequence of prime numbers ($$$2, 3, 5, \dots$$$); otherwise (if $$$a_i$$$ is not a prime number), the greatest divisor of $$$a_i$$$ which is not equal to $$$a_i$$$ is appended to $$$b$$$; Then the obtained array of length $$$2n$$$ is shuffled and given to you in the input. Here $$$p_{a_i}$$$ means the $$$a_i$$$-th prime number. The first prime $$$p_1 = 2$$$, the second one is $$$p_2 = 3$$$, and so on.Your task is to recover any suitable array $$$a$$$ that forms the given array $$$b$$$. It is guaranteed that the answer exists (so the array $$$b$$$ is obtained from some suitable array $$$a$$$). If there are multiple answers, you can print any. | 256 megabytes | import java.io.BufferedReader;
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.Random;
import java.util.StringTokenizer;
public class Solution{
static int maxn = 2800000;
static int[] spf;
static int[] pos;
public static void main(String[] args) {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int tt = 1;
while(tt-->0) {
int n = fs.nextInt();
int[] cnt = new int[maxn+1];
int[] b = new int[2*n];
for(int i=0;i<2*n;i++) {
b[i] = fs.nextInt();
cnt[b[i]]++;
}
sieve();
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=maxn;i>0;i--) {
while(cnt[i]>0) {
if(spf[i]==i) {
cnt[pos[i]]--;
list.add(pos[i]);
}
else {
cnt[i/spf[i]]--;
list.add(i);
}
cnt[i]--;
}
}
for(int i: list) out.print(i+" ");
out.println();
}
out.close();
}
static void sieve() {
spf = new int[maxn+1];
pos = new int[maxn+1];
for(int i=1;i<=maxn;i++) spf[i] = i;
for(int i=2;i*i<=maxn;i++) {
if(spf[i]==i) {
for(int j = i*i;j<=maxn;j+=i) {
if(spf[j]==j)
spf[j] = i;
}
}
}
int cur = 0;
for(int i=2;i<=maxn;i++) {
if(spf[i]==i) pos[i] = ++cur;
}
}
static final Random random=new Random();
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n); int temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static class FastScanner{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String next(){
while(!st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
} catch(IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt(){
return Integer.parseInt(next());
}
public int[] readArray(int n){
int[] a = new int[n];
for(int i=0;i<n;i++)
a[i] = nextInt();
return a;
}
public long nextLong() {
return Long.parseLong(next());
}
public char nextChar() {
return next().toCharArray()[0];
}
}
} | Java | ["3\n3 5 2 3 2 4", "1\n2750131 199999", "1\n3 6"] | 4 seconds | ["3 4 2", "199999", "6"] | null | Java 11 | standard input | [
"greedy",
"graphs",
"number theory",
"sortings",
"dfs and similar"
] | 07484b6a6915c5cb5fdf1921355f2a6a | The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$2n$$$ integers $$$b_1, b_2, \dots, b_{2n}$$$ ($$$2 \le b_i \le 2750131$$$), where $$$b_i$$$ is the $$$i$$$-th element of $$$b$$$. $$$2750131$$$ is the $$$199999$$$-th prime number. | 1,800 | In the only line of the output print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$2 \le a_i \le 2 \cdot 10^5$$$) in any order — the array $$$a$$$ from which the array $$$b$$$ can be obtained using the sequence of moves given in the problem statement. If there are multiple answers, you can print any. | standard output | |
PASSED | 1597ffc15afea7262fb0edcfecdd41e3 | train_004.jsonl | 1560090900 | Authors guessed an array $$$a$$$ consisting of $$$n$$$ integers; each integer is not less than $$$2$$$ and not greater than $$$2 \cdot 10^5$$$. You don't know the array $$$a$$$, but you know the array $$$b$$$ which is formed from it with the following sequence of operations: Firstly, let the array $$$b$$$ be equal to the array $$$a$$$; Secondly, for each $$$i$$$ from $$$1$$$ to $$$n$$$: if $$$a_i$$$ is a prime number, then one integer $$$p_{a_i}$$$ is appended to array $$$b$$$, where $$$p$$$ is an infinite sequence of prime numbers ($$$2, 3, 5, \dots$$$); otherwise (if $$$a_i$$$ is not a prime number), the greatest divisor of $$$a_i$$$ which is not equal to $$$a_i$$$ is appended to $$$b$$$; Then the obtained array of length $$$2n$$$ is shuffled and given to you in the input. Here $$$p_{a_i}$$$ means the $$$a_i$$$-th prime number. The first prime $$$p_1 = 2$$$, the second one is $$$p_2 = 3$$$, and so on.Your task is to recover any suitable array $$$a$$$ that forms the given array $$$b$$$. It is guaranteed that the answer exists (so the array $$$b$$$ is obtained from some suitable array $$$a$$$). If there are multiple answers, you can print any. | 256 megabytes | /* Code by detestmaths*/
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.lang.System.*;
public class Main {
static ArrayList<Integer>pr;
static int pointer = 199998;
static final int maxVal = 2750131;
static int maximal[];
static void init(){
pr = new ArrayList<>();
maximal = new int[maxVal + 1];
boolean prime[] = new boolean[maxVal + 1];
fill(prime,true);
for (int i = 2; i <= maxVal; i++) {
if(!prime[i])continue;
pr.add(i);
long j = i;
while (i * j <= maxVal){
if(!prime[i * (int)j]){
j++;
continue;
}
prime[i * (int)j] = false;
maximal[i * (int)j] = (int)j;
j++;
}
}
}
static int find(int a){
if(!isPrime(a))return -1;
while (pointer > 0){
if(pr.get(pointer) == a)return pointer+1;
pointer--;
}
return 1;
}
static boolean isPrime(int a){
int l = 0;
int r = 199998;
while (l + 1 != r){
int m = (l + r) >> 1;
if(pr.get(m) <= a)l = m;
else r = m;
}
return pr.get(r) == a || pr.get(l) == a;
}
static int findMaximal(int a){
return maximal[a];
}
public static void main(String[] args) throws IOException {
// FastScanner in = new FastScanner("dance.in");
// PrintWriter out = new PrintWriter("dance.out");
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
init();
TreeMap<Integer,Integer>b = new TreeMap<>(new Comparator<Integer>() {
@Override
public int compare(Integer integer, Integer t1) {
return -Integer.compare(integer,t1);
}
});
for (int i = 0; i < 2 * n; i++) {
int t = in.nextInt();
b.put(t,b.getOrDefault(t,0) + 1);
}
while (!b.isEmpty()){
int max = b.firstKey();
int cnt = b.get(max);
if(cnt == 1)b.remove(max);
else b.put(max,cnt - 1);
int f = find(max);
if(f == -1){
out.print(max + " ");
int debug = findMaximal(max);
// out.print(debug + " ");
int q = b.get(debug);
if(q == 1)
b.remove(debug);
else b.put(debug,q-1);
}else{
out.print(f + " ");
int q = b.get(f);
if(q == 1)
b.remove(f);
else b.put(f,q - 1);
}
}
out.close();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st = new StringTokenizer("");
public FastScanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public FastScanner(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(new File(s)));
}
public String next() throws IOException {
if (!st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
} | Java | ["3\n3 5 2 3 2 4", "1\n2750131 199999", "1\n3 6"] | 4 seconds | ["3 4 2", "199999", "6"] | null | Java 11 | standard input | [
"greedy",
"graphs",
"number theory",
"sortings",
"dfs and similar"
] | 07484b6a6915c5cb5fdf1921355f2a6a | The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$2n$$$ integers $$$b_1, b_2, \dots, b_{2n}$$$ ($$$2 \le b_i \le 2750131$$$), where $$$b_i$$$ is the $$$i$$$-th element of $$$b$$$. $$$2750131$$$ is the $$$199999$$$-th prime number. | 1,800 | In the only line of the output print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$2 \le a_i \le 2 \cdot 10^5$$$) in any order — the array $$$a$$$ from which the array $$$b$$$ can be obtained using the sequence of moves given in the problem statement. If there are multiple answers, you can print any. | standard output | |
PASSED | a591737acd122b47edc0084f83c67ebd | train_004.jsonl | 1560090900 | Authors guessed an array $$$a$$$ consisting of $$$n$$$ integers; each integer is not less than $$$2$$$ and not greater than $$$2 \cdot 10^5$$$. You don't know the array $$$a$$$, but you know the array $$$b$$$ which is formed from it with the following sequence of operations: Firstly, let the array $$$b$$$ be equal to the array $$$a$$$; Secondly, for each $$$i$$$ from $$$1$$$ to $$$n$$$: if $$$a_i$$$ is a prime number, then one integer $$$p_{a_i}$$$ is appended to array $$$b$$$, where $$$p$$$ is an infinite sequence of prime numbers ($$$2, 3, 5, \dots$$$); otherwise (if $$$a_i$$$ is not a prime number), the greatest divisor of $$$a_i$$$ which is not equal to $$$a_i$$$ is appended to $$$b$$$; Then the obtained array of length $$$2n$$$ is shuffled and given to you in the input. Here $$$p_{a_i}$$$ means the $$$a_i$$$-th prime number. The first prime $$$p_1 = 2$$$, the second one is $$$p_2 = 3$$$, and so on.Your task is to recover any suitable array $$$a$$$ that forms the given array $$$b$$$. It is guaranteed that the answer exists (so the array $$$b$$$ is obtained from some suitable array $$$a$$$). If there are multiple answers, you can print any. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.lang.System.*;
public class Main {
static ArrayList<Integer>pr;
static int pointer = 199998;
static final int maxVal = 2750131;
static int maximal[];
static void init(){
pr = new ArrayList<>();
maximal = new int[maxVal + 1];
boolean prime[] = new boolean[maxVal + 1];
fill(prime,true);
for (int i = 2; i <= maxVal; i++) {
if(!prime[i])continue;
pr.add(i);
long j = i;
while (i * j <= maxVal){
if(!prime[i * (int)j]){
j++;
continue;
}
prime[i * (int)j] = false;
maximal[i * (int)j] = (int)j;
j++;
}
}
}
static int find(int a){
if(!isPrime(a))return -1;
while (pointer > 0){
if(pr.get(pointer) == a)return pointer+1;
pointer--;
}
return 1;
}
static boolean isPrime(int a){
int l = 0;
int r = 199998;
while (l + 1 != r){
int m = (l + r) >> 1;
if(pr.get(m) <= a)l = m;
else r = m;
}
return pr.get(r) == a || pr.get(l) == a;
}
static int findMaximal(int a){
return maximal[a];
}
public static void main(String[] args) throws IOException {
// FastScanner in = new FastScanner("dance.in");
// PrintWriter out = new PrintWriter("dance.out");
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
init();
TreeMap<Integer,Integer>b = new TreeMap<>(new Comparator<Integer>() {
@Override
public int compare(Integer integer, Integer t1) {
return -Integer.compare(integer,t1);
}
});
for (int i = 0; i < 2 * n; i++) {
int t = in.nextInt();
b.put(t,b.getOrDefault(t,0) + 1);
}
while (!b.isEmpty()){
int max = b.firstKey();
int cnt = b.get(max);
if(cnt == 1)b.remove(max);
else b.put(max,cnt - 1);
int f = find(max);
if(f == -1){
out.print(max + " ");
int debug = findMaximal(max);
// out.print(debug + " ");
int q = b.get(debug);
if(q == 1)
b.remove(debug);
else b.put(debug,q-1);
}else{
out.print(f + " ");
int q = b.get(f);
if(q == 1)
b.remove(f);
else b.put(f,q - 1);
}
}
out.close();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st = new StringTokenizer("");
public FastScanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public FastScanner(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(new File(s)));
}
public String next() throws IOException {
if (!st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
} | Java | ["3\n3 5 2 3 2 4", "1\n2750131 199999", "1\n3 6"] | 4 seconds | ["3 4 2", "199999", "6"] | null | Java 11 | standard input | [
"greedy",
"graphs",
"number theory",
"sortings",
"dfs and similar"
] | 07484b6a6915c5cb5fdf1921355f2a6a | The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$2n$$$ integers $$$b_1, b_2, \dots, b_{2n}$$$ ($$$2 \le b_i \le 2750131$$$), where $$$b_i$$$ is the $$$i$$$-th element of $$$b$$$. $$$2750131$$$ is the $$$199999$$$-th prime number. | 1,800 | In the only line of the output print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$2 \le a_i \le 2 \cdot 10^5$$$) in any order — the array $$$a$$$ from which the array $$$b$$$ can be obtained using the sequence of moves given in the problem statement. If there are multiple answers, you can print any. | standard output | |
PASSED | 404ec66ef0bf6f10542e14dd9fa61423 | train_004.jsonl | 1548938100 | Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with $$$n$$$ nodes and $$$m$$$ bidirectional edges. Initially Bob is at the node $$$1$$$ and he records $$$1$$$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $$$a_1, a_2, \ldots, a_n$$$ is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence $$$x$$$ is lexicographically smaller than a sequence $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$ (this is impossible in this problem as all considered sequences have the same length); in the first position where $$$x$$$ and $$$y$$$ differ, the sequence $$$x$$$ has a smaller element than the corresponding element in $$$y$$$. | 256 megabytes | import java.util.*;
public class Main {
static boolean used[];
static Node arr[];
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
used=new boolean[n+1];
arr=new Node[n+1];
arr[0]=new Node();
for(int i=1;i<=n;i++){
arr[i]=new Node();
}
while(m--!=0){
int a=sc.nextInt();
int b=sc.nextInt();
arr[b].q.add(a);
arr[a].q.add(b);
}
PriorityQueue<Integer> q=new PriorityQueue<Integer>();
q.add(1);
while(!q.isEmpty()){
int a=q.poll();
if(used[a])continue;
used[a]=true;
System.out.print(a==1?1:" "+a);
while(!arr[a].q.isEmpty()){
q.add(arr[a].q.poll());
}
}
System.out.println();
}
}
class Node{
PriorityQueue<Integer>q;
public Node(){
q=new PriorityQueue<Integer>();
}
}
//Stream
/* public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
PriorityQueue<Node> q=new PriorityQueue<Node>();
int a[]=new int[n+1];
int b[]=new int[n+1];
for(int i=1;i<=n;i++)
a[i]=sc.nextInt();
for(int i=1;i<=n;i++)
b[i]=sc.nextInt();
for(int i=1;i<=n;i++)
q.add(new Node(i,a[i],b[i]));
while(m--!=0){
int x=sc.nextInt();
int y=sc.nextInt();
long sum=0;
int min=Math.min(y,a[x]);
sum+=min*1l*b[x];
a[x]-=min;
y-=min;
while(y!=0){
// System.out.println(y);
if(q.isEmpty())
break;
Node node=q.peek();
int id=node.id;
min=Math.min(y,a[id]);
sum+=1l*min*b[id];
a[id]-=min;
if(a[id]==0)
q.poll();
y-=min;
}
System.out.println(y==0?sum:0);
}
/* int n=sc.nextInt();
long arr[]=new long[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
Arrays.sort(arr);
long sum=0;
for(int i=0;i<n;i++)
sum+=(arr[i]+arr[n-1-i])*(arr[i]+arr[n-1-i]);
sum/=2;
System.out.println(sum);
int n=sc.nextInt();
char[][] arr=new char[n][n];
sc.nextLine();
for(int i=0;i<n;i++){
String s=sc.nextLine();
for(int j=0;j<s.length();j++){
arr[i][j]=s.charAt(j);
}
}
int sum=0;
for(int i=1;i<n-1;i++){
for(int j=1;j<n-1;j++){
if(arr[i][j]=='X'&&arr[i-1][j-1]=='X'&&arr[i-1][j+1]=='X'&&arr[i+1][j-1]=='X'&&arr[i+1][j+1]=='X')
{ sum++;
// System.out.println(i+" "+j);
}
}
}
System.out.println(sum);
}
}
class Node implements Comparable{
int id,num,count;
public Node(int id,int num,int count){
this.id=id;
this.num=num;
this.count=count;
}
public int compareTo(Object o){
Node n=(Node)o;
if(this.count!=n.count)
return this.count-n.count;
return this.id-n.id;
}
}
*/ | Java | ["3 2\n1 2\n1 3", "5 5\n1 4\n3 4\n5 4\n3 2\n1 5", "10 10\n1 4\n6 8\n2 5\n3 7\n9 4\n5 6\n3 4\n8 10\n8 9\n1 10"] | 3 seconds | ["1 2 3", "1 4 3 2 5", "1 4 3 7 9 8 6 5 2 10"] | NoteIn the first sample, Bob's optimal wandering path could be $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$. Therefore, Bob will obtain the sequence $$$\{1, 2, 3\}$$$, which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be $$$1 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 5$$$. Therefore, Bob will obtain the sequence $$$\{1, 4, 3, 2, 5\}$$$, which is the lexicographically smallest one. | Java 8 | standard input | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | 157630371c4f6c3bcc6355d96c86a626 | The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), denoting the number of nodes and edges, respectively. The following $$$m$$$ lines describe the bidirectional edges in the graph. The $$$i$$$-th of these lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), representing the nodes the $$$i$$$-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. | 1,500 | Output a line containing the lexicographically smallest sequence $$$a_1, a_2, \ldots, a_n$$$ Bob can record. | standard output | |
PASSED | bf942b799361c5b8e30dfc71469f0925 | train_004.jsonl | 1548938100 | Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with $$$n$$$ nodes and $$$m$$$ bidirectional edges. Initially Bob is at the node $$$1$$$ and he records $$$1$$$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $$$a_1, a_2, \ldots, a_n$$$ is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence $$$x$$$ is lexicographically smaller than a sequence $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$ (this is impossible in this problem as all considered sequences have the same length); in the first position where $$$x$$$ and $$$y$$$ differ, the sequence $$$x$$$ has a smaller element than the corresponding element in $$$y$$$. | 256 megabytes | import java.util.*;
public class LunarYear {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int numNodes = sc.nextInt();
int numEdges = sc.nextInt();
ArrayList<Integer>[] adjacencyList = new ArrayList[numNodes + 1];
for (int i = 0; i < adjacencyList.length; i++) {
adjacencyList[i] = new ArrayList<>();
}
PriorityQueue<Integer> queue = new PriorityQueue<>();
HashSet<Integer> visitedSet = new HashSet<>();
for (int i = 0; i < numEdges; i++) {
int vertex1 = sc.nextInt();
int vertex2 = sc.nextInt();
adjacencyList[vertex1].add(vertex2);
adjacencyList[vertex2].add(vertex1);
}
ArrayList<Integer> order = new ArrayList<Integer>(numNodes);
queue.add(1);
visitedSet.add(1);
while (!queue.isEmpty() && order.size() < numNodes) {
int currVertex = queue.poll();
order.add(currVertex);
for (int i = 0; i < adjacencyList[currVertex].size(); i++) {
int nextNode = adjacencyList[currVertex].get(i);
if (!visitedSet.contains(nextNode)) {
visitedSet.add(nextNode);
queue.add(nextNode);
}
}
}
for (int i = 0; i < order.size(); i++) {
System.out.print(order.get(i) + " ");
}
}
}
| Java | ["3 2\n1 2\n1 3", "5 5\n1 4\n3 4\n5 4\n3 2\n1 5", "10 10\n1 4\n6 8\n2 5\n3 7\n9 4\n5 6\n3 4\n8 10\n8 9\n1 10"] | 3 seconds | ["1 2 3", "1 4 3 2 5", "1 4 3 7 9 8 6 5 2 10"] | NoteIn the first sample, Bob's optimal wandering path could be $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$. Therefore, Bob will obtain the sequence $$$\{1, 2, 3\}$$$, which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be $$$1 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 5$$$. Therefore, Bob will obtain the sequence $$$\{1, 4, 3, 2, 5\}$$$, which is the lexicographically smallest one. | Java 8 | standard input | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | 157630371c4f6c3bcc6355d96c86a626 | The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), denoting the number of nodes and edges, respectively. The following $$$m$$$ lines describe the bidirectional edges in the graph. The $$$i$$$-th of these lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), representing the nodes the $$$i$$$-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. | 1,500 | Output a line containing the lexicographically smallest sequence $$$a_1, a_2, \ldots, a_n$$$ Bob can record. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.