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 | f3860e2589740dbc86d9333fae3040d8 | train_002.jsonl | 1561710000 | Vus the Cossack has $$$n$$$ real numbers $$$a_i$$$. It is known that the sum of all numbers is equal to $$$0$$$. He wants to choose a sequence $$$b$$$ the size of which is $$$n$$$ such that the sum of all numbers is $$$0$$$ and each $$$b_i$$$ is either $$$\lfloor a_i \rfloor$$$ or $$$\lceil a_i \rceil$$$. In other words, $$$b_i$$$ equals $$$a_i$$$ rounded up or down. It is not necessary to round to the nearest integer.For example, if $$$a = [4.58413, 1.22491, -2.10517, -3.70387]$$$, then $$$b$$$ can be equal, for example, to $$$[4, 2, -2, -4]$$$. Note that if $$$a_i$$$ is an integer, then there is no difference between $$$\lfloor a_i \rfloor$$$ and $$$\lceil a_i \rceil$$$, $$$b_i$$$ will always be equal to $$$a_i$$$.Help Vus the Cossack find such sequence! | 256 megabytes | import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
StringBuffer sb=new StringBuffer();
int n=sc.nextInt();
int d[]=new int[n];
double d3[]=new double[n];
int count=0;
for(int i=0;i<n;i++)
{
double d1=sc.nextDouble();
d[i]=(int)d1;
count+=d[i];
d3[i]=d1;
}
for(int i=0;i<n;i++)
{
if(count==0&&i==n)
break;
if(d3[i]<0&&count>0&&d[i]<0&&d[i]!=d3[i])
{
d[i]=d[i]-1;
count--;
}
else if(d3[i]>0&&count<0&&d[i]>=0&&d[i]!=d3[i])
{
d[i]=d[i]+1;
count++;
}
sb.append(d[i]+"\n");
}
System.out.println(sb);
}
} | Java | ["4\n4.58413\n1.22491\n-2.10517\n-3.70387", "5\n-6.32509\n3.30066\n-0.93878\n2.00000\n1.96321"] | 1 second | ["4\n2\n-2\n-4", "-6\n3\n-1\n2\n2"] | NoteThe first example is explained in the legend.In the second example, we can round the first and fifth numbers up, and the second and third numbers down. We can round the fourth number neither up, nor down. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"math"
] | 6059cfa13594d47b3e145d7c26f1b0b3 | The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of numbers. Each of the next $$$n$$$ lines contains one real number $$$a_i$$$ ($$$|a_i| < 10^5$$$). It is guaranteed that each $$$a_i$$$ has exactly $$$5$$$ digits after the decimal point. It is guaranteed that the sum of all the numbers is equal to $$$0$$$. | 1,500 | In each of the next $$$n$$$ lines, print one integer $$$b_i$$$. For each $$$i$$$, $$$|a_i-b_i|<1$$$ must be met. If there are multiple answers, print any. | standard output | |
PASSED | 0844fe5725673c978b6fdc81ef66f176 | train_002.jsonl | 1561710000 | Vus the Cossack has $$$n$$$ real numbers $$$a_i$$$. It is known that the sum of all numbers is equal to $$$0$$$. He wants to choose a sequence $$$b$$$ the size of which is $$$n$$$ such that the sum of all numbers is $$$0$$$ and each $$$b_i$$$ is either $$$\lfloor a_i \rfloor$$$ or $$$\lceil a_i \rceil$$$. In other words, $$$b_i$$$ equals $$$a_i$$$ rounded up or down. It is not necessary to round to the nearest integer.For example, if $$$a = [4.58413, 1.22491, -2.10517, -3.70387]$$$, then $$$b$$$ can be equal, for example, to $$$[4, 2, -2, -4]$$$. Note that if $$$a_i$$$ is an integer, then there is no difference between $$$\lfloor a_i \rfloor$$$ and $$$\lceil a_i \rceil$$$, $$$b_i$$$ will always be equal to $$$a_i$$$.Help Vus the Cossack find such sequence! | 256 megabytes |
import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class Solution 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 Solution(),"Main",1<<27).start();
}
public void run()
{
InputReader in = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int n=in.nextInt();
int ro[]=new int[100000];
double b[]=new double[100000];
int a[]=new int[100000];
int sum=0;
for(int i=0;i<n;i++)
{
b[i]=in.nextDouble();
if(b[i]>0 && Math.floor(b[i])!=b[i])
{
a[i]=(int)Math.floor(b[i]);
ro[i]=1;
}
else if(b[i]<0 && Math.floor(b[i])!=b[i])
{
a[i]=(int)Math.ceil(b[i]);
ro[i]=2;
}
else
a[i]=(int)b[i];
sum+=a[i];
}
if(sum<0)
{
int k=-sum,j=0;
for(int i=0;i<n;i++)
{
if(ro[i]==1)
{
a[i]++;
j++;
}
if(j==k)
break;
}
}
else if(sum>0)
{
int k=sum,j=0;
for(int i=0;i<n;i++)
{
if(ro[i]==2)
{
a[i]--;
j++;
}
if(j==k)
break;
}
}
for(int i=0;i<n;i++)
w.println(a[i]);
w.flush();
w.close();
}
} | Java | ["4\n4.58413\n1.22491\n-2.10517\n-3.70387", "5\n-6.32509\n3.30066\n-0.93878\n2.00000\n1.96321"] | 1 second | ["4\n2\n-2\n-4", "-6\n3\n-1\n2\n2"] | NoteThe first example is explained in the legend.In the second example, we can round the first and fifth numbers up, and the second and third numbers down. We can round the fourth number neither up, nor down. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"math"
] | 6059cfa13594d47b3e145d7c26f1b0b3 | The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of numbers. Each of the next $$$n$$$ lines contains one real number $$$a_i$$$ ($$$|a_i| < 10^5$$$). It is guaranteed that each $$$a_i$$$ has exactly $$$5$$$ digits after the decimal point. It is guaranteed that the sum of all the numbers is equal to $$$0$$$. | 1,500 | In each of the next $$$n$$$ lines, print one integer $$$b_i$$$. For each $$$i$$$, $$$|a_i-b_i|<1$$$ must be met. If there are multiple answers, print any. | standard output | |
PASSED | d230558f226617739508c7ad64b579b9 | train_002.jsonl | 1561710000 | Vus the Cossack has $$$n$$$ real numbers $$$a_i$$$. It is known that the sum of all numbers is equal to $$$0$$$. He wants to choose a sequence $$$b$$$ the size of which is $$$n$$$ such that the sum of all numbers is $$$0$$$ and each $$$b_i$$$ is either $$$\lfloor a_i \rfloor$$$ or $$$\lceil a_i \rceil$$$. In other words, $$$b_i$$$ equals $$$a_i$$$ rounded up or down. It is not necessary to round to the nearest integer.For example, if $$$a = [4.58413, 1.22491, -2.10517, -3.70387]$$$, then $$$b$$$ can be equal, for example, to $$$[4, 2, -2, -4]$$$. Note that if $$$a_i$$$ is an integer, then there is no difference between $$$\lfloor a_i \rfloor$$$ and $$$\lceil a_i \rceil$$$, $$$b_i$$$ will always be equal to $$$a_i$$$.Help Vus the Cossack find such sequence! | 256 megabytes | import java.util.Scanner;
import java.util.Arrays;
public class D {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
double[] a = new double[n];
long sum = 0;
for (int i = 0; i < n; i++) {
a[i] = sc.nextDouble();
sum += (int) a[i];
}
for (int i = 0; i < n; i++) {
if (sum > 0 && a[i] < 0 && a[i] != (int) a[i]) {
System.out.print((int) a[i] - 1 + " ");
sum--;
} else if (sum < 0 && a[i] > 0 && a[i] != (int) a[i]) {
System.out.print((int) a[i] + 1 + " ");
sum++;
} else {
System.out.print((int) a[i] + " ");
}
}
System.out.println();
}
} | Java | ["4\n4.58413\n1.22491\n-2.10517\n-3.70387", "5\n-6.32509\n3.30066\n-0.93878\n2.00000\n1.96321"] | 1 second | ["4\n2\n-2\n-4", "-6\n3\n-1\n2\n2"] | NoteThe first example is explained in the legend.In the second example, we can round the first and fifth numbers up, and the second and third numbers down. We can round the fourth number neither up, nor down. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"math"
] | 6059cfa13594d47b3e145d7c26f1b0b3 | The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of numbers. Each of the next $$$n$$$ lines contains one real number $$$a_i$$$ ($$$|a_i| < 10^5$$$). It is guaranteed that each $$$a_i$$$ has exactly $$$5$$$ digits after the decimal point. It is guaranteed that the sum of all the numbers is equal to $$$0$$$. | 1,500 | In each of the next $$$n$$$ lines, print one integer $$$b_i$$$. For each $$$i$$$, $$$|a_i-b_i|<1$$$ must be met. If there are multiple answers, print any. | standard output | |
PASSED | fefea008885436dbdf3e37245632f1c2 | train_002.jsonl | 1561710000 | Vus the Cossack has $$$n$$$ real numbers $$$a_i$$$. It is known that the sum of all numbers is equal to $$$0$$$. He wants to choose a sequence $$$b$$$ the size of which is $$$n$$$ such that the sum of all numbers is $$$0$$$ and each $$$b_i$$$ is either $$$\lfloor a_i \rfloor$$$ or $$$\lceil a_i \rceil$$$. In other words, $$$b_i$$$ equals $$$a_i$$$ rounded up or down. It is not necessary to round to the nearest integer.For example, if $$$a = [4.58413, 1.22491, -2.10517, -3.70387]$$$, then $$$b$$$ can be equal, for example, to $$$[4, 2, -2, -4]$$$. Note that if $$$a_i$$$ is an integer, then there is no difference between $$$\lfloor a_i \rfloor$$$ and $$$\lceil a_i \rceil$$$, $$$b_i$$$ will always be equal to $$$a_i$$$.Help Vus the Cossack find such sequence! | 256 megabytes | import java.io.*;
import java.util.*;
public class D implements Runnable {
public static void main (String[] args) {new Thread(null, new D(), "_cf", 1 << 28).start();}
public void run() {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
System.err.println("");
int n = fs.nextInt();
int[] res = new int[n];
boolean[] pos = new boolean[n];
boolean[] isDec = new boolean[n];
long[][] sums = new long[2][2];
int[][] vals = new int[n][2];
for(int i = 0; i < n; i++) {
String str = fs.next();
boolean dec = str.endsWith(".00000");
isDec[i] = dec;
if(str.charAt(0) == '-') {
String num = str.substring(1, str.indexOf('.'));
int nn = Integer.parseInt(num);
vals[i][0] = -nn;
if(!dec) vals[i][1] = -(nn+1);
else vals[i][1] = vals[i][0];
sums[0][0] += vals[i][0];
sums[0][1] += vals[i][1];
}
else {
pos[i] = true;
String num = str.substring(0, str.indexOf('.'));
int nn = Integer.parseInt(num);
vals[i][0] = nn;
vals[i][1] = dec ? vals[i][0] : nn+1;
sums[1][0] += vals[i][0];
sums[1][1] += vals[i][1];
}
}
if(sums[0][1] <= -sums[1][0] && -sums[1][0] <= sums[0][0]) {
long sumCur = 0;
long regSum = 0;
for(int i = 0; i < n; i++) if(pos[i]) {
res[i] = vals[i][0];
regSum += res[i];
}
for(int i = 0; i < n; i++) if(!pos[i]) {
sumCur += vals[i][1];
res[i] = vals[i][1];
}
for(int i = 0; i < n && -sumCur != regSum; i++) if(!pos[i] && !isDec[i]) {
sumCur++;
res[i] = vals[i][0];
}
}
else if (sums[1][0] <= -sums[0][0] && -sums[0][0] <= sums[1][1]) {
long sumCur = 0;
long regSum = 0;
for(int i = 0; i < n; i++) if(!pos[i]) {
res[i] = vals[i][0];
regSum += res[i];
}
for(int i = 0; i < n; i++) if(pos[i]) {
sumCur += vals[i][1];
res[i] = vals[i][1];
}
for(int i = 0; i < n && -sumCur != regSum; i++) if(pos[i] && !isDec[i]) {
sumCur--;
res[i] = vals[i][0];
}
}
else {
throw new RuntimeException();
}
for(int i : res) out.println(i);
out.close();
}
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 | ["4\n4.58413\n1.22491\n-2.10517\n-3.70387", "5\n-6.32509\n3.30066\n-0.93878\n2.00000\n1.96321"] | 1 second | ["4\n2\n-2\n-4", "-6\n3\n-1\n2\n2"] | NoteThe first example is explained in the legend.In the second example, we can round the first and fifth numbers up, and the second and third numbers down. We can round the fourth number neither up, nor down. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"math"
] | 6059cfa13594d47b3e145d7c26f1b0b3 | The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of numbers. Each of the next $$$n$$$ lines contains one real number $$$a_i$$$ ($$$|a_i| < 10^5$$$). It is guaranteed that each $$$a_i$$$ has exactly $$$5$$$ digits after the decimal point. It is guaranteed that the sum of all the numbers is equal to $$$0$$$. | 1,500 | In each of the next $$$n$$$ lines, print one integer $$$b_i$$$. For each $$$i$$$, $$$|a_i-b_i|<1$$$ must be met. If there are multiple answers, print any. | standard output | |
PASSED | 4ab712e1e0a6290fd283525b8f2d0dce | train_002.jsonl | 1561710000 | Vus the Cossack has $$$n$$$ real numbers $$$a_i$$$. It is known that the sum of all numbers is equal to $$$0$$$. He wants to choose a sequence $$$b$$$ the size of which is $$$n$$$ such that the sum of all numbers is $$$0$$$ and each $$$b_i$$$ is either $$$\lfloor a_i \rfloor$$$ or $$$\lceil a_i \rceil$$$. In other words, $$$b_i$$$ equals $$$a_i$$$ rounded up or down. It is not necessary to round to the nearest integer.For example, if $$$a = [4.58413, 1.22491, -2.10517, -3.70387]$$$, then $$$b$$$ can be equal, for example, to $$$[4, 2, -2, -4]$$$. Note that if $$$a_i$$$ is an integer, then there is no difference between $$$\lfloor a_i \rfloor$$$ and $$$\lceil a_i \rceil$$$, $$$b_i$$$ will always be equal to $$$a_i$$$.Help Vus the Cossack find such sequence! | 256 megabytes |
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.StringTokenizer;
public class mis {
public static class FastReader {
BufferedReader br;
StringTokenizer st;
//it reads the data about the specified point and divide the data about it ,it is quite fast
//than using direct
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception r) {
r.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());//converts string to integer
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (Exception r) {
r.printStackTrace();
}
return str;
}
}
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
public static void main(String[] args) {
// TODO Auto-generated method stub
FastReader in=new FastReader();
int n=in.nextInt();int a[]=new int[n];int sum=0;double b[]=new double[n];
for(int i=0;i<n;i++)
{
double t=in.nextDouble();
a[i]=(int)Math.floor(t);b[i]=t-a[i];
sum+=a[i];
}
sum=Math.abs(sum);
for(int i=0;i<n;i++)
{if(b[i]!=0.0&&sum>0)
{
System.out.println(a[i]+1);sum--;
}
else
System.out.println(a[i]);
}
}
}
| Java | ["4\n4.58413\n1.22491\n-2.10517\n-3.70387", "5\n-6.32509\n3.30066\n-0.93878\n2.00000\n1.96321"] | 1 second | ["4\n2\n-2\n-4", "-6\n3\n-1\n2\n2"] | NoteThe first example is explained in the legend.In the second example, we can round the first and fifth numbers up, and the second and third numbers down. We can round the fourth number neither up, nor down. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"math"
] | 6059cfa13594d47b3e145d7c26f1b0b3 | The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of numbers. Each of the next $$$n$$$ lines contains one real number $$$a_i$$$ ($$$|a_i| < 10^5$$$). It is guaranteed that each $$$a_i$$$ has exactly $$$5$$$ digits after the decimal point. It is guaranteed that the sum of all the numbers is equal to $$$0$$$. | 1,500 | In each of the next $$$n$$$ lines, print one integer $$$b_i$$$. For each $$$i$$$, $$$|a_i-b_i|<1$$$ must be met. If there are multiple answers, print any. | standard output | |
PASSED | 0950ea50034a97d65d8535818ade47f7 | train_002.jsonl | 1561710000 | Vus the Cossack has $$$n$$$ real numbers $$$a_i$$$. It is known that the sum of all numbers is equal to $$$0$$$. He wants to choose a sequence $$$b$$$ the size of which is $$$n$$$ such that the sum of all numbers is $$$0$$$ and each $$$b_i$$$ is either $$$\lfloor a_i \rfloor$$$ or $$$\lceil a_i \rceil$$$. In other words, $$$b_i$$$ equals $$$a_i$$$ rounded up or down. It is not necessary to round to the nearest integer.For example, if $$$a = [4.58413, 1.22491, -2.10517, -3.70387]$$$, then $$$b$$$ can be equal, for example, to $$$[4, 2, -2, -4]$$$. Note that if $$$a_i$$$ is an integer, then there is no difference between $$$\lfloor a_i \rfloor$$$ and $$$\lceil a_i \rceil$$$, $$$b_i$$$ will always be equal to $$$a_i$$$.Help Vus the Cossack find such sequence! | 256 megabytes | import java.io.*;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
public class D {
static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
static MyScanner sc = new MyScanner();
public static void main(String[] args) {
doTask();
out.flush();
}
public static void doTask(){
int n = sc.nextInt();
double cur = 0;
long[] a = new long[n];
long negnumber =0, posnumber=0, negsum = 0, possum = 0;
Set<Integer> oneState = new HashSet<Integer>();
for (int i = 0; i<n;i++) {
cur = sc.nextDouble();
if (Math.abs(cur - Math.round(cur)) < 0.00000000000001) {
oneState.add(i);
}
a[i] = Math.round(cur - 0.5);
if (a[i] < 0) {
negnumber++;
negsum += a[i];
} else {
posnumber++;
possum += a[i];
}
}
// out.println(negsum + " " + possum);
long diff = Math.abs(negsum) - possum;
if (diff >= 0) {
for (int i = 0; i < n; i++) {
if (diff != 0 && !oneState.contains(i)) {
if (a[i] >= 0) {
a[i]++;
} else {
a[i]++;
}
diff--;
}
out.println(a[i]);
}
} else {
diff = Math.abs(diff);
for (int i = 0; i < n; i++) {
if (diff != 0 && !oneState.contains(i)) {
if (a[i] < 0) {
a[i]--;
}
diff--;
}
out.println(a[i]);
}
}
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["4\n4.58413\n1.22491\n-2.10517\n-3.70387", "5\n-6.32509\n3.30066\n-0.93878\n2.00000\n1.96321"] | 1 second | ["4\n2\n-2\n-4", "-6\n3\n-1\n2\n2"] | NoteThe first example is explained in the legend.In the second example, we can round the first and fifth numbers up, and the second and third numbers down. We can round the fourth number neither up, nor down. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"math"
] | 6059cfa13594d47b3e145d7c26f1b0b3 | The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of numbers. Each of the next $$$n$$$ lines contains one real number $$$a_i$$$ ($$$|a_i| < 10^5$$$). It is guaranteed that each $$$a_i$$$ has exactly $$$5$$$ digits after the decimal point. It is guaranteed that the sum of all the numbers is equal to $$$0$$$. | 1,500 | In each of the next $$$n$$$ lines, print one integer $$$b_i$$$. For each $$$i$$$, $$$|a_i-b_i|<1$$$ must be met. If there are multiple answers, print any. | standard output | |
PASSED | b7305ab2caa6d4011b9cbfd64d4485eb | train_002.jsonl | 1561710000 | Vus the Cossack has $$$n$$$ real numbers $$$a_i$$$. It is known that the sum of all numbers is equal to $$$0$$$. He wants to choose a sequence $$$b$$$ the size of which is $$$n$$$ such that the sum of all numbers is $$$0$$$ and each $$$b_i$$$ is either $$$\lfloor a_i \rfloor$$$ or $$$\lceil a_i \rceil$$$. In other words, $$$b_i$$$ equals $$$a_i$$$ rounded up or down. It is not necessary to round to the nearest integer.For example, if $$$a = [4.58413, 1.22491, -2.10517, -3.70387]$$$, then $$$b$$$ can be equal, for example, to $$$[4, 2, -2, -4]$$$. Note that if $$$a_i$$$ is an integer, then there is no difference between $$$\lfloor a_i \rfloor$$$ and $$$\lceil a_i \rceil$$$, $$$b_i$$$ will always be equal to $$$a_i$$$.Help Vus the Cossack find such sequence! | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.management.MemoryType;
import java.math.BigInteger;
import java.util.*;
public class Main {
static final int INF = Integer.MAX_VALUE;
static int mergeSort(int[] a,int [] c, int begin, int end)
{
int inversion=0;
if(begin < end)
{
inversion=0;
int mid = (begin + end) >>1;
inversion+= mergeSort(a,c, begin, mid);
inversion+=mergeSort(a, c,mid + 1, end);
inversion+=merge(a,c, begin, mid, end);
}
return inversion;
}
static int merge(int[] a,int[]c, int b, int mid, int e)
{
int n1 = mid - b + 1;
int n2 = e - mid;
int[] L = new int[n1+1], R = new int[n2+1];
int[] L1 = new int[n1+1], R1 = new int[n2+1];
//inversion
int inversion=0;
for(int i = 0; i < n1; i++) {
L[i] = a[b + i];
L1[i] = c[b + i];
// L2[i] = w[b + i];
}
for(int i = 0; i < n2; i++) {
R[i] = a[mid + 1 + i];
R1[i] = c[mid + 1 + i];
//R2[i] = w[mid + 1 + i];
}
L[n1] = R[n2] = INF;
for(int k = b, i = 0, j = 0; k <= e; k++)
if(L[i] <= R[j]){
a[k] = L[i];
c[k] = L1[i];
++i;
// w[k]=L2[i++];
}
else
{
a[k] = R[j];
c[k] = R1[j];
//w[k] = R2[j++];
++j;
inversion=inversion+(n1-i);
}
return inversion;
}
static int []c;
static int[] v;
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
public static void main (String[]args) throws IOException {
Scanner in = new Scanner(System.in);
try(PrintWriter or = new PrintWriter(System.out)){
int n = in.nextInt();
double[] a = new double[n];
int[] b = new int[n];
//System.out.println(n + " " + in.next());
int sum = 0;
for(int i = 0;i<n;++i){
a[i] = in.nextDouble();
b[i] = (int)a[i];
sum += b[i];
}
//System.out.println(sum);
StringBuilder res = new StringBuilder();
for(int i = 0;i<n && sum != 0;++i){
if(sum > 0 && a[i]<0 && Math.abs(a[i]-b[i])>=1e-5) {
b[i]--;
sum--;
} else if(sum < 0 && a[i]>0 && Math.abs(a[i]-b[i])>=1e-5){
b[i]++;
sum++;
}
}
for(int i = 0;i<n;++i){
res.append(b[i] + "\n");
}
System.out.println(res);
}
}
static int getlen(int r,int l,int a){
return (r-l+1+1)/(a+1);
}
static int check(Pair[] a, int c) {
ArrayList<Integer> trouble = new ArrayList<>();
int n = a.length;
for (int i = 0; i < n - 1; i++)
if (a[i + 1].val - a[i].val != c) trouble.add(i);
if (trouble.size() == 0) return a[0].idx + 1;
if (trouble.size() == 1) {
int idx = trouble.get(0);
if (idx == 0) return a[idx].idx + 1;
if (idx == n - 2) return a[idx + 1].idx + 1;
if (a[idx].val == a[idx + 1].val) return a[idx].idx + 1;
}
if (trouble.size() == 2) {
int one = trouble.get(0);
int two = trouble.get(1);
if (one + 1 == two && a[two + 1].val - a[one].val == c) return a[two].idx + 1;
}
return -1;
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++) {
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec) {
f *= 10;
}
}
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
class Pair implements Comparable<Pair> {
int idx, val;
public Pair(int idx, int val) {
this.idx = idx;
this.val = val;
}
@Override
public int compareTo(Pair o) {
return val - o.val;
}
}
class Tempo {
int num;
int index;
public Tempo(int num, int index) {
this.num = num;
this.index = index;
}
} | Java | ["4\n4.58413\n1.22491\n-2.10517\n-3.70387", "5\n-6.32509\n3.30066\n-0.93878\n2.00000\n1.96321"] | 1 second | ["4\n2\n-2\n-4", "-6\n3\n-1\n2\n2"] | NoteThe first example is explained in the legend.In the second example, we can round the first and fifth numbers up, and the second and third numbers down. We can round the fourth number neither up, nor down. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"math"
] | 6059cfa13594d47b3e145d7c26f1b0b3 | The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of numbers. Each of the next $$$n$$$ lines contains one real number $$$a_i$$$ ($$$|a_i| < 10^5$$$). It is guaranteed that each $$$a_i$$$ has exactly $$$5$$$ digits after the decimal point. It is guaranteed that the sum of all the numbers is equal to $$$0$$$. | 1,500 | In each of the next $$$n$$$ lines, print one integer $$$b_i$$$. For each $$$i$$$, $$$|a_i-b_i|<1$$$ must be met. If there are multiple answers, print any. | standard output | |
PASSED | 84b02a2f6256cb49a4919d07d3d6cc62 | train_002.jsonl | 1561710000 | Vus the Cossack has $$$n$$$ real numbers $$$a_i$$$. It is known that the sum of all numbers is equal to $$$0$$$. He wants to choose a sequence $$$b$$$ the size of which is $$$n$$$ such that the sum of all numbers is $$$0$$$ and each $$$b_i$$$ is either $$$\lfloor a_i \rfloor$$$ or $$$\lceil a_i \rceil$$$. In other words, $$$b_i$$$ equals $$$a_i$$$ rounded up or down. It is not necessary to round to the nearest integer.For example, if $$$a = [4.58413, 1.22491, -2.10517, -3.70387]$$$, then $$$b$$$ can be equal, for example, to $$$[4, 2, -2, -4]$$$. Note that if $$$a_i$$$ is an integer, then there is no difference between $$$\lfloor a_i \rfloor$$$ and $$$\lceil a_i \rceil$$$, $$$b_i$$$ will always be equal to $$$a_i$$$.Help Vus the Cossack find such sequence! | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class work2
{
static FastReader s;;
static int dp[];
static PrintWriter out;
static class pair
{
double a;
int b;
pair(double x, int y)
{
a=x;
b=y;
}
}
public static void main(String[] args) throws IOException
{
s = new FastReader();
out=new PrintWriter(System.out);
int n = s.ni();
double arr[] = new double[n];
int sum = 0;
pair list[] = new pair[n];
for (int i = 0; i < n; i++)
{
double a = s.nextDouble();
list[i] = new pair(a, i);
sum += (int)a;
}
Arrays.sort(list, new Comparator<pair>()
{
public int compare(pair x, pair y)
{
if (x.a < y.a)
return -1;
else if (x.a > y.a)
return 1;
else
return x.b < y.b ? -1 :1;
}
});
int l = 0, h = n-1;
while ( l <= h)
{
if (sum > 0)
{
if (Math.floor(list[l].a) != (int) list[l].a)
{
list[l].a = Math.floor(list[l].a);
sum--;
}
else
list[l].a = (int) list[l].a;
l++;
}
else if (sum < 0)
{
if (Math.ceil(list[h].a) != (int) list[h].a)
{
list[h].a = Math.ceil(list[h].a);
sum++;
}
else
list[h].a = (int) list[h].a;
h--;
}
else
{
list[l].a = (int) list[l].a;
list[h].a = (int) list[h].a;
l++;
h--;
}
}
Arrays.sort(list, new Comparator<pair>()
{
public int compare(pair x, pair y)
{
if (x.b < y.b)
return -1;
else
return 1;
}
});
for (int i = 0; i < n; i++)
print((int)list[i].a+" ");
println("");
out.flush();
out.close();
}
static int solve(int n, int m)
{
int k = n / 3;
int rem = n - k * 3;
if (rem == 2)
{
k++;
rem = 0;
}
k = (int)(Math.ceil(m/2.0) * k);
if (rem == 1)
{
int g = m/3;
int rem2 = m - g * 3;
if (rem2 == 2)
{
g++;
rem2 = 0;
}
k += g;
}
return k;
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String file_name) throws IOException
{
br = new BufferedReader(new FileReader(file_name));
}
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 nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
} catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static void piarr(Integer arr[])
{
int n = arr.length;
for (int i = 0; i < n; i++)
{
print(arr[i]+" ");
}
println("");
}
static void plarr(Long arr[])
{
int n = arr.length;
for (int i = 0; i < n; i++)
{
print(arr[i]+" ");
}
println("");
}
static void println(Object line)
{
out.println(line);
}
static void print(Object line)
{
out.print(line);
}
static Integer[] iarr(int n)
{
Integer arr[]=new Integer[n];
for(int i = 0; i < n;i++)
arr[i]=s.ni();
return arr;
}
static Long[] larr(int n)
{
Long arr[]=new Long[n];
for(int i = 0; i < n;i++)
arr[i]=s.nl();
return arr;
}
static Integer[][] i2arr(int n, int m)
{
Integer arr[][]=new Integer[n][m];
for(int i = 0; i < n;i++)
for(int j = 0; j < m;j++)
arr[i][j]=s.ni();
return arr;
}
static Long[][] l2arr(int n, int m)
{
Long arr[][]=new Long[n][m];
for(int i = 0; i < n;i++)
for(int j = 0; j < m;j++)
arr[i][j]=s.nl();
return arr;
}
static char [] nc()
{
String str = s.next();
char c[] = str.toCharArray();
return c;
}
static char [][] n2c(int n)
{
char c[][] = new char[n][];
for (int i = 0; i < n; i++)
c[i] = s.next().toCharArray();
return c;
}
} | Java | ["4\n4.58413\n1.22491\n-2.10517\n-3.70387", "5\n-6.32509\n3.30066\n-0.93878\n2.00000\n1.96321"] | 1 second | ["4\n2\n-2\n-4", "-6\n3\n-1\n2\n2"] | NoteThe first example is explained in the legend.In the second example, we can round the first and fifth numbers up, and the second and third numbers down. We can round the fourth number neither up, nor down. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"math"
] | 6059cfa13594d47b3e145d7c26f1b0b3 | The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of numbers. Each of the next $$$n$$$ lines contains one real number $$$a_i$$$ ($$$|a_i| < 10^5$$$). It is guaranteed that each $$$a_i$$$ has exactly $$$5$$$ digits after the decimal point. It is guaranteed that the sum of all the numbers is equal to $$$0$$$. | 1,500 | In each of the next $$$n$$$ lines, print one integer $$$b_i$$$. For each $$$i$$$, $$$|a_i-b_i|<1$$$ must be met. If there are multiple answers, print any. | standard output | |
PASSED | b82b4fa07d9b9b8f71ab9ba7e650f49b | train_002.jsonl | 1561710000 | Vus the Cossack has $$$n$$$ real numbers $$$a_i$$$. It is known that the sum of all numbers is equal to $$$0$$$. He wants to choose a sequence $$$b$$$ the size of which is $$$n$$$ such that the sum of all numbers is $$$0$$$ and each $$$b_i$$$ is either $$$\lfloor a_i \rfloor$$$ or $$$\lceil a_i \rceil$$$. In other words, $$$b_i$$$ equals $$$a_i$$$ rounded up or down. It is not necessary to round to the nearest integer.For example, if $$$a = [4.58413, 1.22491, -2.10517, -3.70387]$$$, then $$$b$$$ can be equal, for example, to $$$[4, 2, -2, -4]$$$. Note that if $$$a_i$$$ is an integer, then there is no difference between $$$\lfloor a_i \rfloor$$$ and $$$\lceil a_i \rceil$$$, $$$b_i$$$ will always be equal to $$$a_i$$$.Help Vus the Cossack find such sequence! | 256 megabytes | // Working program using Reader Class
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.HashMap;
public class Main
{
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
public static void main (String[] args) throws IOException {
Reader s=new Reader();
int n=s.nextInt();
int i,sum=0;
double a[]=new double[n];
HashMap<Integer, Integer> hmap2=new HashMap<> ();
for(i=0;i<n;i++){
a[i]=s.nextDouble();
if((int)(Math.floor(a[i])) == (int)(Math.ceil(a[i]))){
hmap2.put(i, 1);
}
else{
hmap2.put(i, 0);
}
sum+=(int)(Math.floor(a[i]));
}
if(sum==0){
for(i=0;i<n;i++){
System.out.println((int)(Math.floor(a[i])));
}
}
else{
int curr_c = 0, curr_f=0;
for(i=0;i<n;i++){
curr_c=(int)(Math.ceil(a[i]));
curr_f=(int)(Math.floor(a[i]));
if(sum==0){
System.out.println(curr_f);
}
else if(curr_c != curr_f ){
System.out.println(curr_c);
sum+=1;
}
else{
System.out.println(curr_f);
}
}
}
}
}
| Java | ["4\n4.58413\n1.22491\n-2.10517\n-3.70387", "5\n-6.32509\n3.30066\n-0.93878\n2.00000\n1.96321"] | 1 second | ["4\n2\n-2\n-4", "-6\n3\n-1\n2\n2"] | NoteThe first example is explained in the legend.In the second example, we can round the first and fifth numbers up, and the second and third numbers down. We can round the fourth number neither up, nor down. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"math"
] | 6059cfa13594d47b3e145d7c26f1b0b3 | The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of numbers. Each of the next $$$n$$$ lines contains one real number $$$a_i$$$ ($$$|a_i| < 10^5$$$). It is guaranteed that each $$$a_i$$$ has exactly $$$5$$$ digits after the decimal point. It is guaranteed that the sum of all the numbers is equal to $$$0$$$. | 1,500 | In each of the next $$$n$$$ lines, print one integer $$$b_i$$$. For each $$$i$$$, $$$|a_i-b_i|<1$$$ must be met. If there are multiple answers, print any. | standard output | |
PASSED | 3bc3ab6c884538adf05f64134b44b6e2 | train_002.jsonl | 1561710000 | Vus the Cossack has $$$n$$$ real numbers $$$a_i$$$. It is known that the sum of all numbers is equal to $$$0$$$. He wants to choose a sequence $$$b$$$ the size of which is $$$n$$$ such that the sum of all numbers is $$$0$$$ and each $$$b_i$$$ is either $$$\lfloor a_i \rfloor$$$ or $$$\lceil a_i \rceil$$$. In other words, $$$b_i$$$ equals $$$a_i$$$ rounded up or down. It is not necessary to round to the nearest integer.For example, if $$$a = [4.58413, 1.22491, -2.10517, -3.70387]$$$, then $$$b$$$ can be equal, for example, to $$$[4, 2, -2, -4]$$$. Note that if $$$a_i$$$ is an integer, then there is no difference between $$$\lfloor a_i \rfloor$$$ and $$$\lceil a_i \rceil$$$, $$$b_i$$$ will always be equal to $$$a_i$$$.Help Vus the Cossack find such sequence! | 256 megabytes |
import java.io.*;
import static java.lang.Double.max;
import static java.lang.Math.pow;
import java.util.*;
/**
*
* @author Mohammed M Elkady
*/
public class Mamo {
static long ans,sum,max=-99999999;
static long []ho;
static StringBuilder Sd=new StringBuilder();
static FastReader in=new FastReader();
public static void main(String[] args) {
int n=in.nextInt();
double a[]=new double[n],d=0;
for(int i=0;i<n;i++){a[i]=in.nextDouble();d+=(int)a[i];}
if(d==0){
for(int i=0;i<n;i++){System.out.println((int)a[i]);}
}
else if(d>0){
for(int i=0;i<n;i++){
if(a[i]%1==0||a[i]>0||d==0)
System.out.println((int)a[i]);
else {System.out.println((int)a[i]-1);d--;}
}
}
else{for(int i=0;i<n;i++){
if(a[i]%1==0||a[i]<0||d==0)
System.out.println((int)a[i]);
else {System.out.println((int)a[i]+1);d++;}
}}
}}
class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
class Sorting{
public static int[] bucketSort(int[] array, int bucketCount) {
if (bucketCount <= 0) throw new IllegalArgumentException("Invalid bucket count");
if (array.length <= 1) return array; //trivially sorted
int high = array[0];
int low = array[0];
for (int i = 1; i < array.length; i++) { //find the range of input elements
if (array[i] > high) high = array[i];
if (array[i] < low) low = array[i];
}
double interval = ((double)(high - low + 1))/bucketCount; //range of one bucket
ArrayList<Integer> buckets[] = new ArrayList[bucketCount];
for (int i = 0; i < bucketCount; i++) { //initialize buckets
buckets[i] = new ArrayList();
}
for (int i = 0; i < array.length; i++) { //partition the input array
buckets[(int)((array[i] - low)/interval)].add(array[i]);
}
int pointer = 0;
for (int i = 0; i < buckets.length; i++) {
Collections.sort(buckets[i]); //mergeSort
for (int j = 0; j < buckets[i].size(); j++) { //merge the buckets
array[pointer] = buckets[i].get(j);
pointer++;
}
}
return array;
}
} | Java | ["4\n4.58413\n1.22491\n-2.10517\n-3.70387", "5\n-6.32509\n3.30066\n-0.93878\n2.00000\n1.96321"] | 1 second | ["4\n2\n-2\n-4", "-6\n3\n-1\n2\n2"] | NoteThe first example is explained in the legend.In the second example, we can round the first and fifth numbers up, and the second and third numbers down. We can round the fourth number neither up, nor down. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"math"
] | 6059cfa13594d47b3e145d7c26f1b0b3 | The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of numbers. Each of the next $$$n$$$ lines contains one real number $$$a_i$$$ ($$$|a_i| < 10^5$$$). It is guaranteed that each $$$a_i$$$ has exactly $$$5$$$ digits after the decimal point. It is guaranteed that the sum of all the numbers is equal to $$$0$$$. | 1,500 | In each of the next $$$n$$$ lines, print one integer $$$b_i$$$. For each $$$i$$$, $$$|a_i-b_i|<1$$$ must be met. If there are multiple answers, print any. | standard output | |
PASSED | 7c6159373ca5407625c22fd6d2215cb8 | train_002.jsonl | 1561710000 | Vus the Cossack has $$$n$$$ real numbers $$$a_i$$$. It is known that the sum of all numbers is equal to $$$0$$$. He wants to choose a sequence $$$b$$$ the size of which is $$$n$$$ such that the sum of all numbers is $$$0$$$ and each $$$b_i$$$ is either $$$\lfloor a_i \rfloor$$$ or $$$\lceil a_i \rceil$$$. In other words, $$$b_i$$$ equals $$$a_i$$$ rounded up or down. It is not necessary to round to the nearest integer.For example, if $$$a = [4.58413, 1.22491, -2.10517, -3.70387]$$$, then $$$b$$$ can be equal, for example, to $$$[4, 2, -2, -4]$$$. Note that if $$$a_i$$$ is an integer, then there is no difference between $$$\lfloor a_i \rfloor$$$ and $$$\lceil a_i \rceil$$$, $$$b_i$$$ will always be equal to $$$a_i$$$.Help Vus the Cossack find such sequence! | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException{
InputReader input = new InputReader (System.in);
PrintWriter out = new PrintWriter(System.out);
int n = input.nextInt();
ArrayList<Double>a = new ArrayList<Double>();
int suma = 0; int sumb = 0; int numa = 0; int numb = 0;
double random = 0;
for(int i=0; i<n; i++) {
random = input.nextDouble();
a.add(random);
if(random>0) {
suma+=(int)Math.ceil(random);
}else{
sumb-=(int)Math.floor(random);
}
}
double num=0;
if(suma>=sumb) {
int cha = suma-sumb;
for(int i=0; i<a.size(); i++) {
num = a.get(i);
if(num>0) {
if(cha>0 && num%1!=0) {
cha--;
out.println((int)Math.floor(num));
}else {
out.println((int)Math.ceil(num));
}
}else {
out.println((int)Math.floor(num));
}
}
}else {
int cha = sumb-suma;
for(int i=0; i<a.size(); i++) {
num = a.get(i);
if(num<0) {
if(cha>0 && num%1!=0) {
cha--;
out.println((int)Math.ceil(num));
}else {
out.println((int)Math.floor(num));
}
}else {
out.println((int)Math.ceil(num));
}
}
}
out.close();
}
}
class InputReader{
private final static int BUF_SZ = 65536;
BufferedReader in;
StringTokenizer tokenizer;
public InputReader(InputStream in) {
super();
this.in = new BufferedReader(new InputStreamReader(in),BUF_SZ);
tokenizer = new StringTokenizer("");
}
private String next() {
while (!tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(in.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
} | Java | ["4\n4.58413\n1.22491\n-2.10517\n-3.70387", "5\n-6.32509\n3.30066\n-0.93878\n2.00000\n1.96321"] | 1 second | ["4\n2\n-2\n-4", "-6\n3\n-1\n2\n2"] | NoteThe first example is explained in the legend.In the second example, we can round the first and fifth numbers up, and the second and third numbers down. We can round the fourth number neither up, nor down. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"math"
] | 6059cfa13594d47b3e145d7c26f1b0b3 | The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of numbers. Each of the next $$$n$$$ lines contains one real number $$$a_i$$$ ($$$|a_i| < 10^5$$$). It is guaranteed that each $$$a_i$$$ has exactly $$$5$$$ digits after the decimal point. It is guaranteed that the sum of all the numbers is equal to $$$0$$$. | 1,500 | In each of the next $$$n$$$ lines, print one integer $$$b_i$$$. For each $$$i$$$, $$$|a_i-b_i|<1$$$ must be met. If there are multiple answers, print any. | standard output | |
PASSED | d393c1b29ce77525b710e3612a94c894 | train_002.jsonl | 1561710000 | Vus the Cossack has $$$n$$$ real numbers $$$a_i$$$. It is known that the sum of all numbers is equal to $$$0$$$. He wants to choose a sequence $$$b$$$ the size of which is $$$n$$$ such that the sum of all numbers is $$$0$$$ and each $$$b_i$$$ is either $$$\lfloor a_i \rfloor$$$ or $$$\lceil a_i \rceil$$$. In other words, $$$b_i$$$ equals $$$a_i$$$ rounded up or down. It is not necessary to round to the nearest integer.For example, if $$$a = [4.58413, 1.22491, -2.10517, -3.70387]$$$, then $$$b$$$ can be equal, for example, to $$$[4, 2, -2, -4]$$$. Note that if $$$a_i$$$ is an integer, then there is no difference between $$$\lfloor a_i \rfloor$$$ and $$$\lceil a_i \rceil$$$, $$$b_i$$$ will always be equal to $$$a_i$$$.Help Vus the Cossack find such sequence! | 256 megabytes | import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.StringTokenizer;
public class D {
static FastReader scan;
static PrintWriter out;
public static void main(String[] args) throws FileNotFoundException {
Solver solver = new Solver();
scan = new FastReader();
out = new PrintWriter(System.out);
int testCases = 1;
for(int i = 1; i <= testCases; i++) {
// out.print("Case #" + i + ": ");
solver.solve();
}
out.close();
}
static class Solver {
void solve() {
int n = scan.nextInt(), last = -1;
long total = 0;
double[] a = scan.nextDoubleArray(n);
for(int i = 0; i < n; i++) {
if(a[i] >= 0) total += (long) (a[i]);
else if(a[i] != (long) a[i]) {
total += ((long) (a[i]))-1L;
}
else total += (long) a[i];
}
for(int i = 0; i < n; i++) {
if(a[i] == (long) a[i]) out.println((long) a[i]);
else if(total < 0) {
if(a[i] > 0) out.println((long) (a[i])+1L);
else out.println((long) a[i]);
total++;
}
else {
if(a[i] > 0) out.println((long) (a[i]));
else out.println(((long) a[i])-1L);
}
}
}
}
// Sathvik's Template Stuff BELOW!!!!!!!!!!!!!!!!!!!!!!
static class DSU {
int[] root, size;
int n;
DSU(int n) {
this.n = n;
root = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
root[i] = i;
size[i] = 1;
}
}
int findParent(int idx) {
while (root[idx] != idx) {
root[idx] = root[root[idx]];
idx = root[idx];
}
return idx;
}
boolean union(int x, int y) {
int parX = findParent(x);
int parY = findParent(y);
if (parX == parY)
return false;
if (size[parX] < size[parY]) {
root[parY] = parX;
size[parX] += size[parY];
} else {
root[parX] = parY;
size[parY] += size[parX];
}
return true;
}
}
static class Extra {
static void sort(int[] a) {
Integer[] aa = new Integer[a.length];
for (int i = 0; i < aa.length; i++)
aa[i] = a[i];
Arrays.sort(aa);
for (int i = 0; i < aa.length; i++)
a[i] = aa[i];
}
static void sort(long[] a) {
Long[] aa = new Long[a.length];
for (int i = 0; i < aa.length; i++)
aa[i] = a[i];
Arrays.sort(aa);
for (int i = 0; i < aa.length; i++)
a[i] = aa[i];
}
static void sort(double[] a) {
Double[] aa = new Double[a.length];
for (int i = 0; i < aa.length; i++)
aa[i] = a[i];
Arrays.sort(aa);
for (int i = 0; i < aa.length; i++)
a[i] = aa[i];
}
static void sort(char[] a) {
Character[] aa = new Character[a.length];
for (int i = 0; i < aa.length; i++)
aa[i] = a[i];
Arrays.sort(aa);
for (int i = 0; i < aa.length; i++)
a[i] = aa[i];
}
static long gcd(long a, long b) {
while (b > 0) {
long temp = b;
b = a % b;
a = temp;
}
return a;
}
static long lcm(long a, long b) {
return a * (b / gcd(a, b));
}
static boolean isPrime(long n) {
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (long i = 5; i * i <= n; i = i + 6) {
if (n % i == 0 || n % (i + 2) == 0)
return false;
}
return true;
}
static HashSet<Integer> sieve(int n) {
boolean[] prime = new boolean[n + 1];
HashSet<Integer> res = new HashSet<>();
for (int p = 2; p * p <= n; p++) {
if (!prime[p]) {
res.add(p);
for (int i = p * p; i <= n; i += p)
prime[i] = true;
}
}
return res;
}
static HashMap<Long, Integer> primeFactorization(long n) {
HashMap<Long, Integer> res = new HashMap<>();
while (n % 2 == 0) {
res.put(2L, res.getOrDefault(2L, 0) + 1);
n /= 2;
}
for (long i = 3; i * i <= n; i += 2) {
while (n % i == 0) {
res.put(i, res.getOrDefault(i, 0) + 1);
n /= i;
}
}
if (n > 2)
res.put(n, 1);
return res;
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(new File(s)));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
double nextDouble() {
return Double.parseDouble(next());
}
double[] nextDoubleArray(int n) {
double[] a = new double[n];
for (int i = 0; i < n; i++)
a[i] = nextDouble();
return a;
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["4\n4.58413\n1.22491\n-2.10517\n-3.70387", "5\n-6.32509\n3.30066\n-0.93878\n2.00000\n1.96321"] | 1 second | ["4\n2\n-2\n-4", "-6\n3\n-1\n2\n2"] | NoteThe first example is explained in the legend.In the second example, we can round the first and fifth numbers up, and the second and third numbers down. We can round the fourth number neither up, nor down. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"math"
] | 6059cfa13594d47b3e145d7c26f1b0b3 | The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of numbers. Each of the next $$$n$$$ lines contains one real number $$$a_i$$$ ($$$|a_i| < 10^5$$$). It is guaranteed that each $$$a_i$$$ has exactly $$$5$$$ digits after the decimal point. It is guaranteed that the sum of all the numbers is equal to $$$0$$$. | 1,500 | In each of the next $$$n$$$ lines, print one integer $$$b_i$$$. For each $$$i$$$, $$$|a_i-b_i|<1$$$ must be met. If there are multiple answers, print any. | standard output | |
PASSED | 12191d9b0755c732df55adb4c05149eb | train_002.jsonl | 1561710000 | Vus the Cossack has $$$n$$$ real numbers $$$a_i$$$. It is known that the sum of all numbers is equal to $$$0$$$. He wants to choose a sequence $$$b$$$ the size of which is $$$n$$$ such that the sum of all numbers is $$$0$$$ and each $$$b_i$$$ is either $$$\lfloor a_i \rfloor$$$ or $$$\lceil a_i \rceil$$$. In other words, $$$b_i$$$ equals $$$a_i$$$ rounded up or down. It is not necessary to round to the nearest integer.For example, if $$$a = [4.58413, 1.22491, -2.10517, -3.70387]$$$, then $$$b$$$ can be equal, for example, to $$$[4, 2, -2, -4]$$$. Note that if $$$a_i$$$ is an integer, then there is no difference between $$$\lfloor a_i \rfloor$$$ and $$$\lceil a_i \rceil$$$, $$$b_i$$$ will always be equal to $$$a_i$$$.Help Vus the Cossack find such sequence! | 256 megabytes | import javafx.util.Pair;
import sun.net.www.content.text.Generic;
import static java.lang.Double.parseDouble;
import static java.lang.Integer.parseInt;
import static java.lang.Integer.reverse;
import static java.lang.Long.parseLong;
import static java.lang.Math.abs;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.System.exit;
import static java.util.Comparator.comparingInt;
import static java.util.Map.Entry.comparingByValue;
import static java.util.stream.Collectors.toMap;
import java.io.*;
import java.lang.reflect.Array;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;
public class Solution {
static BufferedReader in;
static PrintWriter out;
static StringTokenizer tok;
void solve() throws Exception {
int n = nextInt();
long sum = 0;
int a[] = new int[n], b[] = new int[n];
for(int i = 0; i < n; i++) {
double d = nextDouble();
a[i] = b[i] = (int)d;
if(d >= 0) {
if(d != (int)d)
b[i]++;
} else {
if(d != (int)d)
b[i]--;
}
sum += min((long)a[i], (long)b[i]);
}
for(int i = 0; i < n; i++) {
if(sum < 0) {
if(a[i] > b[i]) {
out.println(a[i]);
sum++;
}
else if(a[i] < b[i]) {
out.println(b[i]);
sum++;
} else out.println(a[i]);
} else out.println(min((long)a[i], (long)b[i]));
}
}
// call it like this: lower_bound(a, x + 1) ( /!\ + 1 )
public static int lower_bound(int[] a, int v) {
int low = -1, high = a.length;
while (high - low > 1) {
int h = high + low >>> 1;
if (a[h] >= v) {
high = h;
} else {
low = h;
}
}
return high;
}
private String getFraction(int a, int b) {
assert b != 0;
String sign = (a > 0 && b > 0) || (a < 0) && (b < 0) ? "+" : "-";
a = abs(a);
b = abs(b);
int gcd = gcd(a, b);
return sign + (a / gcd) + "/" + (b / gcd);
}
private int gcd(int a, int b) {
while (b > 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
private int lcm(int a, int b) {
return a * (b / gcd(a, b));
}
public static int[] radixSort(int[] f) {
if (f.length < 100) {
Arrays.sort(f);
return f;
}
int[] to = new int[f.length];
{
int[] b = new int[65537];
for (int i = 0; i < f.length; i++) b[1 + (f[i] & 0xffff)]++;
for (int i = 1; i <= 65536; i++) b[i] += b[i - 1];
for (int i = 0; i < f.length; i++) to[b[f[i] & 0xffff]++] = f[i];
int[] d = f;
f = to;
to = d;
}
{
int[] b = new int[65537];
for (int i = 0; i < f.length; i++) b[1 + (f[i] >>> 16)]++;
for (int i = 1; i <= 65536; i++) b[i] += b[i - 1];
for (int i = 0; i < f.length; i++) to[b[f[i] >>> 16]++] = f[i];
int[] d = f;
f = to;
to = d;
}
return f;
}
public static boolean nextPermutation(int[] a) {
int n = a.length;
int i;
for (i = n - 2; i >= 0 && a[i] >= a[i + 1]; i--) ;
if (i == -1)
return false;
int j;
for (j = i + 1; j < n && a[i] < a[j]; j++) ;
int d = a[i];
a[i] = a[j - 1];
a[j - 1] = d;
for (int p = i + 1, q = n - 1; p < q; p++, q--) {
d = a[p];
a[p] = a[q];
a[q] = d;
}
return true;
}
void print(Object x) {
out.print(String.valueOf(x));
out.flush();
}
void println(Object x) {
out.println(String.valueOf(x));
out.flush();
}
// for Map with custom key/value, override toString in your custom class
void printMap(Map map) {
if (map.keySet().size() == 0) return;
Object firstValue = map.keySet().iterator().next();
if (map.get(firstValue) instanceof Queue || map.get(firstValue) instanceof List) {
for (Object key : map.keySet()) {
out.print(String.valueOf(key) + ": ");
Collection values = (Collection) map.get(key);
for (Object value : values) out.print(String.valueOf(value) + " ");
out.println();
}
} else if (map.get(firstValue).getClass().isArray()) {
for (Object key : map.keySet()) {
out.print(String.valueOf(key) + ": ");
Object[] values = (Object[]) map.get(key);
for (Object value : values) out.print(String.valueOf(value) + " ");
out.println();
}
} else {
for (Object key : map.keySet()) {
out.println(String.valueOf(key) + ": " + map.get(key));
}
}
}
private int[] na(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
private long[] nal(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
int nextInt() throws IOException {
return parseInt(next());
}
long nextLong() throws IOException {
return parseLong(next());
}
double nextDouble() throws IOException {
return parseDouble(next());
}
String next() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
public static void main(String[] args) throws Exception {
try {
boolean isLocal = false;
if (isLocal) {
in = new BufferedReader(new FileReader("mr_x.txt"));
out = new PrintWriter(new BufferedWriter(new FileWriter("solution.out")));
} else {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
}
//long lStartTime = System.currentTimeMillis();
new Solution().solve();
//long lEndTime = System.currentTimeMillis();
//out.println("Elapsed time in seconds: " + (double)(lEndTime - lStartTime) / 1000.0);
in.close();
out.close();
} catch (Throwable e) {
e.printStackTrace();
exit(1);
}
}
} | Java | ["4\n4.58413\n1.22491\n-2.10517\n-3.70387", "5\n-6.32509\n3.30066\n-0.93878\n2.00000\n1.96321"] | 1 second | ["4\n2\n-2\n-4", "-6\n3\n-1\n2\n2"] | NoteThe first example is explained in the legend.In the second example, we can round the first and fifth numbers up, and the second and third numbers down. We can round the fourth number neither up, nor down. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"math"
] | 6059cfa13594d47b3e145d7c26f1b0b3 | The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of numbers. Each of the next $$$n$$$ lines contains one real number $$$a_i$$$ ($$$|a_i| < 10^5$$$). It is guaranteed that each $$$a_i$$$ has exactly $$$5$$$ digits after the decimal point. It is guaranteed that the sum of all the numbers is equal to $$$0$$$. | 1,500 | In each of the next $$$n$$$ lines, print one integer $$$b_i$$$. For each $$$i$$$, $$$|a_i-b_i|<1$$$ must be met. If there are multiple answers, print any. | standard output | |
PASSED | d899466d09844882070ed0fd08bc19e7 | train_002.jsonl | 1441526400 | People in BubbleLand like to drink beer. Little do you know, beer here is so good and strong that every time you drink it your speed goes 10 times slower than before you drank it.Birko lives in city Beergrade, but wants to go to city Beerburg. You are given a road map of BubbleLand and you need to find the fastest way for him. When he starts his journey in Beergrade his speed is 1. When he comes to a new city he always tries a glass of local beer, which divides his speed by 10. The question here is what the minimal time for him to reach Beerburg is. If there are several paths with the same minimal time, pick the one that has least roads on it. If there is still more than one path, pick any.It is guaranteed that there will be at least one path from Beergrade to Beerburg. | 256 megabytes | //package bubble8;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.InputMismatchException;
import java.util.Queue;
public class G {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni(), m = ni();
int[] from = new int[m];
int[] to = new int[m];
int[] w = new int[m];
for (int i = 0; i < m; i++) {
from[i] = ni();
to[i] = ni();
w[i] = ni();
}
int[][][] g = packWU(n, from, to, w);
int[] ds = distmap(g, 0);
int[] dg2 = distmap2(g, n-1);
int[] come = new int[n];
Arrays.fill(come, 10);
Queue<Integer> q = new ArrayDeque<>();
int N = n+3;
for(int i = 0;i < n;i++){
if(dg2[i] == 0){
N = Math.min(N, ds[i]);
}
}
char[] ret = new char[N];
for(int i = 0;i < n;i++){
if(dg2[i] == 0 && ds[i] == N){
q.add(i);
come[i] = -1;
}
}
int pos = 0;
while(!q.isEmpty()){
if(ds[q.peek()] == 0)break;
Queue<Integer> nq = new ArrayDeque<>();
int lmin = 10;
while(!q.isEmpty()){
int cur = q.poll();
for(int[] e : g[cur]){
if(ds[e[0]] < ds[cur]){
if(come[e[0]] == 10){
nq.add(e[0]);
}
if(e[1] < come[e[0]]){
come[e[0]] = e[1];
}
lmin = Math.min(lmin, e[1]);
}
}
}
ret[pos++] = (char)('0'+lmin);
while(!nq.isEmpty()){
int cur = nq.poll();
if(come[cur] == lmin){
q.add(cur);
}
}
}
boolean vis = false;
for(int i = 0;i < N;i++){
if(ret[i] != '0')vis = true;
if(vis)out.print(ret[i]);
}
if(!vis)out.print(0);
out.println();
// if(dg2[i] == 0 && ds[i] == N){
q = new ArrayDeque<>();
q.add(0);
int[] prev = new int[n];
Arrays.fill(prev, -1);
int[] dsx = new int[n];
Arrays.fill(dsx, 99999999);
dsx[0] = 0;
while(!q.isEmpty()){
int cur = q.poll();
for(int[] e : g[cur]){
if(dsx[e[0]] > dsx[cur] + 1){
if(N-1-ds[cur] >= 0){
if(ret[N-1-ds[cur]] != '0' + e[1])continue;
}else{
if(e[1] != 0)continue;
}
dsx[e[0]] = dsx[cur] + 1;
q.add(e[0]);
prev[e[0]] = cur;
}
}
}
out.println(dsx[n-1]+1);
int[] route = new int[dsx[n-1]+1];
int p = dsx[n-1];
for(int i = n-1;i != -1;i = prev[i]){
route[p--] = i;
}
for(int v : route){
out.print(v + " ");
}
out.println();
}
int[] distmap(int[][][] g, int s)
{
int n = g.length;
int[] d = new int[n];
Arrays.fill(d, 999999999);
d[s] = 0;
Queue<Integer> q = new ArrayDeque<>();
q.add(s);
while(!q.isEmpty()){
int cur = q.poll();
for(int[] e : g[cur]){
if(d[e[0]] > d[cur] + 1){
d[e[0]] = d[cur] + 1;
q.add(e[0]);
}
}
}
return d;
}
int[] distmap2(int[][][] g, int s)
{
int n = g.length;
int[] d = new int[n];
Arrays.fill(d, 999999999);
d[s] = 0;
Deque<Integer> q = new ArrayDeque<>();
q.add(s);
while(!q.isEmpty()){
int cur = q.pollFirst();
for(int[] e : g[cur]){
if(e[1] > 0){
if(d[e[0]] > d[cur] + 1){
d[e[0]] = d[cur] + 1;
q.addLast(e[0]);
}
}else{
if(d[e[0]] > d[cur]){
d[e[0]] = d[cur];
q.addFirst(e[0]);
}
}
}
}
return d;
}
public static int[][][] packWU(int n, int[] from, int[] to, int[] w) {
int[][][] g = new int[n][][];
int[] p = new int[n];
for (int f : from)
p[f]++;
for (int t : to)
p[t]++;
for (int i = 0; i < n; i++)
g[i] = new int[p[i]][2];
for (int i = 0; i < from.length; i++) {
--p[from[i]];
g[from[i]][p[from[i]]][0] = to[i];
g[from[i]][p[from[i]]][1] = w[i];
--p[to[i]];
g[to[i]][p[to[i]]][0] = from[i];
g[to[i]][p[to[i]]][1] = w[i];
}
return g;
}
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 G().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 | ["8 10\n0 1 1\n1 2 5\n2 7 6\n0 3 2\n3 7 3\n0 4 0\n4 5 0\n5 7 2\n0 6 0\n6 7 7"] | 1 second | ["32\n3\n0 3 7"] | null | Java 8 | standard input | [
"dfs and similar",
"shortest paths"
] | f5e23ee7d82a91b4f1a2cb301e59d8ec | The first line of input contains integer N — the number of cities in Bubbleland and integer M — the number of roads in this country. Cities are enumerated from 0 to N - 1, with city 0 being Beergrade, and city N - 1 being Beerburg. Each of the following M lines contains three integers a, b (a ≠ b) and len. These numbers indicate that there is a bidirectional road between cities a and b with length len. 2 ≤ N ≤ 105 1 ≤ M ≤ 105 0 ≤ len ≤ 9 There is at most one road between two cities | 2,200 | The first line of output should contain minimal time needed to go from Beergrade to Beerburg. The second line of the output should contain the number of cities on the path from Beergrade to Beerburg that takes minimal time. The third line of output should contain the numbers of cities on this path in the order they are visited, separated by spaces. | standard output | |
PASSED | 84d55e998f802160596d7cfbd81d6faa | train_002.jsonl | 1441526400 | People in BubbleLand like to drink beer. Little do you know, beer here is so good and strong that every time you drink it your speed goes 10 times slower than before you drank it.Birko lives in city Beergrade, but wants to go to city Beerburg. You are given a road map of BubbleLand and you need to find the fastest way for him. When he starts his journey in Beergrade his speed is 1. When he comes to a new city he always tries a glass of local beer, which divides his speed by 10. The question here is what the minimal time for him to reach Beerburg is. If there are several paths with the same minimal time, pick the one that has least roads on it. If there is still more than one path, pick any.It is guaranteed that there will be at least one path from Beergrade to Beerburg. | 256 megabytes | import java.util.LinkedList;
import java.util.Arrays;
import java.util.ArrayList;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.io.BufferedReader;
import java.util.Collection;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Comparator;
import java.util.Queue;
import java.io.IOException;
import java.util.StringTokenizer;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Reader in = new Reader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskG solver = new TaskG();
solver.solve(1, in, out);
out.close();
}
}
class TaskG {
class Edge {
int b, e;
int len;
Edge(int q, int w, int qw) {
b = q; e = w;
len = qw;
}
}
ArrayList<Edge>[] r;
int[] w;
boolean[] was;
int[] atime;
void dfszero(int q, Queue<Integer> qu)
{
qu.add(q);
w[q] = 1;
for (Edge rr : r[q]) {
if (w[rr.e] == 0 && rr.len == 0) {
dfszero(rr.e, qu);
}
}
}
public void solve(int testNumber, Reader in, PrintWriter out) {
int n = in.nextInt();
r = new ArrayList[n];
w = new int[n];
for (int i = 0; i < n; i++) r[i] = new ArrayList<>();
int m = in.nextInt();
for (int i = 0; i < m; i++) {
int a = in.nextInt();
int b = in.nextInt();
int len = in.nextInt();
r[a].add(new Edge(a, b, len));
r[b].add(new Edge(b, a, len));
}
Queue<Integer> qu = new LinkedList<>();
dfszero(n - 1, qu);
while(!qu.isEmpty()) {
int q = qu.poll();
for (Edge rr : r[q]) {
if (w[rr.e] == 0) {
w[rr.e] = w[q] + 1;
qu.add(rr.e);
}
}
}
int d = w[0] - 1;
atime = new int[n];
Arrays.fill(atime, -1);
if (d != 0) {
boolean[] w2 = new boolean[n];
ArrayList<Edge>[] r2 = new ArrayList[n];
for (int i = 0; i < n; i++) r2[i] = new ArrayList<>();
qu.add(0);
w2[0] = true;
while (!qu.isEmpty()) {
int q = qu.poll();
for (Edge rr : r[q]) {
if (!w2[rr.e] && w[rr.b] == w[rr.e] + 1) {
w2[rr.e] = true;
qu.add(rr.e);
}
if (w[rr.b] == w[rr.e] + 1) {
r2[rr.e].add(new Edge(rr.e, rr.b, rr.len));
}
}
}
ArrayList<Edge>[] ed = new ArrayList[d + 1];
for (int i = 1; i <= d; i++) ed[i] = new ArrayList<>();
for (int i = 0; i < n; i++) {
for (Edge rr : r2[i]) {
if (w[rr.b] == w[rr.e] - 1) ed[w[rr.b]].add(rr);
}
}
was = new boolean[n];
Collections.sort(ed[1], (o1, o2) -> o1.len - o2.len);
int ll = ed[1].get(0).len;
for (Edge rr : ed[1]) {
if (rr.len != ll) break;
was[rr.b] = was[rr.e] = true;
}
atime[1] = ll;
for (int dd = 2; dd <= d; dd++) {
Collections.sort(ed[dd], (o1, o2) -> (was[o1.b] && was[o2.b]) ? o1.len - o2.len : (was[o1.b] ? -1 : (was[o2.b] ? 1 : o1.len - o2.len)));
atime[dd] = ed[dd].get(0).len;
for (Edge rr : ed[dd]) {
if (!was[rr.b] || rr.len != atime[dd]) break;
was[rr.e] = true;
}
}
}
ArrayList<Edge>[] newr = new ArrayList[n];
for (int i = 0; i < n; i++) newr[i] = new ArrayList<>();
for (int i = 0; i < n; i++) {
for (Edge rr : r[i]) {
if (w[rr.b] == 1 && w[rr.e] == 1 && rr.len == 0) {
newr[rr.b].add(rr);
}
if (w[rr.b] == w[rr.e] - 1 && (d == 0 || rr.len == atime[w[rr.b]])) {
newr[rr.b].add(rr);
}
}
}
Queue<Integer> newq = new LinkedList<>();
int[] back = new int[n];
newq.add(n - 1);
back[n - 1] = -1;
while (!newq.isEmpty()) {
int q = newq.poll();
for (Edge rr : newr[q]) {
if (back[rr.e] == 0) {
back[rr.e] = rr.b;
newq.add(rr.e);
}
}
}
int[] ans = new int[n];
int al = 0;
int q = 0;
while (q != -1) {
ans[al++] = q;
q = back[q];
}
if (d == 0) out.print(0); else
for (int i = 1; i <= d; i++) out.print(atime[i]);
out.println();
out.println(al);
for (int i = 0; i < al; i++) out.print(ans[i] + " ");
out.println();
}
}
class Reader {
private BufferedReader in;
private StringTokenizer st;
public Reader(InputStream is) {
in = new BufferedReader(new InputStreamReader(is));
}
public String next() {
try {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
}
| Java | ["8 10\n0 1 1\n1 2 5\n2 7 6\n0 3 2\n3 7 3\n0 4 0\n4 5 0\n5 7 2\n0 6 0\n6 7 7"] | 1 second | ["32\n3\n0 3 7"] | null | Java 8 | standard input | [
"dfs and similar",
"shortest paths"
] | f5e23ee7d82a91b4f1a2cb301e59d8ec | The first line of input contains integer N — the number of cities in Bubbleland and integer M — the number of roads in this country. Cities are enumerated from 0 to N - 1, with city 0 being Beergrade, and city N - 1 being Beerburg. Each of the following M lines contains three integers a, b (a ≠ b) and len. These numbers indicate that there is a bidirectional road between cities a and b with length len. 2 ≤ N ≤ 105 1 ≤ M ≤ 105 0 ≤ len ≤ 9 There is at most one road between two cities | 2,200 | The first line of output should contain minimal time needed to go from Beergrade to Beerburg. The second line of the output should contain the number of cities on the path from Beergrade to Beerburg that takes minimal time. The third line of output should contain the numbers of cities on this path in the order they are visited, separated by spaces. | standard output | |
PASSED | eeeb6df95301a77c190ee055b321c217 | train_002.jsonl | 1441526400 | People in BubbleLand like to drink beer. Little do you know, beer here is so good and strong that every time you drink it your speed goes 10 times slower than before you drank it.Birko lives in city Beergrade, but wants to go to city Beerburg. You are given a road map of BubbleLand and you need to find the fastest way for him. When he starts his journey in Beergrade his speed is 1. When he comes to a new city he always tries a glass of local beer, which divides his speed by 10. The question here is what the minimal time for him to reach Beerburg is. If there are several paths with the same minimal time, pick the one that has least roads on it. If there is still more than one path, pick any.It is guaranteed that there will be at least one path from Beergrade to Beerburg. | 256 megabytes | import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.HashMap;
import java.util.Comparator;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.AbstractCollection;
import java.util.LinkedList;
import java.util.HashSet;
import java.util.Collection;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Set;
import java.util.TreeSet;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Andrey Rechitsky (arechitsky@gmail.com)
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskG solver = new TaskG();
solver.solve(1, in, out);
out.close();
}
}
class TaskG {
int inf = 10000000;
public void solve(int testNumber, FastScanner in, FastPrinter out) {
int n = in.nextInt();
int m = in.nextInt();
final HashMap<Integer, Integer> []adj = new HashMap[n];
for (int i = 0; i < n; i++) {
adj[i] = new HashMap<Integer, Integer>();
}
for (int i = 0; i < m; i++) {
int u = in.nextInt();
int v = in.nextInt();
int l = in.nextInt();
adj[u].put(v, l);
adj[v].put(u, l);
}
boolean []vis = new boolean[n];
vis[0] = true;
final int[]d1 = new int[n];
Arrays.fill(d1, inf);
final int[]d2 = new int[n];
Arrays.fill(d2, inf);
d2[n-1] = 0;
d1[0] = 0;
LinkedList<Integer> q = new LinkedList<Integer>();
q.add(0);
vis[0] = true;
while (!q.isEmpty()){
int cur = q.poll();
for (int next:adj[cur].keySet()){
if (vis[next]) continue;
vis[next] = true;
d1[next] = d1[cur]+1;
q.add(next);
}
}
Arrays.fill(vis, false);
vis[n-1] = true;
q.add(n-1);
final int []next2 = new int[n];
next2[n-1] = -1;
while (!q.isEmpty()){
int cur = q.poll();
for (int next:adj[cur].keySet()){
if (adj[cur].get(next)!=0) continue;
if (vis[next]) continue;
vis[next] = true;
d2[next] = d2[cur]+1;
next2[next] = cur;
q.add(next);
}
}
int lans = inf;
for (int i = 0; i < n; i++) {
if (d2[i]==inf) continue;
lans = Math.min(lans, d1[i]);
}
HashSet<Integer> []levels = new HashSet[lans+1];
for (int i = 0; i < lans+1; i++) {
levels[i] = new HashSet<Integer>();
}
for (int i = 0; i < n; i++) {
if(d1[i]>lans) continue;
levels[d1[i]].add(i);
}
final int []next = new int[n];
next[0] = -1;
final int []order = new int[n];
order[0] = 0;
final Comparator<Integer> part = new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
int e1 = adj[o1].get(next[o1]);
int e2 = adj[o2].get(next[o2]);
return e1==e2?order[next[o1]]-order[next[o2]]:e1-e2;}
};
Comparator<Integer> full = new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
int c = part.compare(o1,o2);
return c==0?o1-o2:c;
}
};
for (int i = 1; i < lans+1; i++) {
for (int cur:levels[i]){
int best = -1;
for (int prev:adj[cur].keySet()){
if (d1[prev]!=i-1) continue;
if (best==-1 || adj[cur].get(prev)<adj[cur].get(best) || adj[cur].get(prev).equals(adj[cur].get(best)) && order[prev]<order[best]) best = prev;
}
next[cur] = best;
}
TreeSet<Integer> tmp = new TreeSet<Integer>(full);
tmp.addAll(levels[i]);
int ind = 0;
int prev = tmp.first();
order[prev] = 0;
for (Integer cur = tmp.higher(prev); cur != null; cur = tmp.higher(cur)){
if (part.compare(prev, cur)!=0) ind++;
order[cur] = ind;
}
}
int best = -1;
for (int c:levels[lans]){
if (d2[c]==inf) continue;
if (best==-1||order[best]>order[c] || order[best]==order[c] && d2[best]>d2[c]) best = c;
}
LinkedList<Integer> a1 = new LinkedList<Integer>();
int c = best;
while (c!=n-1){
c = next2[c];
a1.addFirst(c);
}
c = best;
while (c!=0){
a1.add(c);
c = next[c];
}
a1.add(0);
LinkedList<Integer> a2 = new LinkedList<Integer>();
int prev = a1.poll();
a2.addFirst(prev);
boolean qq = true;
for (int cur:a1){
int val = adj[prev].get(cur);
if (qq && val!=0) qq = false;
if (!qq) out.print(val);
prev = cur;
a2.addFirst(cur);
}
if (qq) out.print(0);
out.printLine();
out.printLine(a2.size());
for (int cur:a2){
out.print(cur);
out.print(' ');
}
out.printLine();
}
}
class FastScanner {
private BufferedReader reader;
private StringTokenizer st;
public FastScanner(InputStream stream) {
this.reader = new BufferedReader(new InputStreamReader(stream));
this.st = new StringTokenizer("");
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
while (!st.hasMoreTokens()) {
st = new StringTokenizer(readLine());
}
return st.nextToken();
}
private String readLine() {
try {
String line = reader.readLine();
if (line == null) throw new InputMismatchException();
return line;
} catch (IOException e) {
throw new InputMismatchException();
}
}
}
class FastPrinter {
private final PrintWriter writer;
public FastPrinter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public void close() {
writer.close();
}
public void printLine(long i) {
writer.println(i);
}
public void printLine() {
writer.println();
}
public void print(long i) {
writer.print(i);
}
public void print(char c) {
writer.print(c);
}
}
| Java | ["8 10\n0 1 1\n1 2 5\n2 7 6\n0 3 2\n3 7 3\n0 4 0\n4 5 0\n5 7 2\n0 6 0\n6 7 7"] | 1 second | ["32\n3\n0 3 7"] | null | Java 8 | standard input | [
"dfs and similar",
"shortest paths"
] | f5e23ee7d82a91b4f1a2cb301e59d8ec | The first line of input contains integer N — the number of cities in Bubbleland and integer M — the number of roads in this country. Cities are enumerated from 0 to N - 1, with city 0 being Beergrade, and city N - 1 being Beerburg. Each of the following M lines contains three integers a, b (a ≠ b) and len. These numbers indicate that there is a bidirectional road between cities a and b with length len. 2 ≤ N ≤ 105 1 ≤ M ≤ 105 0 ≤ len ≤ 9 There is at most one road between two cities | 2,200 | The first line of output should contain minimal time needed to go from Beergrade to Beerburg. The second line of the output should contain the number of cities on the path from Beergrade to Beerburg that takes minimal time. The third line of output should contain the numbers of cities on this path in the order they are visited, separated by spaces. | standard output | |
PASSED | 304c44dfdf8176f0c951ba122cf75714 | train_002.jsonl | 1441526400 | People in BubbleLand like to drink beer. Little do you know, beer here is so good and strong that every time you drink it your speed goes 10 times slower than before you drank it.Birko lives in city Beergrade, but wants to go to city Beerburg. You are given a road map of BubbleLand and you need to find the fastest way for him. When he starts his journey in Beergrade his speed is 1. When he comes to a new city he always tries a glass of local beer, which divides his speed by 10. The question here is what the minimal time for him to reach Beerburg is. If there are several paths with the same minimal time, pick the one that has least roads on it. If there is still more than one path, pick any.It is guaranteed that there will be at least one path from Beergrade to Beerburg. | 256 megabytes | import java.util.*;
import java.io.*;
import java.awt.Point;
import java.math.BigDecimal;
import java.math.BigInteger;
import static java.lang.Math.*;
// Solution is at the bottom of code
public class G implements Runnable{
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
OutputWriter out;
StringTokenizer tok = new StringTokenizer("");
public static void main(String[] args){
new Thread(null, new G(), "", 128 * (1L << 20)).start();
}
/////////////////////////////////////////////////////////////////////
void init() throws FileNotFoundException{
Locale.setDefault(Locale.US);
if (ONLINE_JUDGE){
in = new BufferedReader(new InputStreamReader(System.in));
out = new OutputWriter(System.out);
}else{
in = new BufferedReader(new FileReader("input.txt"));
out = new OutputWriter("output.txt");
}
}
////////////////////////////////////////////////////////////////
long timeBegin, timeEnd;
void time(){
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
void debug(Object... objects){
if (ONLINE_JUDGE){
for (Object o: objects){
System.err.println(o.toString());
}
}
}
/////////////////////////////////////////////////////////////////////
public void run(){
try{
timeBegin = System.currentTimeMillis();
Locale.setDefault(Locale.US);
init();
solve();
out.close();
time();
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
/////////////////////////////////////////////////////////////////////
String delim = " ";
String readString() throws IOException{
while(!tok.hasMoreTokens()){
try{
tok = new StringTokenizer(in.readLine());
}catch (Exception e){
return null;
}
}
return tok.nextToken(delim);
}
String readLine() throws IOException{
return in.readLine();
}
/////////////////////////////////////////////////////////////////
final char NOT_A_SYMBOL = '\0';
char readChar() throws IOException{
int intValue = in.read();
if (intValue == -1){
return NOT_A_SYMBOL;
}
return (char) intValue;
}
char[] readCharArray() throws IOException{
return readLine().toCharArray();
}
/////////////////////////////////////////////////////////////////
int readInt() throws IOException {
return Integer.parseInt(readString());
}
int[] readIntArray(int size) throws IOException {
int[] array = new int[size];
for (int index = 0; index < size; ++index){
array[index] = readInt();
}
return array;
}
int[] readSortedIntArray(int size) throws IOException {
Integer[] array = new Integer[size];
for (int index = 0; index < size; ++index) {
array[index] = readInt();
}
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) {
sortedArray[index] = array[index];
}
return sortedArray;
}
int[] readIntArrayWithDecrease(int size) throws IOException {
int[] array = readIntArray(size);
for (int i = 0; i < size; ++i) {
array[i]--;
}
return array;
}
///////////////////////////////////////////////////////////////////
int[][] readIntMatrix(int rowsCount, int columnsCount) throws IOException {
int[][] matrix = new int[rowsCount][];
for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
matrix[rowIndex] = readIntArray(columnsCount);
}
return matrix;
}
int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) throws IOException {
int[][] matrix = new int[rowsCount][];
for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
matrix[rowIndex] = readIntArrayWithDecrease(columnsCount);
}
return matrix;
}
///////////////////////////////////////////////////////////////////
long readLong() throws IOException{
return Long.parseLong(readString());
}
long[] readLongArray(int size) throws IOException{
long[] array = new long[size];
for (int index = 0; index < size; ++index){
array[index] = readLong();
}
return array;
}
////////////////////////////////////////////////////////////////////
double readDouble() throws IOException{
return Double.parseDouble(readString());
}
double[] readDoubleArray(int size) throws IOException{
double[] array = new double[size];
for (int index = 0; index < size; ++index){
array[index] = readDouble();
}
return array;
}
////////////////////////////////////////////////////////////////////
BigInteger readBigInteger() throws IOException {
return new BigInteger(readString());
}
BigDecimal readBigDecimal() throws IOException {
return new BigDecimal(readString());
}
/////////////////////////////////////////////////////////////////////
Point readPoint() throws IOException{
int x = readInt();
int y = readInt();
return new Point(x, y);
}
Point[] readPointArray(int size) throws IOException{
Point[] array = new Point[size];
for (int index = 0; index < size; ++index){
array[index] = readPoint();
}
return array;
}
/////////////////////////////////////////////////////////////////////
List<Integer>[] readGraph(int vertexNumber, int edgeNumber)
throws IOException{
@SuppressWarnings("unchecked")
List<Integer>[] graph = new List[vertexNumber];
for (int index = 0; index < vertexNumber; ++index){
graph[index] = new ArrayList<Integer>();
}
while (edgeNumber-- > 0){
int from = readInt() - 1;
int to = readInt() - 1;
graph[from].add(to);
graph[to].add(from);
}
return graph;
}
/////////////////////////////////////////////////////////////////////
static class IntIndexPair {
static Comparator<IntIndexPair> increaseComparator = new Comparator<IntIndexPair>() {
@Override
public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) {
int value1 = indexPair1.value;
int value2 = indexPair2.value;
if (value1 != value2) return value1 - value2;
int index1 = indexPair1.index;
int index2 = indexPair2.index;
return index1 - index2;
}
};
static Comparator<IntIndexPair> decreaseComparator = new Comparator<IntIndexPair>() {
@Override
public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) {
int value1 = indexPair1.value;
int value2 = indexPair2.value;
if (value1 != value2) return -(value1 - value2);
int index1 = indexPair1.index;
int index2 = indexPair2.index;
return index1 - index2;
}
};
int value, index;
public IntIndexPair(int value, int index) {
super();
this.value = value;
this.index = index;
}
public int getRealIndex() {
return index + 1;
}
}
IntIndexPair[] readIntIndexArray(int size) throws IOException {
IntIndexPair[] array = new IntIndexPair[size];
for (int index = 0; index < size; ++index) {
array[index] = new IntIndexPair(readInt(), index);
}
return array;
}
/////////////////////////////////////////////////////////////////////
static class OutputWriter extends PrintWriter {
final int DEFAULT_PRECISION = 12;
protected int precision;
protected String format, formatWithSpace;
{
precision = DEFAULT_PRECISION;
format = createFormat(precision);
formatWithSpace = format + " ";
}
public OutputWriter(OutputStream out) {
super(out);
}
public OutputWriter(String fileName) throws FileNotFoundException {
super(fileName);
}
public int getPrecision() {
return precision;
}
public void setPrecision(int precision) {
precision = max(0, precision);
this.precision = precision;
format = createFormat(precision);
formatWithSpace = format + " ";
}
private String createFormat(int precision){
return "%." + precision + "f";
}
@Override
public void print(double d){
printf(format, d);
}
public void printWithSpace(double d){
printf(formatWithSpace, d);
}
public void printAll(double...d){
for (int i = 0; i < d.length - 1; ++i){
printWithSpace(d[i]);
}
print(d[d.length - 1]);
}
@Override
public void println(double d){
printlnAll(d);
}
public void printlnAll(double... d){
printAll(d);
println();
}
}
/////////////////////////////////////////////////////////////////////
static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
static final int[][] steps8 = {
{-1, 0}, {1, 0}, {0, -1}, {0, 1},
{-1, -1}, {1, 1}, {1, -1}, {-1, 1}
};
static final boolean check(int index, int lim){
return (0 <= index && index < lim);
}
/////////////////////////////////////////////////////////////////////
static final boolean checkBit(int mask, int bit){
return (mask & (1 << bit)) != 0;
}
/////////////////////////////////////////////////////////////////////
static final long getSum(int[] array) {
long sum = 0;
for (int value: array) {
sum += value;
}
return sum;
}
static final Point getMinMax(int[] array) {
int min = array[0];
int max = array[0];
for (int index = 0, size = array.length; index < size; ++index, ++index) {
int value = array[index];
if (index == size - 1) {
min = min(min, value);
max = max(max, value);
} else {
int otherValue = array[index + 1];
if (value <= otherValue) {
min = min(min, value);
max = max(max, otherValue);
} else {
min = min(min, otherValue);
max = max(max, value);
}
}
}
return new Point(min, max);
}
/////////////////////////////////////////////////////////////////////
class Edge {
int to;
int digit;
public Edge(int to, int digit) {
super();
this.to = to;
this.digit = digit;
}
}
List<Edge>[] graph;
void solve() throws IOException {
int n = readInt();
int m = readInt();
this.graph = new List[n];
for (int i = 0; i < n; ++i) {
graph[i] = new ArrayList<Edge>();
}
for (int i = 0; i < m; ++i) {
int from = readInt();
int to = readInt();
int digit = readInt();
graph[from].add(new Edge(to, digit));
graph[to].add(new Edge(from, digit));
}
int start = 0;
int end = n - 1;
boolean[] isZeroAdjacents = new boolean[n];
int[] zeroDistances = zeroBfs(end);
for (int i = 0; i < n; ++i) {
if (zeroDistances[i] != -1) {
isZeroAdjacents[i] = true;
}
}
int[] distances = bfs(start);
int minZeroDistance = n;
for (int i = 0; i < n; ++i) {
if (isZeroAdjacents[i]) {
minZeroDistance = min(minZeroDistance, distances[i]);
}
}
int[] zeroRoots = new int[n];
Arrays.fill(zeroRoots, -1);
int[] parents = new int[n];
Arrays.fill(parents, -1);
List<Integer> ansTime = new ArrayList<Integer>();
boolean[] used = new boolean[n];
List<Integer> queue = new ArrayList<Integer>();
for (int i = 0; i < n; ++i) {
if (isZeroAdjacents[i] && distances[i] == minZeroDistance) {
used[i] = true;
queue.add(i);
zeroRoots[i] = i;
}
}
int curStart = 0, curEnd = queue.size();
for (int curDistance = minZeroDistance; curDistance > 0; --curDistance) {
int minDigit = 10;
for (int index = curStart; index < curEnd; ++index) {
int from = queue.get(index);
for (Edge e : graph[from]) {
int to = e.to;
if (!used[to] && distances[to] < distances[from]) {
minDigit = min(minDigit, e.digit);
}
}
}
ansTime.add(minDigit);
for (int index = curStart; index < curEnd; ++index) {
int from = queue.get(index);
for (Edge e : graph[from]) {
int to = e.to;
if (distances[to] < distances[from] && e.digit == minDigit) {
if (!used[to] || zeroDistances[zeroRoots[to]] > zeroDistances[zeroRoots[from]]) {
parents[to] = from;
used[to] = true;
zeroRoots[to] = zeroRoots[from];
queue.add(to);
}
}
}
}
curStart = curEnd;
curEnd = queue.size();
}
if (ansTime.size() > 0) {
for (int digit : ansTime) {
out.print(digit);
}
out.println();
} else {
out.println(0);
}
List<Integer> way = new ArrayList<Integer>();
for (int cur = start; cur != -1; cur = parents[cur]) {
way.add(cur);
}
parents = parentZeroBfs(end);
int last = way.remove(way.size() - 1);
for (int cur = last; cur != -1; cur = parents[cur]) {
way.add(cur);
}
out.println(way.size());
for (int v : way) {
out.print(v + " ");
}
out.println();
}
int[] zeroBfs(int start) {
boolean[] used = new boolean[graph.length];
Queue<Integer> queue = new ArrayDeque<Integer>();
int[] distances = new int[graph.length];
Arrays.fill(distances, -1);
distances[start] = 0;
used[start] = true;
queue.add(start);
while (queue.size() > 0) {
int from = queue.poll();
for (Edge e : graph[from]) {
int to = e.to;
if (!used[to] && e.digit == 0) {
used[to] = true;
distances[to] = distances[from] + 1;
queue.add(to);
}
}
}
return distances;
}
int[] bfs(int start) {
boolean[] used = new boolean[graph.length];
int[] distances = new int[graph.length];
Queue<Integer> queue = new ArrayDeque<Integer>();
used[start] = true;
distances[start] = 0;
queue.add(start);
while (queue.size() > 0) {
int from = queue.poll();
for (Edge e : graph[from]) {
int to = e.to;
if (!used[to]) {
used[to] = true;
distances[to] = distances[from] + 1;
queue.add(to);
}
}
}
return distances;
}
int[] parentZeroBfs(int start) {
int[] parents = new int[graph.length];
Arrays.fill(parents, -1);
boolean[] used = new boolean[graph.length];
Queue<Integer> queue = new ArrayDeque<Integer>();
used[start] = true;
queue.add(start);
while (queue.size() > 0) {
int from = queue.poll();
for (Edge e : graph[from]) {
int to = e.to;
if (!used[to] && e.digit == 0) {
used[to] = true;
parents[to] = from;
queue.add(to);
}
}
}
return parents;
}
}
| Java | ["8 10\n0 1 1\n1 2 5\n2 7 6\n0 3 2\n3 7 3\n0 4 0\n4 5 0\n5 7 2\n0 6 0\n6 7 7"] | 1 second | ["32\n3\n0 3 7"] | null | Java 8 | standard input | [
"dfs and similar",
"shortest paths"
] | f5e23ee7d82a91b4f1a2cb301e59d8ec | The first line of input contains integer N — the number of cities in Bubbleland and integer M — the number of roads in this country. Cities are enumerated from 0 to N - 1, with city 0 being Beergrade, and city N - 1 being Beerburg. Each of the following M lines contains three integers a, b (a ≠ b) and len. These numbers indicate that there is a bidirectional road between cities a and b with length len. 2 ≤ N ≤ 105 1 ≤ M ≤ 105 0 ≤ len ≤ 9 There is at most one road between two cities | 2,200 | The first line of output should contain minimal time needed to go from Beergrade to Beerburg. The second line of the output should contain the number of cities on the path from Beergrade to Beerburg that takes minimal time. The third line of output should contain the numbers of cities on this path in the order they are visited, separated by spaces. | standard output | |
PASSED | 2e043601ea1922a553e6bcd2b15301aa | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int t = in.nextInt();
while (t-- > 0) {
int N = in.nextInt();
char a[] = in.next().toCharArray();
int count = 0;
Items items[] = new Items[N];
for (int i = 0; i < N; i++) {
items[i] = new Items(a[i] - '0', i);
}
Arrays.sort(items);
int painted[] = new int[N];
int lastIndex = -1;
int maxValue = -1;
int lastValueThatCanBePainted = 10;
for (int i = items[0].index - 1; i >= 0; i--) {
lastValueThatCanBePainted = Math.min(lastValueThatCanBePainted, a[i] - '0');
}
for (int i = 0; i < N; i++) {
for (int j = lastIndex + 1; j < items[i].index; j++) {
lastValueThatCanBePainted = Math.min(lastValueThatCanBePainted, a[j] - '0');
}
if (items[i].value > lastValueThatCanBePainted) {
break;
}
if (items[i].index > lastIndex && items[i].value >= maxValue) {
count++;
painted[items[i].index] = 1;
lastIndex = items[i].index;
maxValue = items[i].value;
}
}
lastIndex = -1;
for (int i = 0; i < N; i++) {
if (painted[items[i].index] == 0) {
if (items[i].index > lastIndex && items[i].value >= maxValue) {
count++;
painted[items[i].index] = 2;
lastIndex = items[i].index;
maxValue = items[i].value;
} else {
break;
}
}
}
if (count == N) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < N; i++) {
stringBuilder.append(painted[i]);
}
out.printLine(stringBuilder);
} else {
out.printLine("-");
}
}
}
class Items implements Comparable<Items> {
int value;
int index;
public Items(int value, int index) {
this.value = value;
this.index = index;
}
public int compareTo(Items a) {
if (a.value != this.value) {
return this.value - a.value;
}
return this.index - a.index;
}
}
}
static class InputReader {
BufferedReader in;
StringTokenizer tokenizer = null;
public InputReader(InputStream inputStream) {
in = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() {
try {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(in.readLine());
}
return tokenizer.nextToken();
} catch (IOException e) {
return null;
}
}
public int nextInt() {
return Integer.parseInt(next());
}
}
static class OutputWriter {
PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
}
| Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | c6ce65987bbfc3de377f18c3308f4a1c | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static InputReader in = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
static int oo = (int)1e9;
static int mod = 1000000007;
public static void main(String[] args) throws IOException {
int tests = in.nextInt();
test: for(int test = 0; test < tests; ++test) {
int n = in.nextInt();
char[] a = in.readString().toCharArray();
char[] ans = new char[n];
start: for(int start = 0; start < 10; ++start) {
int cur1 = 0, cur2 = start;
for(int i = 0; i < n; ++i) {
int c = a[i] - '0';
if(c >= cur2) {
ans[i] = '2';
cur2 = c;
}
else if(c >= cur1 && c <= start) {
ans[i] = '1';
cur1 = c;
}
else {
continue start;
}
}
out.println(ans);
continue test;
}
out.println("-");
}
out.close();
}
static class SegmentTree {
int n;
long[] a, seg;
int DEFAULT_VALUE = 0;
public SegmentTree(long[] a, int n) {
super();
this.a = a;
this.n = n;
seg = new long[n * 4 + 1];
build(1, 0, n-1);
}
private long build(int node, int i, int j) {
if(i == j)
return seg[node] = a[i];
long first = build(node * 2, i, (i+j) / 2);
long second = build(node * 2 + 1, (i+j) / 2 + 1, j);
return seg[node] = combine(first, second);
}
long update(int k, long value) {
return update(1, 0, n-1, k, value);
}
private long update(int node, int i, int j, int k, long value) {
if(k < i || k > j)
return seg[node];
if(i == j && j == k) {
a[k] = value;
seg[node] = value;
return value;
}
int m = (i + j) / 2;
long first = update(node * 2, i, m, k, value);
long second = update(node * 2 + 1, m + 1, j, k, value);
return seg[node] = combine(first, second);
}
long query(int l, int r) {
return query(1, 0, n-1, l, r);
}
private long query(int node, int i, int j, int l, int r) {
if(l <= i && j <= r)
return seg[node];
if(j < l || i > r)
return DEFAULT_VALUE;
int m = (i + j) / 2;
long first = query(node * 2, i, m, l, r);
long second = query(node * 2 + 1, m+1, j, l, r);
return combine(first, second);
}
private long combine(long a, long b) {
return a + b;
}
}
static class DisjointSet {
int n;
int[] g;
int[] h;
public DisjointSet(int n) {
super();
this.n = n;
g = new int[n];
h = new int[n];
for(int i = 0; i < n; ++i) {
g[i] = i;
h[i] = 1;
}
}
int find(int x) {
if(g[x] == x)
return x;
return g[x] = find(g[x]);
}
void union(int x, int y) {
x = find(x); y = find(y);
if(x == y)
return;
if(h[x] >= h[y]) {
g[y] = x;
if(h[x] == h[y])
h[x]++;
}
else {
g[x] = y;
}
}
}
static int[] getPi(char[] a) {
int m = a.length;
int j = 0;
int[] pi = new int[m];
for(int i = 1; i < m; ++i) {
while(j > 0 && a[i] != a[j])
j = pi[j-1];
if(a[i] == a[j]) {
pi[i] = j + 1;
j++;
}
}
return pi;
}
static long lcm(long a, long b) {
return a * b / gcd(a, b);
}
static boolean nextPermutation(int[] a) {
for(int i = a.length - 2; i >= 0; --i) {
if(a[i] < a[i+1]) {
for(int j = a.length - 1; ; --j) {
if(a[i] < a[j]) {
int t = a[i];
a[i] = a[j];
a[j] = t;
for(i++, j = a.length - 1; i < j; ++i, --j) {
t = a[i];
a[i] = a[j];
a[j] = t;
}
return true;
}
}
}
}
return false;
}
static void shuffle(int[] a) {
Random r = new Random();
for(int i = a.length - 1; i > 0; --i) {
int si = r.nextInt(i);
int t = a[si];
a[si] = a[i];
a[i] = t;
}
}
static void shuffle(long[] a) {
Random r = new Random();
for(int i = a.length - 1; i > 0; --i) {
int si = r.nextInt(i);
long t = a[si];
a[si] = a[i];
a[i] = t;
}
}
static int lower_bound(int[] a, int n, int k) {
int s = 0;
int e = n;
int m;
while (e - s > 0) {
m = (s + e) / 2;
if (a[m] < k)
s = m + 1;
else
e = m;
}
return e;
}
static int lower_bound(long[] a, int n, long k) {
int s = 0;
int e = n;
int m;
while (e - s > 0) {
m = (s + e) / 2;
if (a[m] < k)
s = m + 1;
else
e = m;
}
return e;
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
static class Pair implements Comparable<Pair> {
int first, second;
public Pair(int first, int second) {
super();
this.first = first;
this.second = second;
}
@Override
public int compareTo(Pair o) {
return this.first != o.first ? this.first - o.first : this.second - o.second;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + first;
result = prime * result + second;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pair other = (Pair) obj;
if (first != other.first)
return false;
if (second != other.second)
return false;
return true;
}
}
}
class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
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 {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = 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 (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public 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 | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | 34ddccc825167fde4f874f85bbeac747 | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static InputReader in = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
static int oo = (int)1e9;
static int mod = 1000000007;
public static void main(String[] args) throws IOException {
int t = in.nextInt();
out:
while(t --> 0) {
int n = in.nextInt();
char[] ca = in.readString().toCharArray();
int[] a = new int[n];
for(int i = 0; i < n; ++i)
a[i] = ca[i] - '0';
int[] min = new int[n];
for(int i = n-1; i >= 0; --i) {
min[i] = i == n-1 ? a[i] : Math.min(min[i+1], a[i]);
}
int[] max = new int[n];
for(int i = 0; i < n; ++i) {
max[i] = i == 0 ? a[i] : Math.max(max[i-1], a[i]);
}
int[] ans = new int[n];
for(int i = 0; i < n; ++i) {
if(max[i] > a[i]) {
ans[i] = 1;
}
}
for(int i = n-1; i >= 0; --i) {
if(min[i] < a[i]) {
if(ans[i] == 1) {
out.println("-");
continue out;
}
ans[i] = 2;
}
}
ArrayList<Integer> first = new ArrayList<>();
ArrayList<Integer> second = new ArrayList<>();
for(int i = 0; i < n; ++i) {
if(ans[i] == 1)
first.add(a[i]);
else if(ans[i] == 2)
second.add(a[i]);
else {
if(!second.isEmpty()) {
ans[i] = 2;
second.add(a[i]);
}
else {
ans[i] = 1;
first.add(a[i]);
}
}
}
first.addAll(second);
for(int i = 0; i < n-1; ++i) {
if(first.get(i) > first.get(i+1)) {
out.println("-");
continue out;
}
}
for(int x : ans)
out.print(x);
out.println();
}
out.close();
}
static class SegmentTree {
int n;
long[] a, seg;
int DEFAULT_VALUE = 0;
public SegmentTree(long[] a, int n) {
super();
this.a = a;
this.n = n;
seg = new long[n * 4 + 1];
build(1, 0, n-1);
}
private long build(int node, int i, int j) {
if(i == j)
return seg[node] = a[i];
long first = build(node * 2, i, (i+j) / 2);
long second = build(node * 2 + 1, (i+j) / 2 + 1, j);
return seg[node] = combine(first, second);
}
long update(int k, long value) {
return update(1, 0, n-1, k, value);
}
private long update(int node, int i, int j, int k, long value) {
if(k < i || k > j)
return seg[node];
if(i == j && j == k) {
a[k] = value;
seg[node] = value;
return value;
}
int m = (i + j) / 2;
long first = update(node * 2, i, m, k, value);
long second = update(node * 2 + 1, m + 1, j, k, value);
return seg[node] = combine(first, second);
}
long query(int l, int r) {
return query(1, 0, n-1, l, r);
}
private long query(int node, int i, int j, int l, int r) {
if(l <= i && j <= r)
return seg[node];
if(j < l || i > r)
return DEFAULT_VALUE;
int m = (i + j) / 2;
long first = query(node * 2, i, m, l, r);
long second = query(node * 2 + 1, m+1, j, l, r);
return combine(first, second);
}
private long combine(long a, long b) {
return a + b;
}
}
static class DisjointSet {
int n;
int[] g;
int[] h;
public DisjointSet(int n) {
super();
this.n = n;
g = new int[n];
h = new int[n];
for(int i = 0; i < n; ++i) {
g[i] = i;
h[i] = 1;
}
}
int find(int x) {
if(g[x] == x)
return x;
return g[x] = find(g[x]);
}
void union(int x, int y) {
x = find(x); y = find(y);
if(x == y)
return;
if(h[x] >= h[y]) {
g[y] = x;
if(h[x] == h[y])
h[x]++;
}
else {
g[x] = y;
}
}
}
static int[] getPi(char[] a) {
int m = a.length;
int j = 0;
int[] pi = new int[m];
for(int i = 1; i < m; ++i) {
while(j > 0 && a[i] != a[j])
j = pi[j-1];
if(a[i] == a[j]) {
pi[i] = j + 1;
j++;
}
}
return pi;
}
static long lcm(long a, long b) {
return a * b / gcd(a, b);
}
static boolean nextPermutation(int[] a) {
for(int i = a.length - 2; i >= 0; --i) {
if(a[i] < a[i+1]) {
for(int j = a.length - 1; ; --j) {
if(a[i] < a[j]) {
int t = a[i];
a[i] = a[j];
a[j] = t;
for(i++, j = a.length - 1; i < j; ++i, --j) {
t = a[i];
a[i] = a[j];
a[j] = t;
}
return true;
}
}
}
}
return false;
}
static void shuffle(int[] a) {
Random r = new Random();
for(int i = a.length - 1; i > 0; --i) {
int si = r.nextInt(i);
int t = a[si];
a[si] = a[i];
a[i] = t;
}
}
static void shuffle(long[] a) {
Random r = new Random();
for(int i = a.length - 1; i > 0; --i) {
int si = r.nextInt(i);
long t = a[si];
a[si] = a[i];
a[i] = t;
}
}
static int lower_bound(int[] a, int n, int k) {
int s = 0;
int e = n;
int m;
while (e - s > 0) {
m = (s + e) / 2;
if (a[m] < k)
s = m + 1;
else
e = m;
}
return e;
}
static int lower_bound(long[] a, int n, long k) {
int s = 0;
int e = n;
int m;
while (e - s > 0) {
m = (s + e) / 2;
if (a[m] < k)
s = m + 1;
else
e = m;
}
return e;
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
static class Pair implements Comparable<Pair> {
int first, second;
public Pair(int first, int second) {
super();
this.first = first;
this.second = second;
}
@Override
public int compareTo(Pair o) {
return this.first != o.first ? this.first - o.first : this.second - o.second;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + first;
result = prime * result + second;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pair other = (Pair) obj;
if (first != other.first)
return false;
if (second != other.second)
return false;
return true;
}
}
}
class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
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 {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = 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 (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public 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 | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | 124c4d311df85981a2c3d640c1bd0ed2 | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author keyur_jain
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskC solver = new TaskC();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
String s = in.nextString();
for (int x = 0; x <= 9; x++) {
boolean foundGreaterThanX = false;
int[] coloring = new int[n];
for (int i = 0; i < n; i++) {
int val = Character.getNumericValue(s.charAt(i));
if (val < x) {
coloring[i] = 1;
} else if (val > x) {
coloring[i] = 2;
foundGreaterThanX = true;
} else {
if (foundGreaterThanX) {
coloring[i] = 1;
} else {
coloring[i] = 2;
}
}
}
boolean validColoring = true;
for (int color = 1; color <= 2; color++) {
int prv = -1;
for (int i = 0; i < n; i++) {
if (coloring[i] != color)
continue;
int val = Character.getNumericValue(s.charAt(i));
if (val < prv) {
validColoring = false;
}
prv = val;
}
}
if (validColoring) {
for (int i = 0; i < n; i++) {
out.print(coloring[i]);
}
out.println();
return;
}
}
out.println("-");
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return nextString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println() {
writer.println();
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void print(int i) {
writer.print(i);
}
}
}
| Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | d1fc37f8aaef6b1b6110cd5748fcbca5 | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author null
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Input in = new Input(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, Input in, PrintWriter out) {
try {
int kt = in.readInt();
for (int nt = 0; nt < kt; nt++) {
int n = in.readInt();
char[] s = in.readWord().toCharArray();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = s[i] - '0';
}
StringBuilder ans = null;
for (int x = 0; x <= 9 && ans == null; x++) {
ans = new StringBuilder(n);
int f = x;
int v = 0;
for (int i = 0; i < n; i++) {
if (a[i] < f) {
if (a[i] < v || a[i] > x) {
ans = null;
break;
} else {
v = a[i];
ans.append('1');
}
} else {
f = a[i];
ans.append('2');
}
}
}
out.println((ans != null) ? ans.toString() : '-');
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
static class Input {
public final BufferedReader reader;
private String line = "";
private int pos = 0;
public Input(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
}
private boolean isSpace(char ch) {
return ch <= 32;
}
public String readWord() throws IOException {
skip();
int start = pos;
while (pos < line.length() && !isSpace(line.charAt(pos))) {
pos++;
}
return line.substring(start, pos);
}
public int readInt() throws IOException {
return Integer.parseInt(readWord());
}
private void skip() throws IOException {
while (true) {
if (pos >= line.length()) {
line = reader.readLine();
pos = 0;
}
while (pos < line.length() && isSpace(line.charAt(pos))) {
pos++;
}
if (pos < line.length()) {
return;
}
}
}
}
}
| Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | 6da64d7b8acd1df5ef56fdf9f44fd507 | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 256 megabytes | import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
private static int getPivotIndex(String s, int pivotNum) {
for (int k = s.length() - 1; k >= 0; k--)
if (s.charAt(k) - '0' < pivotNum) return k;
return -1;
}
private static String getResultWithPivotNum(String s, int pivotNum) {
StringBuilder result = new StringBuilder();
int pivotIndex = getPivotIndex(s, pivotNum);
int lastOne = -1, lastTwo = -1;
for (int j = 0; j < s.length(); j++) {
int currNum = s.charAt(j) - '0';
if (currNum < pivotNum || (currNum == pivotNum && j > pivotIndex)) {
if (lastOne == -1 || !(lastOne > currNum))
lastOne = currNum;
else
return "-";
result.append("1");
} else if (currNum > pivotNum || (currNum == pivotNum && j < pivotIndex)) {
if (lastTwo == -1 || !(lastTwo > currNum))
lastTwo = currNum;
else
return "-";
result.append("2");
}
}
return result.toString();
}
private static String getResult(String s) {
for (int pivotNum = 0; pivotNum <= 9; pivotNum++) {
String res = getResultWithPivotNum(s, pivotNum);
if (!res.equals("-"))
return res;
}
return "-";
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
for (int i = 0; i < t; i++) {
scanner.nextInt();
System.out.println(getResult(scanner.next()));
}
}
} | Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | 1785b7add2528095419e9d8a239c21a4 | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Codechef
{ static PrintWriter out=new PrintWriter(System.out);static FastScanner in = new FastScanner(System.in);static class FastScanner {BufferedReader br;StringTokenizer stok;FastScanner(InputStream is) {br = new BufferedReader(new InputStreamReader(is));}
String next() throws IOException {while (stok == null || !stok.hasMoreTokens()) {String s = br.readLine();if (s == null) {return null;}
stok = new StringTokenizer(s);}return stok.nextToken();}
int ni() throws IOException {return Integer.parseInt(next());}long nl() throws IOException {return Long.parseLong(next());}double nd() throws IOException {return Double.parseDouble(next());}char nc() throws IOException {return (char) (br.read());}String ns() throws IOException {return br.readLine();}
int[] nia(int n) throws IOException{int a[] = new int[n];for (int i = 0; i < n; i++)a[i] = ni();return a;}long[] nla(int n) throws IOException {long a[] = new long[n];for (int i = 0; i < n; i++)a[i] = nl();return a;}
double[] nda(int n)throws IOException {double a[] = new double[n];for (int i = 0; i < n; i++)a[i] = nd();return a;}int [][] imat(int n,int m) throws IOException{int mat[][]=new int[n][m];for(int i=0;i<n;i++){for(int j=0;j<m;j++)mat[i][j]=ni();}return mat;}
}
static long mod=Long.MAX_VALUE;
public static void main (String[] args) throws java.lang.Exception
{ int i,j;
HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>();
/* if(hm.containsKey(z))
hm.put(z,hm.get(z)+1);
else
hm.put(z,1);
*/
ArrayList<Integer> arr=new ArrayList<Integer>();
HashSet<Integer> set=new HashSet<Integer>();
PriorityQueue<Integer> pq=new PriorityQueue<Integer>();
int t=in.ni();
while(t--!=0)
{
int n=in.ni();
String s=in.next();
int index=-1;
for(i=0;i<=9;i++)
{ ArrayList<Integer> arr1=new ArrayList<>();
ArrayList<Integer> arr2=new ArrayList<>();
int max=-1;
for(j=0;j<n;j++)
{
if(s.charAt(j)-'0'<i )
arr1.add(s.charAt(j)-'0');
else if(s.charAt(j)-'0'==i && max!=-1)
arr1.add(s.charAt(j)-'0');
else
{ arr2.add(s.charAt(j)-'0');
if(s.charAt(j)-'0'>i)
max=1;
}
}
int flag=0;
for(j=0;j<arr1.size()-1;j++)
if(arr1.get(j)>arr1.get(j+1))
{flag=-1;break;}
for(j=0;j<arr2.size()-1;j++)
if(arr2.get(j)>arr2.get(j+1))
{flag=-1;break;}
if(flag==0)
{index=i;break;}
}
if(index==-1)
out.println("-");
else
{ int max=-1;
for(i=0;i<n;i++)
{
if(s.charAt(i)-'0'<index )
out.print(1);
else if(s.charAt(i)-'0'==index && max!=-1)
out.print(1);
else
{ out.print(2);
if(s.charAt(i)-'0'>index)
max=1;
}
}
out.println();
}
}
out.close();
}
static class pair implements Comparable<pair>{
int x, y;
public pair(int x, int y){this.x = x; this.y = y;}
@Override
public int compareTo(pair arg0)
{ if(x<arg0.x) return -1;
else if(x==arg0.x)
{ if(y<arg0.y) return -1;
else if(y>arg0.y) return 1;
else return 0;
}
else return 1;
}
}
static long gcd(long a,long b)
{ if(b==0)
return a;
return gcd(b,a%b);
}
static long exponent(long a,long n)
{ long ans=1;
while(n!=0)
{ if(n%2==1)
ans=(ans*a)%mod;
a=(a*a)%mod;
n=n>>1;
}
return ans;
}
static int binarySearch(int a[], int item, int low, int high)
{ if (high <= low)
return (item > a[low])? (low + 1): low;
int mid = (low + high)/2;
if(item == a[mid])
return mid+1;
if(item > a[mid])
return binarySearch(a, item, mid+1, high);
return binarySearch(a, item, low, mid-1);
}
static void merge(int arr[], int l, int m, int r) {
int n1 = m - l + 1; int n2 = r - m; int L[] = new int [n1]; int R[] = new int [n2];
for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else{ arr[k] = R[j]; j++; } k++; } while (i < n1){ arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; }
}
static void Sort(int arr[], int l, int r) {if (l < r) { int m = (l+r)/2; Sort(arr, l, m); Sort(arr , m+1, r); merge(arr, l, m, r); } }
static void sort(int a[])
{Sort(a,0,a.length-1);}
} | Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | 61485fdb1808a46e065fb4fb31c349ad | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 256 megabytes | import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.System.exit;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class C {
static void solve() throws Exception {
int tests = scanInt();
test: for (int test = 0; test < tests; test++) {
int n = scanInt();
String s = scanString();
char ans[] = new char[n];
start: for (int start = 0; start < 10; start++) {
int cur1 = 0, cur2 = start;
for (int i = 0; i < n; i++) {
int c = s.charAt(i) - '0';
if (c >= cur2) {
ans[i] = '2';
cur2 = c;
} else if (c >= cur1 && c <= start) {
ans[i] = '1';
cur1 = c;
} else {
continue start;
}
}
out.println(ans);
continue test;
}
out.println('-');
}
}
static int scanInt() throws IOException {
return parseInt(scanString());
}
static long scanLong() throws IOException {
return parseLong(scanString());
}
static String scanString() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
static BufferedReader in;
static PrintWriter out;
static StringTokenizer tok;
public static void main(String[] args) {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
} catch (Throwable e) {
e.printStackTrace();
exit(1);
}
}
} | Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | 9c64a0199c806fd3571df3d8c72eabb2 | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 256 megabytes |
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class C {
public static void main(String[] args) throws Exception {
FastScanner sc = new FastScanner(System.in);
FastPrinter out = new FastPrinter(System.out);
int T = sc.nextInt();
dp = new int[200_000][10][10];
for (int i = 0; i < T; i++) {
new C().run(sc, out);
}
out.close();
}
static int[][][] dp;
int lowC2;
public void run(FastScanner sc, FastPrinter out) throws Exception {
int n = sc.nextInt();
char[] arr = sc.next().toCharArray();
for (lowC2 = 0; lowC2 <= 10; lowC2++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < 10; j++) {
for (int k = 0; k < 10; k++) {
dp[i][j][k] = -1;
}
}
}
int ans = solve(0, 0, 0, arr);
if (ans == 1) {
int c1 = 0;
int c2 = 0;
for (int index = 0; index < n; index++) {
int val = arr[index] - '0';
if (val >= c1 && val <= lowC2 && solve(index + 1, val, c2, arr) == 1) {
c1 = val;
arr[index] = '1';
} else {
c2 = val;
arr[index] = '2';
}
}
out.println(arr);
return;
}
}
out.println('-');
}
private int solve(int index, int c1, int c2, char[] arr) {
if (index == arr.length) return 1;
if (dp[index][c1][c2] == -1) {
int val = arr[index] - '0';
int ans = 2;
if (val >= c1 && val <= lowC2) {
if (solve(index + 1, val, c2, arr) == 1) {
ans = 1;
}
}
if (val >= c2 && val >= lowC2) {
if (solve(index + 1, c1, val, arr) == 1) {
ans = 1;
}
}
dp[index][c1][c2] = ans;
}
return dp[index][c1][c2];
}
public void shuffle(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int r = (int) (Math.random() * arr.length);
if (i != r) {
arr[i] ^= arr[r];
arr[r] ^= arr[i];
arr[i] ^= arr[r];
}
}
}
static class FastScanner {
final private int BUFFER_SIZE = 1 << 10;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public FastScanner() {
this(System.in);
}
public FastScanner(InputStream stream) {
din = new DataInputStream(stream);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastScanner(String fileName) throws IOException {
Path p = Paths.get(fileName);
buffer = Files.readAllBytes(p);
bytesRead = buffer.length;
}
int[] nextIntArray(int N) throws IOException {
int[] arr = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = nextInt();
}
return arr;
}
String nextLine() throws IOException {
int c = read();
while (c != -1 && isEndline(c))
c = read();
if (c == -1) {
return null;
}
StringBuilder res = new StringBuilder();
do {
if (c >= 0) {
res.appendCodePoint(c);
}
c = read();
} while (!isEndline(c));
return res.toString();
}
boolean isEndline(int c) {
return c == '\n' || c == '\r' || c == -1;
}
String next() throws Exception {
int c = readOutSpaces();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
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 {
if (din == null) {
bufferPointer = 0;
bytesRead = -1;
} else {
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++];
}
private int readOutSpaces() throws IOException {
while (true) {
if (bufferPointer == bytesRead) fillBuffer();
int c = buffer[bufferPointer++];
if (!isSpaceChar(c)) {
return c;
}
}
}
public void close() throws IOException {
if (din == null) return;
din.close();
}
public int[][] readGraph(int N, int M, boolean zeroIndexed, boolean bidirectional) throws Exception {
int[][] adj = new int[N][];
int[] numNodes = new int[N];
int[][] input = new int[M][2];
for (int i = 0; i < M; i++) {
int a = nextInt();
int b = nextInt();
if (zeroIndexed) {
a--;
b--;
}
input[i][0] = a;
input[i][1] = b;
numNodes[a]++;
if (bidirectional) numNodes[b]++;
}
for (int i = 0; i < N; i++) {
adj[i] = new int[numNodes[i]];
numNodes[i] = 0;
}
for (int i = 0; i < M; i++) {
int a = input[i][0];
int b = input[i][1];
adj[a][numNodes[a]++] = b;
if (bidirectional) adj[b][numNodes[b]++] = a;
}
return adj;
}
public int[][][] readWeightedGraph(int N, int M, boolean zeroIndexed, boolean bidirectional) throws Exception {
int[][][] adj = new int[N][][];
int[] numNodes = new int[N];
int[][] input = new int[M][3];
for (int i = 0; i < M; i++) {
int a = nextInt();
int b = nextInt();
if (zeroIndexed) {
a--;
b--;
}
int d = nextInt();
input[i][0] = a;
input[i][1] = b;
input[i][2] = d;
numNodes[a]++;
if (bidirectional) numNodes[b]++;
}
for (int i = 0; i < N; i++) {
adj[i] = new int[numNodes[i]][2];
numNodes[i] = 0;
}
for (int i = 0; i < M; i++) {
int a = input[i][0];
int b = input[i][1];
int d = input[i][2];
adj[a][numNodes[a]][0] = b;
adj[a][numNodes[a]][1] = d;
numNodes[a]++;
if (bidirectional) {
adj[b][numNodes[b]][0] = a;
adj[b][numNodes[b]][1] = d;
numNodes[b]++;
}
}
return adj;
}
}
static class FastPrinter {
static final char ENDL = '\n';
StringBuilder buf;
PrintWriter pw;
public FastPrinter(OutputStream stream) {
buf = new StringBuilder();
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream)));
}
public FastPrinter(String fileName) throws Exception {
buf = new StringBuilder();
pw = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
}
public FastPrinter(StringBuilder buf) {
this.buf = buf;
}
public void print(int a) {
buf.append(a);
}
public void print(long a) {
buf.append(a);
}
public void print(char a) {
buf.append(a);
}
public void print(char[] a) {
buf.append(a);
}
public void print(double a) {
buf.append(a);
}
public void print(String a) {
buf.append(a);
}
public void print(Object a) {
buf.append(a.toString());
}
public void println() {
buf.append(ENDL);
}
public void println(int a) {
buf.append(a);
buf.append(ENDL);
}
public void println(long a) {
buf.append(a);
buf.append(ENDL);
}
public void println(char a) {
buf.append(a);
buf.append(ENDL);
}
public void println(char[] a) {
buf.append(a);
buf.append(ENDL);
}
public void println(double a) {
buf.append(a);
buf.append(ENDL);
}
public void println(String a) {
buf.append(a);
buf.append(ENDL);
}
public void println(Object a) {
buf.append(a.toString());
buf.append(ENDL);
}
public void printf(String format, Object... args) {
buf.append(String.format(format, args));
}
public void close() {
pw.print(buf);
pw.close();
}
public void flush() {
pw.print(buf);
pw.flush();
buf.setLength(0);
}
}
} | Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | 82b30a63af73ca9f1dc27818f428c885 | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class Solution 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 Solution(),"Main",1<<27).start();
}
public static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
public static long findGCD(long arr[], int n)
{
long result = arr[0];
for (int i = 1; i < n; i++)
result = gcd(arr[i], result);
return result;
}
static void sortbycolomn(long arr[][], int col)
{
Arrays.sort(arr, new Comparator<long[]>() {
@Override
public int compare(final long[] entry1,
final long[] entry2) {
if (entry1[col] > entry2[col])
return 1;
else
return -1;
}
});
}
public void run()
{
InputReader in = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int t=in.nextInt();
while(t--!=0){
int n=in.nextInt();
char[] c=in.next().toCharArray();
int flag=0;
int l=0;
int r=0;
int split=0;
for(int i=1;i<=9;i++){
l=0; r=i; flag=0;
for(int j=0;j<n;j++){
if(c[j]-48<i){
if(c[j]-48>=l)
l=c[j]-48;
else{
flag=1;
break;
}
}
else if(c[j]-48>i){
if(c[j]-48>=r)
r=c[j]-48;
else{
flag=1;
break;
}
}
else{
if(r>i)
l=i;
}
}
if(flag==0){
split=i;
break;
}
}
if(flag==1)
w.println("-");
else{
// w.println(split);
char[] ans=new char[n];
l=0; r=split;
for(int i=0;i<n;i++){
if(c[i]-48>=split){
if(c[i]-48>=r){
ans[i]='2';
r=c[i]-48;
}
}
else
ans[i]='1';
}
for(int i=0;i<n;i++){
if(ans[i]!='1' && ans[i]!='2')
ans[i]='1';
}
w.println(ans);
}
}
w.flush();
w.close();
}
} | Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | 364049779fc0d3145b28b18a14c85420 | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 256 megabytes | import java.util.*;
import java.math.*;
// **** C. Paint the Digits ****
public class C {
static char [] in = new char [1000000];
public static void main (String [] arg) throws Throwable {
int t = nextInt();
StringBuilder ans = new StringBuilder(200000);
for (int ii = 0; ii<t; ++ii) {
int n = nextInt();
char [] s = next().toCharArray();
char [] a = new char [n];
Pair [] P = new Pair [n];
for (int i = 0; i<n; ++i) P[i] = new Pair(i, i, s[i]-'0');
Arrays.sort(P);
a[P[0].i] = '1';
int i = 1;
for (; i<n; ++i) {
if (P[i].i < P[i-1].i) {
int i2 = i+1;
while (i2 < n && P[i2].L == P[i].L && P[i2].i < P[i-1].i) i2++;
if (i2 == n || P[i2].L != P[i].L) {
//System.err.println("VIOLATION 1 : " + i + " , " + P[i].i + " vs " + P[i-1].i + " with values " + P[i].L + " , " + P[i-1].L);
break;
} else {
while (i2 < n && P[i2].L == P[i].L) {
a[P[i2].i] = '1';
i2++;
}
break;
}
}
a[P[i].i] = '1';
}
if (i != n) a[P[i].i] = '2';
int prev = (i != n) ? P[i].i : 0;
i++;
for (; i<n; ++i) {
if (a[P[i].i] == '1') continue;
if (P[i].i < prev) {
//System.err.println("VIOLATION 2 : " + i + " , "+ P[i].i + " vs " + P[i-1].i + " with values " + P[i].L + " , " + P[i-1].L);
break;
}
prev = P[i].i;
a[P[i].i] = '2';
}
if (i < n) {
ans = ans.append("-\n");
} else {
ans = ans.append(new String(a));
ans = ans.append("\n");
}
}
System.out.print(ans);
}
/************** HELPER CLASSES ***************/
//static class HS extends HashSet<Integer>{public HS(){super();}public HS(int a){super(a);}};
//static class AL extends ArrayList<Integer>{public AL(){super();}public AL(int a){super (a);}};
static class Pair implements Comparable<Pair> {
int i,j;long L; public Pair(int xx, int yy, long LL){i=xx;j=yy;L=LL;}
public int compareTo(Pair p) { return (this.L < p.L) ? -1 : (this.L == p.L) ? this.i - p.i : 1;}
}
/************** FAST IO CODE FOLLOWS *****************/
public static long nextLong() throws Throwable {
long i = System.in.read();boolean neg = false;while (i < 33) i = System.in.read();if (i == 45) {neg=true;i=48;}i = i - 48;
int j = System.in.read();while (j > 32) {i*=10;i+=j-48;j = System.in.read();}return (neg) ? -i : i;
}
public static int nextInt() throws Throwable {return (int)nextLong();}
public static String next() throws Throwable {
int i = 0; while (i < 33 && i != -1) i = System.in.read(); int cptr = 0; while (i >= 33) { in[cptr++] = (char)i; i = System.in.read();}
return new String(in, 0,cptr);
}
/**** LIBRARIES ****/
public static long gcdL(long a, long b) {while (b != 0) {long tmp = b;b = (a % b);a = tmp;}return a;}
public static int gcd(int a, int b) {while (b != 0) {int tmp = b;b = (a % b);a = tmp;}return a;}
public static int[] sieve(int LIM) {
int i,count = 0;
boolean [] b = new boolean [LIM];
for (i = 2;i<LIM; ++i) if (!b[i]) {count++; for (int j = i<<1; j<LIM; j+=i) b[j] = true;}
int [] primes = new int[count];
for (i = 2,count=0;i<LIM;++i) if (!b[i]) primes[count++] = i;
return primes;
}
public static int[] numPrimeFactors(int LIM) {
int i,count = 0;
int [] b = new int [LIM];
for (i = 2;i<LIM; ++i) if (b[i] == 0) {count++; for (int j = i; j<LIM; j+=i) b[j]++;}
return b;
}
public static StringBuilder stringFromArray(int [] a) {
StringBuilder b = new StringBuilder(9*a.length);
for (int i = 0; i<a.length; ++i) {
if (i != 0) b = b.append(' ');
b = b.append(a[i]);
}
return b;
}
public static long modPow (long a, long n, long MOD) { long S = 1; for (;n > 0; n>>=1, a=(a*a)%MOD) if ((n & 1) != 0) S = (a*S) % MOD; return S;}
}
/* Full Problem Text:
You are given a sequence of n digits d_1d_2 \dots d_{n}.
You need to paint all the digits in two colors so that:
each digit is painted either in the color 1 or in the color 2;
if you write in a row from left to right all the digits painted in the color 1, and then after them all the digits painted in the color 2, then the resulting sequence of n digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit).
For example, for the sequence d=914 the only valid coloring is 211 (paint in the color 1 two last digits, paint in the color 2 the first digit).
But 122 is not a valid coloring (9 concatenated with 14 is not a non-decreasing sequence).
It is allowed that either of the two colors is not used at all.
Digits painted in the same color are not required to have consecutive positions.
Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do.
*/ | Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | a9dbe939116373439af16e857deac59e | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class PaintTheDigits {
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int t = Integer.parseInt(f.readLine());
PrintWriter out = new PrintWriter(System.out);
for (int iter = 0; iter < t; iter++) {
int n = Integer.parseInt(f.readLine());
char[] str = f.readLine().toCharArray();
int[] coloring = new int[n];
int lastIndex = -1;
int nextLastIndex = -1;
int curColor = 1;
boolean flag = true;
for (int num = 0; num <= 9; num++) {
for (int i = n - 1; i >= 0; i--) {
if (str[i] == num+'0') {
if (i > lastIndex) {
coloring[i] = curColor;
nextLastIndex= Math.max(i, nextLastIndex);
}
else {
curColor++;
coloring[i] = curColor;
lastIndex = -1;
nextLastIndex = i;
}
}
if (curColor > 2) {
flag = false;
break;
}
}
if (!flag) {
break;
}
lastIndex = Math.max(nextLastIndex, lastIndex);
}
if (!flag) {
out.println('-');
}
else {
for (int i = 0; i < n; i++) {
out.print(coloring[i]);
}
out.println();
}
}
out.close();
}
} | Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | 2acd12939409c5df8e5dedaa4639b51b | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class C {
public class Pair implements Comparable<Pair> {
public int dig;
public int ind;
public Pair(int dig, int ind) {
this.dig = dig;
this.ind = ind;
}
public int compareTo(Pair p) {
if(this.dig < p.dig) {
return -1;
} else if(this.dig > p.dig) {
return 1;
}
if(this.ind < p.ind) {
return -1;
}
return 1;
}
}
public void realMain() throws Exception {
BufferedReader fin = new BufferedReader(new InputStreamReader(System.in), 1000000);
String in = fin.readLine();
String[] ar = in.split(" ");
int T = Integer.parseInt(ar[0]);
for(int t = 0; t < T; t++) {
in = fin.readLine();
int n = Integer.parseInt(in);
in = fin.readLine();
Pair[] pairs = new Pair[n];
int[] color = new int[n];
for(int i = 0; i < n; i++) {
int dig = (int)(in.charAt(i) - '0');
pairs[i] = new Pair(dig, i);
}
Arrays.sort(pairs);
int farthestone = -1;
int farthesttwo = -1;
int mostrecentoneval = 0;
int mostrecenttwoval = 0;
int lowesttwoval = 11;
int lowesttwoind = 0;
boolean cant = false;
/* for(int i = 0; i < n; i++) {
if(pairs[i].dig > lowesttwoval) {
if(pairs[i].dig < lowesttwoind) {
cant = true;
}
color[pairs[i].ind] = 2;
mostrecenttwoval = pairs[i].dig;
farthesttwo = Math.max(farthesttwo, pairs[i].ind);
continue;
}
if(pairs[i].ind > farthestone) {
color[pairs[i].ind] = 1;
mostrecentoneval = pairs[i].dig;
farthestone = pairs[i].ind;
} else if(pairs[i].ind > farthesttwo) {
if(pairs[i].dig == mostrecentoneval) {
color[pairs[i].ind] = 1;
} else {
color[pairs[i].ind] = 2;
mostrecenttwoval = pairs[i].dig;
farthesttwo = pairs[i].ind;
if(lowesttwoval == 11) {
lowesttwoval = Math.min(lowesttwoval, pairs[i].dig);
lowesttwoind = pairs[i].ind;
}
}
} else {
if(pairs[i].dig == mostrecenttwoval) {
color[pairs[i].ind] = 2;
} else {
cant = true;
}
}
}*/
int farone = -1;
int lowtwoval = 11;
int lowtwoind = -1;
int prevdig = -1;
int fartwo = -1;
for(int i = 0; i < n; i++) {
int dig = pairs[i].dig;
int ind = pairs[i].ind;
if(lowtwoval == 11 && ind > farone) {
color[ind] = 1;
farone = ind;
prevdig = dig;
continue;
}
if(lowtwoval == 11) {
lowtwoval = dig;
lowtwoind = ind;
color[ind] = 2;
fartwo = ind;
prevdig = dig;
continue;
}
if(dig > lowtwoval) {
if(ind < lowtwoind) {
cant = true;
continue;
}
if(ind < fartwo && dig != prevdig) {
cant = true;
continue;
}
color[ind] = 2;
fartwo = ind;
prevdig = dig;
continue;
}
if(ind > farone) {
color[ind] = 1;
farone = ind;
prevdig = dig;
continue;
}
color[ind] = 2;
fartwo = ind;
prevdig = dig;
}
if(cant) {
System.out.println("-");
} else {
StringBuffer sb = new StringBuffer("");
for(int i = 0; i < n; i++) {
sb.append(color[i]);
}
System.out.println(sb);
}
}
}
public static void main(String[] args) throws Exception {
C c = new C();
c.realMain();
}
} | Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | 982f1e00ac3e2f14ee0f9a69b245e83a | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 256 megabytes | //package test;
import java.util.*;
import java.io.*;
public class CF1 implements Runnable {
FastReader s;
PrintWriter out;
String INPUT = "";
void solve() {
//Type solution here.
int t = s.nextInt();
while(t-->0)
{
int n = s.nextInt();
String str = s.next();
char[] carr = str.toCharArray();
Arrays.sort(carr);
int[] rmin = new int[n];
rmin[n-1] = str.charAt(n-1)-'0';
for(int i=n-2;i>=0;i--)
{
rmin[i] = Math.min(rmin[i+1], str.charAt(i)-'0');
}
boolean found = false;
int[] color = new int[n];
for(int j=0;j<10;j++)
{
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
for(int i=0;i<n;i++)
{
int d = str.charAt(i)-'0';
if(d>j)
{
color[i] = 2;
sb2.append(str.charAt(i));
}
else if(d<j)
{
color[i] = 1;
sb1.append(str.charAt(i));
}
else
{
if(rmin[i]<d)
{
color[i] = 2;
sb2.append(str.charAt(i));
}
else
{
color[i] = 1;
sb1.append(str.charAt(i));
}
}
}
boolean check = true;
String temp = sb1.toString()+sb2.toString();
for(int i=0;i<n;i++)
if(carr[i]!=temp.charAt(i))
check = false;
if(check)
{
found = true;
break;
}
}
if(found)
{
for(int i=0;i<n;i++)
System.out.print(color[i]);
System.out.println();
}
else
System.out.println("-");
}
}
static int getparent(int p, int[] parent)
{
if(parent[p]==p)
return p;
parent[p] = getparent(parent[p], parent);
return parent[p];
}
static void union(int u, int v, int[] parent, int[] rank)
{
if(rank[u]>rank[v])
parent[v] = u;
else if(rank[u]<rank[v])
parent[u] = v;
else
{
rank[u]++;
parent[v] = u;
}
}
static long getgcd(long a, long b)
{
if(b==0)
return a;
return getgcd(b, a%b);
}
static class Pair implements Comparable<Pair>{
int first;
int second;
Pair(){}
Pair(int first, int second)
{
this.first = first;
this.second = second;
}
public int compareTo(Pair p)
{
if(this.first<=p.first)
return -1;
else
return 1;
}
}
public void run() {
long time = System.currentTimeMillis();
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
out = new PrintWriter(System.out);
s = new FastReader(oj);
solve();
out.flush();
if (!oj) {
System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" }));
}
}
public static void main(String[] args) {
new Thread(null, new CF1(), "Main", 1 << 26).start();
}
class FastReader {
InputStream is;
public FastReader(boolean onlineJudge) {
is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes());
}
byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
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++];
}
boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
double nextDouble() {
return Double.parseDouble(next());
}
char nextChar() {
return (char) skip();
}
String next() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
String nextLine() {
int b = skip();
StringBuilder sb = new StringBuilder();
while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
char[] next(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);
}
int nextInt() {
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();
}
}
long nextLong() {
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();
}
}
char[][] nextMatrix(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = next(m);
return map;
}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
int[][] next2DInt(int n, int m) {
int[][] arr = new int[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextIntArray(m);
}
return arr;
}
long[][] next2DLong(int n, int m) {
long[][] arr = new long[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextLongArray(m);
}
return arr;
}
int[] shuffle(int[] arr) {
Random r = new Random();
for (int i = 1, j; i < arr.length; i++) {
j = r.nextInt(i);
int c = arr[i];
arr[i] = arr[j];
arr[j] = c;
}
return arr;
}
long[] shuffle(long[] arr) {
Random r = new Random();
for (int i = 1, j; i < arr.length; i++) {
j = r.nextInt(i);
long c = arr[i];
arr[i] = arr[j];
arr[j] = c;
}
return arr;
}
int[] uniq(int[] arr) {
arr = s.shuffle(arr);
Arrays.sort(arr);
int[] rv = new int[arr.length];
int pos = 0;
rv[pos++] = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[i - 1]) {
rv[pos++] = arr[i];
}
}
return Arrays.copyOf(rv, pos);
}
long[] uniq(long[] arr) {
arr = s.shuffle(arr);
Arrays.sort(arr);
long[] rv = new long[arr.length];
int pos = 0;
rv[pos++] = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[i - 1]) {
rv[pos++] = arr[i];
}
}
return Arrays.copyOf(rv, pos);
}
int[] reverse(int[] arr) {
int l = 0, r = arr.length - 1;
while (l < r) {
arr[l] = arr[l] ^ arr[r];
arr[r] = arr[l] ^ arr[r];
arr[l] = arr[l] ^ arr[r];
l++;
r--;
}
return arr;
}
long[] reverse(long[] arr) {
int l = 0, r = arr.length - 1;
while (l < r) {
arr[l] = arr[l] ^ arr[r];
arr[r] = arr[l] ^ arr[r];
arr[l] = arr[l] ^ arr[r];
l++;
r--;
}
return arr;
}
int[] compress(int[] arr) {
int n = arr.length;
int[] rv = Arrays.copyOf(arr, n);
rv = uniq(rv);
for (int i = 0; i < n; i++) {
arr[i] = Arrays.binarySearch(rv, arr[i]);
}
return arr;
}
long[] compress(long[] arr) {
int n = arr.length;
long[] rv = Arrays.copyOf(arr, n);
rv = uniq(rv);
for (int i = 0; i < n; i++) {
arr[i] = Arrays.binarySearch(rv, arr[i]);
}
return arr;
}
}
} | Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | 83b4dd57b30e49949122a32f7bf1a427 | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 256 megabytes | import java.io.*;
import java.util.*;
public class C {
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
static InputReader r = new InputReader(System.in);
static PrintWriter pw = new PrintWriter(System.out);
public static void main(String[] args) {
int qq = r.nextInt();
for(int q = 1; q <= qq; q++){
int n = r.nextInt();
String s = r.next();
int[] arr = new int[n];
boolean[] exists = new boolean[10];
for(int i = 0; i < n; i++){
arr[i] = (Integer.parseInt(s.substring(i, i+1)));
exists[arr[i]] = true;
}
boolean f = false; // did it work?
for(int b = 0; b <= 9; b++){ // breakpoint; last integer included in the first list
ArrayList<Integer> first = new ArrayList<Integer>();
ArrayList<Integer> second = new ArrayList<Integer>();
int ln = b;
while(ln > 0 && !exists[ln]){
ln--;
}
int li = 1000000; // last index of b
for(int i = n-1; i >= 0; i--){
if(arr[i] == ln){
li = i;
break;
}
if(i == 0){
li = -1;
}
}
for(int i = 0; i < n; i++){
if(arr[i] <= b || (arr[i] == b+1 && i > li)){
first.add(arr[i]);
} else {
second.add(arr[i]);
}
}
/*
System.out.println("--------" + b + "--------");
System.out.println(first);
System.out.println(second);
*/
if(check(first) && check(second)){
for(int i = 0; i < n; i++){
if(arr[i] <= b || arr[i] == b+1 && i > li){
pw.print(1);
} else {
pw.print(2);
}
}
pw.println();
f = true;
break;
}
}
if(!f){
pw.println("-");
}
}
pw.close();
}
public static boolean check(ArrayList<Integer> list){
for(int i = 1; i < list.size(); i++){
if(list.get(i) < list.get(i-1)){
return false;
}
}
return true;
}
}
/**
* _ _ _
* | | | | | |
* ___ ___ __| | ___ | |__ _ _ __| | __ _ _ __ _ __ ___ _ __ _ _ __ _ ___
* / __/ _ \ / _` |/ _ \ | '_ \| | | | / _` |/ _` | '__| '__/ _ \ '_ \ | | | |/ _` |/ _ \
* | (_| (_) | (_| | __/ | |_) | |_| | | (_| | (_| | | | | | __/ | | | | |_| | (_| | (_) |
* \___\___/ \__,_|\___| |_.__/ \__, | \__,_|\__,_|_| |_| \___|_| |_| \__, |\__,_|\___/
* __/ | ______ __/ |
* |___/ |______|___/
*/ | Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | c1cb080fd0b4fd88af011337d3ccf22f | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 256 megabytes | /**
* Created at 22:25 on 2019-09-14
*/
import java.io.*;
import java.util.*;
public class Main {
static FastScanner sc = new FastScanner();
static Output out = new Output(System.out);
static final int[] dx = {0, 1, 0, -1};
static final int[] dy = {-1, 0, 1, 0};
static final long MOD = (long) (1e9 + 7);
static final long INF = Long.MAX_VALUE / 2;
static final int e5 = (int) 1e5;
public static class Solver {
public Solver() {
int T = sc.nextInt();
for (int t=0; t<T; t++) {
int N = sc.nextInt();
String s = sc.next();
ArrayList<Integer>[] dIn = new ArrayList[10];
for (int i=0; i<10; i++) dIn[i] = new ArrayList<Integer>();
for (int i=0; i<N; i++) {
dIn[s.charAt(i)-'0'].add(i);
}
int[] done = new int[10];
for (int i=0; i<10; i++) done[i] = dIn[i].size();
int[] ans = new int[N];
int now = 0;
int c = 1;
boolean ok = true;
for (int d = 0; d < 10; d++) {
if (dIn[d].size() == 0) continue;
int start = -1;
for (int j=0; j<done[d]; j++) {
int index = dIn[d].get(j);
if (index < now) continue;
if (start == -1) start = j;
ans[index] = c;
now = index;
}
if (start != 0) {
if (c >= 2) {
ok = false;
break;
}
now = 0;
if (start != -1) done[d] = start;
c++;
d--;
}
}
if (ok) {
for (int i = 0; i < N; i++) out.print(ans[i]);
out.println();
} else {
out.println("-");
}
}
}
}
public static void main(String[] args) {
new Solver();
out.flush();
}
static class FastScanner {
private InputStream in = System.in;
private final byte[] buffer = new byte[1024];
private int ptr = 0;
private int buflen = 0;
public void load() {
try {
in = new FileInputStream(next());
} catch (Exception e) {
e.printStackTrace();
}
}
private boolean hasNextByte() {
if (ptr < buflen) {
return true;
} else {
ptr = 0;
try {
buflen = in.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
if (buflen <= 0) {
return false;
}
}
return true;
}
private int readByte() {
if (hasNextByte()) return buffer[ptr++];
else return -1;
}
private static boolean isPrintableChar(int c) {
return 33 <= c && c <= 126;
}
private void skipUnprintable() {
while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;
}
public boolean hasNext() {
skipUnprintable();
return hasNextByte();
}
public String next() {
if (!hasNext()) throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while (isPrintableChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public long nextLong() {
if (!hasNext()) throw new NoSuchElementException();
long n = 0;
boolean minus = false;
int b = readByte();
if (b == '-') {
minus = true;
b = readByte();
}
if (b < '0' || '9' < b) {
throw new NumberFormatException();
}
while (true) {
if ('0' <= b && b <= '9') {
n *= 10;
n += b - '0';
} else if (b == -1 || !isPrintableChar(b)) {
return minus ? -n : n;
} else {
throw new NumberFormatException();
}
b = readByte();
}
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextIntArray(int N, boolean oneBased) {
if (oneBased) {
int[] array = new int[N + 1];
for (int i = 1; i <= N; i++) {
array[i] = sc.nextInt();
}
return array;
} else {
int[] array = new int[N];
for (int i = 0; i < N; i++) {
array[i] = sc.nextInt();
}
return array;
}
}
public long[] nextLongArray(int N, boolean oneBased) {
if (oneBased) {
long[] array = new long[N + 1];
for (int i = 1; i <= N; i++) {
array[i] = sc.nextLong();
}
return array;
} else {
long[] array = new long[N];
for (int i = 0; i < N; i++) {
array[i] = sc.nextLong();
}
return array;
}
}
}
static class Output extends PrintWriter {
private long startTime;
public Output(PrintStream ps) {
super(ps);
}
public void print(int[] a, String separator) {
for (int i = 0; i < a.length; i++) {
if (i == 0) print(a[i]);
else print(separator + a[i]);
}
println();
}
public void print(long[] a, String separator) {
for (int i = 0; i < a.length; i++) {
if (i == 0) print(a[i]);
else print(separator + a[i]);
}
println();
}
public void print(String[] a, String separator) {
for (int i = 0; i < a.length; i++) {
if (i == 0) print(a[i]);
else print(separator + a[i]);
}
println();
}
public void print(ArrayList a, String separator) {
for (int i = 0; i < a.size(); i++) {
if (i == 0) print(a.get(i));
else print(separator + a.get(i));
}
println();
}
public void start() {
startTime = System.currentTimeMillis();
}
public void time(String s) {
long time = System.currentTimeMillis() - startTime;
println(s + "(" + time + ")");
}
}
}
| Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | a40f6e21eb5c20492cccfccee5e872cb | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 256 megabytes | import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
public class C {
public static void main(String[] args) throws Exception {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
int T = Integer.parseInt(bf.readLine());
for(int t=0; t<T; t++) {
int n = Integer.parseInt(bf.readLine());
String s = bf.readLine();
int[] a = new int[n];
for(int i=0; i<n; i++) a[i] = s.charAt(i)-'0';
int[] ans = new int[n];
int last1 = -1;
int last2 = -1;
boolean works = true;
int first2 = -1;
int first1 = -1;
for(int i=1; i<n; i++) {
if(a[i] < a[i-1]) {
ans[i] = 1;
ans[i-1] = 2;
//last2 = a[i];
if(first1 == -1) first1 = a[i];
}
}
for(int i=0; i<n; i++) {
if(ans[i] == 0) {
if(last2 != -1) {
if(a[i] >= last2) ans[i] = 2;
else ans[i] = 1;
}
else {
if(a[i] <= first1) ans[i] = 1;
else ans[i] = 2;
}
}
if(ans[i] == 1) {
if(a[i] < last1) works = false;
last1 = a[i];
}
if(ans[i] == 2) {
if(first2 == -1) first2 = a[i];
if(a[i] < last2) works = false;
last2 = a[i];
//out.println(works);
}
}
// out.println(last1 + " " + first2);
if(last1 > first2) works = false;
if(!works) out.println("-");
else {
StringBuilder sb = new StringBuilder();
for(int i=0; i<n; i++) sb.append(ans[i]);
out.println(sb.toString());
}
}
// StringTokenizer st = new StringTokenizer(bf.readLine());
// int[] a = new int[n]; for(int i=0; i<n; i++) a[i] = Integer.parseInt(st.nextToken());
// int n = Integer.parseInt(st.nextToken());
out.close(); System.exit(0);
}
}
| Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | d944d70b29a30c3a70de545bec38bf07 | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 256 megabytes |
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String args[])
{
Scanner scan=new Scanner(System.in);
int t=scan.nextInt();
for(int q=0;q<t;q++) {
int n=scan.nextInt();
String cur=scan.next();
int min[]=new int[n];
// int x=cur.charAt(n)
min[n-1]=(cur.charAt(n-1)-'0');
for(int i=n-2;i>=0;i--) {
int x=cur.charAt(i)-'0';
min[i]=Math.min(x,min[i+1]);
}
int fir=0;
// String ans="";
char ans[]=new char[n];
int sec=0;
int secstart=Integer.MAX_VALUE;
int i=0;
for(i=0;i<n;i++) {
int x=cur.charAt(i)-'0';
if(x<=min[i] && x<=secstart) {
ans[i]='1';
}else if(sec<=x){
if(secstart==Integer.MAX_VALUE) {
secstart=x;
}
sec=x;
ans[i]='2';
}else {
break;
}
}
if(i==n) {
System.out.println(String.valueOf(ans));;
}else {
System.out.println("-");
}
}
}
}
| Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | 98aae64bbad92300d8c8597ccfe2512f | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 256 megabytes | import java.util.*;
public class sol{
public static void paintdigit(String s,int n){
char carr[]=s.toCharArray();
Arrays.sort(carr);
int k=0;
int res[]=new int[n];
for(int i=0;i<s.length();i++){
if(k<s.length())
if(carr[k]==s.charAt(i)){
res[i]=1;
k++;
}
}
for(int i=0;i<s.length();i++){
if(k<s.length())
if(carr[k]==s.charAt(i)){
res[i]=2;
k++;
}
}
if(k==n){
for(int i=0;i<n;i++){
System.out.print(res[i]);
}
}else{
System.out.print("-");
}
System.out.println();
}
public static void main(String[] args){
Scanner scn=new Scanner(System.in);
int t=scn.nextInt();
while(t-->0){
int n=scn.nextInt();
String s=scn.next();
paintdigit(s,n);
}
}
}
| Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | 7492d5354ef2bbddde4905874bd40cf8 | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
CRaskrashivanieCifr solver = new CRaskrashivanieCifr();
solver.solve(1, in, out);
out.close();
}
static class CRaskrashivanieCifr {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int tn = in.nextInt();
for (int t = 0; t < tn; t++) {
int n = in.nextInt();
int[] a = new int[n];
String s = in.next();
for (int i = 0; i < n; i++) {
a[i] = s.charAt(i) - '0';
}
int[] c = new int[n];
boolean ok = false;
for (int d = 0; d < 10; d++) {
int last1 = 0;
int last2 = d;
ok = true;
for (int i = 0; i < n; i++) {
if (a[i] < last1) {
ok = false;
break;
} else if (a[i] < last2) {
c[i] = 1;
last1 = a[i];
} else {
c[i] = 2;
last2 = a[i];
}
}
if (last1 > d) {
ok = false;
}
if (ok) {
StringBuilder ans = new StringBuilder();
for (int i = 0; i < n; i++) {
ans.append(c[i]);
}
out.println(ans);
break;
}
}
if (!ok) {
out.println("-");
}
}
}
}
}
| Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | e2966d6a6b2da46555f71f3da28e3e40 | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class C {
public static void main(String[] args) {
// {
// System.out.println(solve("040425524644"));
// System.out.println(solve("0"));
// System.out.println(solve("123456789"));
// System.out.println(solve("98"));
// System.out.println(solve("987"));
// System.exit(0);
// }
Scanner sc = new Scanner(System.in);
int numTest = sc.nextInt();
for (int i = 0; i < numTest; i++) {
int n = sc.nextInt();
String digits = null;
while (digits == null || digits.isEmpty()) digits = sc.nextLine();
System.out.println(solve(digits));
}
sc.close();
}
static int[] colors = new int[200010];
private static String solve(String digits) {
int n = digits.length();
Arrays.fill(colors, 0, n, 0);
List<Integer> splitPos = new ArrayList<>();
char cur;
for (int i = 0; i < n - 1; ++i) {
cur = digits.charAt(i);
if (cur > digits.charAt(i + 1)) {
if (colors[i] == 1) {
return "-";
}
colors[i] = 2; colors[i + 1] = 1;
splitPos.add(i);
}
}
if (splitPos.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) sb.append('1');
return sb.toString();
}
char min1, min2, max1, max2;
int n1, n2;
for (int pi = 1; pi < splitPos.size(); ++pi) {
n1 = splitPos.get(pi - 1) + 2; n2 = splitPos.get(pi) - 1;
min1 = digits.charAt(splitPos.get(pi - 1) + 1);
min2 = digits.charAt(splitPos.get(pi - 1));
max1 = digits.charAt(splitPos.get(pi) + 1);
max2 = digits.charAt(splitPos.get(pi));
if (!(min1 <= max1 && min2 <= max2 && (min2 == 0 || max1 <= min2))) return "-";
for (int i = n1; i <= n2; i++) {
cur = digits.charAt(i);
if (min1 <= cur && cur <= max1) colors[i] = 1;
else if (min2 <= cur && cur <= max2) colors[i] = 2;
else return "-";
}
}
max1 = digits.charAt(splitPos.get(0) + 1);
char start2 = 0;
for (int i = 0; i < splitPos.get(0); ++i) {
cur = digits.charAt(i);
if (cur <= max1) colors[i] = 1;
else {
colors[i] = 2;
if (start2 == 0) start2 = cur;
}
}
min1 = digits.charAt(splitPos.get(splitPos.size() - 1) + 1);
min2 = digits.charAt(splitPos.get(splitPos.size() - 1));
if (start2 == 0) start2 = digits.charAt(splitPos.get(0));
if (start2 < digits.charAt(splitPos.get(splitPos.size() - 1) + 1)) return "-";
for (int i = splitPos.get(splitPos.size() - 1) + 2; i < n; ++i) {
cur = digits.charAt(i);
if (cur >= min2) colors[i] = 2;
else if (cur >= min1 && cur <= start2) colors[i] = 1;
else return "-";
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) sb.append(colors[i]);
return sb.toString();
}
}
| Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | f36544fcdcd4e9f14e2e241016d863c2 | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
MScanner sc=new MScanner(System.in);
PrintWriter pw=new PrintWriter(System.out);
int t=sc.nextInt();
while(t-->0) {
int n=sc.nextInt();
char[]in=sc.nextLine().toCharArray();
if(n==1) {pw.println('2');continue;}
char f='0',s='0',starts='0';
StringBuilder ans=new StringBuilder();
int i=0;int idx=-1;
for(;i<n-1;i++) {
if(in[i]>in[i+1]) {
f=in[i+1];starts=s=in[i];idx=i+1;
i+=2;
break;
}
}
boolean start=false;
for(int j=0;idx!=-1 && j<=idx;j++) {
if(in[j]<=f) {
ans.append('1');
}
else {
if(!start) {
starts=in[j];
start=true;
}
ans.append('2');
}
}
boolean can=true;
if(idx==-1) {
for(int j=0;j<n;j++) {
pw.print('2');
}
pw.println();
}
else {
for(;i<n;i++) {
if(in[i]>=s) {
ans.append('2');s=in[i];
}
else {
if(in[i]>=f && in[i]<=starts) {
ans.append('1');f=in[i];
}
else {
can=false;break;
}
}
}
if(can) {
pw.println(ans);
}
else {
pw.println('-');
}
}
}
pw.flush();
}
static class MScanner {
StringTokenizer st;
BufferedReader br;
public MScanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public MScanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
} | Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | 1ea38d4eaae7bd8bdf93538e7f6950e6 | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 256 megabytes | import java.io.*;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
public class PaintTheDigits {
static Scanner sc = new Scanner(System.in);
static PrintWriter pw = new PrintWriter(System.out), pw2 = new PrintWriter(System.out);
static int n, arr[];
public static void main(String[] args) throws IOException {
int q = sc.nextInt();
loop:
while (q-- > 0) {
n = sc.nextInt();
char[] c = sc.nextLine().toCharArray();
arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = Integer.parseInt(c[i] + "");
for (int i = 0; i <= 10; i++) {
int max = 0;
boolean[] vis = new boolean[n];
boolean flag = true;
int last, lastidx = -1, firstUnvis = -1;
for (int j = 0; j < n; j++) {
if (arr[j] > i) {
if (firstUnvis == -1)
firstUnvis = arr[j];
continue;
}
if (arr[j] < max) {
flag = false;
break;
}
max = Math.max(max, arr[j]);
vis[j] = true;
lastidx = j;
}
if (flag) {
last = max;
max = 0;
boolean chk = true;
for (int j = 0; j < n; j++) {
if (vis[j])
continue;
if (arr[j] < max) {
if (arr[j] == firstUnvis && j >= lastidx) {
vis[j] = true;
continue;
} else {
chk = false;
break;
}
}
max = Math.max(max, arr[j]);
}
if (chk) {
for (int j = 0; j < n; j++)
if (vis[j])
pw.print(1);
else
pw.print(2);
pw.println();
continue loop;
}
}
}
pw.println('-');
}
pw.flush();
}
public static <E> void print2D(E[][] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
pw.println(arr[i][j]);
}
}
}
public static int digitSum(String s) {
int toReturn = 0;
for (int i = 0; i < s.length(); i++) toReturn += Integer.parseInt(s.charAt(i) + " ");
return toReturn;
}
public static boolean isPrime(long n) {
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (long i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static long pow(long a, long pow) {
return pow == 0 ? 1 : pow % 2 == 0 ? pow(a * a, pow >> 1) : a * pow(a * a, pow >> 1);
}
public static long sumNum(long a) {
return a * (a + 1) / 2;
}
public static int gcd(int n1, int n2) {
return n2 == 0 ? n1 : gcd(n2, n1 % n2);
}
public static long factorial(long a) {
return a == 0 || a == 1 ? 1 : a * factorial(a - 1);
}
public static void sort(int arr[]) {
shuffle(arr);
Arrays.sort(arr);
}
public static void shuffle(int arr[]) {
Random rnd = new Random();
for (int i = arr.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
int temp = arr[index];
arr[index] = arr[i];
arr[i] = temp;
}
}
public static Double[] solveQuadratic(double a, double b, double c) {
double result = (b * b) - 4.0 * a * c;
double r1;
if (result > 0.0) {
r1 = ((double) (-b) + Math.pow(result, 0.5)) / (2.0 * a);
double r2 = ((double) (-b) - Math.pow(result, 0.5)) / (2.0 * a);
return new Double[]{r1, r2};
} else if (result == 0.0) {
r1 = (double) (-b) / (2.0 * a);
return new Double[]{r1, r1};
} else {
return new Double[]{null, null};
}
}
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() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
static class pair<E1, E2> implements Comparable<pair> {
E1 x;
E2 y;
pair(E1 x, E2 y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(pair o) {
return x.equals(o.x) ? (Integer) y - (Integer) o.y : (Integer) x - (Integer) o.x;
}
@Override
public String toString() {
return x + " " + y;
}
public double pointDis(pair p1) {
return Math.sqrt(((Integer) y - (Integer) p1.y) * ((Integer) y - (Integer) p1.y) + ((Integer) x - (Integer) p1.x) * ((Integer) x - (Integer) p1.x));
}
}
}
| Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | 124de050fe50951fc81a2f49a3e31da3 | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 0; i < t; i++) {
int n = sc.nextInt();
char[] d = sc.next().toCharArray();
System.out.println(solve(d));
}
}
private static String solve(char[] d) {
char[] c = new char[d.length];
for (int i = 0; i < d.length; i++) {
c[i] = d[i];
}
Arrays.sort(c);
List<Integer> idx1 = new ArrayList<>();
int di = 0;
int ci = 0;
while (di < d.length && ci < c.length) {
if (d[di]== c[ci]) {
idx1.add(di);
di++;
ci++;
} else {
di++;
}
}
List<Integer> idx2 = new ArrayList<>();
di = 0;
while (di < d.length && ci < c.length) {
if (d[di]== c[ci]) {
idx2.add(di);
di++;
ci++;
} else {
di++;
}
}
if (idx1.size() + idx2.size() < d.length) {
return "-";
}
char[] ans = new char[d.length];
for (int idx : idx1) {
ans[idx] = '1';
}
for (int idx : idx2) {
ans[idx] = '2';
}
return new String(ans);
}
}
| Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | a275b7edaad2247937fefbc5077c671d | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 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.SplittableRandom;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
CPaintTheDigits solver = new CPaintTheDigits();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class CPaintTheDigits {
public void solve(int testNumber, FastReader in, PrintWriter out) {
int n = in.nextInt();
char[] s = in.nextString().toCharArray();
char[] sorted = s.clone();
sorted = ArrayUtils.sort(sorted);
char[] answer = new char[n];
ArrayUtils.fill(answer, '2');
for (int i = 0, ptr = 0; i < n; ++i) {
if (s[i] == sorted[ptr]) {
answer[i] = '1';
++ptr;
}
}
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < n; ++i) {
if (answer[i] == '1') stringBuilder.append(s[i]);
}
for (int i = 0; i < n; ++i) {
if (answer[i] == '2') stringBuilder.append(s[i]);
}
char[] check = stringBuilder.toString().toCharArray();
out.println(Arrays.equals(check, sorted) ? new String(answer) : "-");
}
}
static class ArrayUtils {
public static char[] sort(char[] a) {
a = shuffle(a, new SplittableRandom());
Arrays.sort(a);
return a;
}
public static char[] shuffle(char[] a, SplittableRandom gen) {
for (int i = 0, n = a.length; i < n; i++) {
int ind = gen.nextInt(n - i) + i;
char d = a[i];
a[i] = a[ind];
a[ind] = d;
}
return a;
}
public static void fill(char[] array, char value) {
Arrays.fill(array, value);
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int pnumChars;
public FastReader(InputStream stream) {
this.stream = stream;
}
private int pread() {
if (pnumChars == -1) {
throw new InputMismatchException();
}
if (curChar >= pnumChars) {
curChar = 0;
try {
pnumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (pnumChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public String next() {
return nextString();
}
public int nextInt() {
int c = pread();
while (isSpaceChar(c))
c = pread();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = pread();
}
int res = 0;
do {
if (c == ',') {
c = pread();
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = pread();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = pread();
while (isSpaceChar(c))
c = pread();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = pread();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
| Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | 599741032ad10db14eec9a4528161aeb | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 256 megabytes | import java.io.*;
import java.util.*;
public class C implements Runnable {
FastReader scn;
PrintWriter out;
String INPUT = "";
void solve() {
int t = scn.nextInt();
here: while (t-- > 0) {
int n = scn.nextInt();
String s = scn.next();
int[][] arr = new int[n][2];
int[] need = new int[n];
TreeSet<Integer>[] set = new TreeSet[10];
Arrays.parallelSetAll(set, i -> new TreeSet<>());
for (int i = 0; i < n; i++) {
need[i] = arr[i][0] = s.charAt(i) - '0';
arr[i][1] = i;
set[arr[i][0]].add(i);
}
Arrays.parallelSort(arr, (o1, o2) -> o1[0] != o2[0] ? o1[0] - o2[0] : o1[1] - o2[1]);
int[] ans = new int[n];
for (int i = 0, ind = -1; i < n; i++) {
if(arr[i][1] <= ind) {
continue;
}
ans[arr[i][1]] = 1;
ind = arr[i][1];
}
int min = -1;
for (int i = 0, ind = -1; i < n; i++) {
if (ans[arr[i][1]] != 0 || arr[i][1] <= ind) {
continue;
}
ans[arr[i][1]] = 2;
ind = arr[i][1];
if(min == -1) {
min = arr[i][0];
}
}
for(int i = 0; i < n; i++) {
if(ans[arr[i][1]] == 1 && arr[i][0] > min) {
ans[arr[i][1]] = 2;
}
}
for (int a : ans) {
if(a == 0) {
out.println("-");
continue here;
}
}
int[] a = new int[n];
int p = 0;
for(int i = 0; i < n; i++) {
if(ans[i] == 1) {
a[p++] = need[i];
}
}
for(int i = 0; i < n; i++) {
if(ans[i] == 2) {
a[p++] = need[i];
}
}
Arrays.parallelSort(need);
if(!Arrays.equals(a, need)) {
out.println("-");
continue here;
}
for (int aa : ans) {
out.print(aa);
}
out.println();
}
}
public void run() {
long time = System.currentTimeMillis();
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
out = new PrintWriter(System.out);
scn = new FastReader(oj);
solve();
out.flush();
if (!oj) {
System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" }));
}
}
public static void main(String[] args) {
new Thread(null, new C(), "Main", 1 << 26).start();
}
class FastReader {
InputStream is;
public FastReader(boolean onlineJudge) {
is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes());
}
byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
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++];
}
boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
double nextDouble() {
return Double.parseDouble(next());
}
char nextChar() {
return (char) skip();
}
String next() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
String nextLine() {
int b = skip();
StringBuilder sb = new StringBuilder();
while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
char[] next(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);
}
int nextInt() {
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();
}
}
long nextLong() {
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();
}
}
char[][] nextMatrix(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = next(m);
return map;
}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
int[][] next2DInt(int n, int m) {
int[][] arr = new int[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextIntArray(m);
}
return arr;
}
long[][] next2DLong(int n, int m) {
long[][] arr = new long[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextLongArray(m);
}
return arr;
}
int[] shuffle(int[] arr) {
Random r = new Random();
for (int i = 1, j; i < arr.length; i++) {
j = r.nextInt(i);
int c = arr[i];
arr[i] = arr[j];
arr[j] = c;
}
return arr;
}
long[] shuffle(long[] arr) {
Random r = new Random();
for (int i = 1, j; i < arr.length; i++) {
j = r.nextInt(i);
long c = arr[i];
arr[i] = arr[j];
arr[j] = c;
}
return arr;
}
int[] uniq(int[] arr) {
arr = scn.shuffle(arr);
Arrays.sort(arr);
int[] rv = new int[arr.length];
int pos = 0;
rv[pos++] = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[i - 1]) {
rv[pos++] = arr[i];
}
}
return Arrays.copyOf(rv, pos);
}
long[] uniq(long[] arr) {
arr = scn.shuffle(arr);
Arrays.sort(arr);
long[] rv = new long[arr.length];
int pos = 0;
rv[pos++] = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[i - 1]) {
rv[pos++] = arr[i];
}
}
return Arrays.copyOf(rv, pos);
}
int[] reverse(int[] arr) {
int l = 0, r = arr.length - 1;
while (l < r) {
arr[l] = arr[l] ^ arr[r];
arr[r] = arr[l] ^ arr[r];
arr[l] = arr[l] ^ arr[r];
l++;
r--;
}
return arr;
}
long[] reverse(long[] arr) {
int l = 0, r = arr.length - 1;
while (l < r) {
arr[l] = arr[l] ^ arr[r];
arr[r] = arr[l] ^ arr[r];
arr[l] = arr[l] ^ arr[r];
l++;
r--;
}
return arr;
}
int[] compress(int[] arr) {
int n = arr.length;
int[] rv = Arrays.copyOf(arr, n);
rv = uniq(rv);
for (int i = 0; i < n; i++) {
arr[i] = Arrays.binarySearch(rv, arr[i]);
}
return arr;
}
long[] compress(long[] arr) {
int n = arr.length;
long[] rv = Arrays.copyOf(arr, n);
rv = uniq(rv);
for (int i = 0; i < n; i++) {
arr[i] = Arrays.binarySearch(rv, arr[i]);
}
return arr;
}
}
} | Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | 056cd94dd506fa8c4e17cf1c8678a129 | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 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.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) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader sc = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(1, sc, out);
out.close();
}
static class Task {
public void solve(int testNumber, InputReader sc, PrintWriter out) throws IOException {
int T=sc.nextInt();
while(T-->0) {
int n=sc.nextInt();
char[] res=sc.next().toCharArray();
Node[] buf=new Node[n];
for(int i=0;i<n;i++) {
buf[i]=new Node(i,res[i]-'0');
}
Arrays.sort(buf);
int[] ans=new int[n];
boolean flag=false;
boolean[] jud=new boolean[n];
for(int i=0;i<10;i++) {
Arrays.fill(jud, false);
int[] f=new int[] {-1,-1,-1};
int cnt=0;
for(Node temp:buf) {
if(temp.val>=i)
break;
if(temp.index<f[1])
break;
f[1]=temp.index;
jud[temp.index]=true;
ans[temp.index]=1;
cnt++;
}
boolean check=false;
int last=n-1;
for(Node temp:buf) {
if(temp.val<=i)
continue;
if(temp.index<f[2])
break;
f[2]=temp.index;
if(!check) {
check=true;
last=temp.index;
}
cnt++;
jud[temp.index]=true;
ans[temp.index]=2;
}
for(Node temp:buf) {
if(temp.val==i) {
if(temp.index>f[1]) {
f[1]=temp.index;
cnt++;
jud[temp.index]=true;
ans[temp.index]=1;
}
}
}
f[2]=-1;
for(Node temp:buf) {
if(temp.val==i) {
if(jud[temp.index])
continue;
if(temp.index<last&&temp.index>f[2]) {
f[2]=temp.index;
cnt++;
jud[temp.index]=true;
ans[temp.index]=2;
}
}
}
if(cnt==n) {
flag=true;
break;
}
}
if(flag) {
for(int k:ans)
out.print(k);
out.println();
}
else
out.println("-");
}
}
}
static class Node implements Comparable<Node>{
public int index;
public int val;
public Node(int index,int val) {
this.index=index;
this.val=val;
}
@Override
public int compareTo(Node o) {
if(this.val==o.val)
return this.index-o.index;
return this.val-o.val;
}
}
static class InputReader {
private InputStreamReader reader;
private char[] buf;
private int len, now;
public InputReader(InputStream stream) {
reader = new InputStreamReader(stream);
buf = new char[1024];
len = 0;
now = 0;
}
public String next() throws IOException {
if (!hasNext()) throw new NullPointerException();
StringBuilder sb = new StringBuilder();
while (!isSpaceChar(buf[now])) {
sb.append(buf[now]);
if (!move()) break;
}
return sb.toString();
}
public int nextInt() throws IOException {
if (!hasNext()) throw new NullPointerException();
boolean x = false;
if (buf[now] == '-') {
x = true;
if (!move()) throw new NumberFormatException();
}
int ans = 0;
while (!isSpaceChar(buf[now])) {
if (isNum(buf[now])) ans = ans * 10 + buf[now] - '0';
else throw new NumberFormatException();
if (!move()) break;
}
return (x ? -1 : 1) * ans;
}
public String nextLine() throws IOException {
if (!hasNextLine()) throw new NullPointerException();
StringBuilder sb = new StringBuilder();
while (buf[now] != '\n') {
sb.append(buf[now]);
if (!move()) return sb.toString();
}
now++;
return sb.toString();
}
public long nextLong() throws IOException {
if (!hasNext()) throw new NullPointerException();
boolean x = false;
if (buf[now] == '-') {
x = true;
if (!move()) throw new NumberFormatException();
}
long ans = 0;
while (!isSpaceChar(buf[now])) {
if (isNum(buf[now])) ans = ans * 10 + buf[now] - '0';
else throw new NumberFormatException();
if (!move()) break;
}
return (x ? -1 : 1) * ans;
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public int nextHexInt() throws IOException {
if (!hasNext()) throw new NullPointerException();
boolean x = false;
if (buf[now] == '-') {
x = true;
if (!move()) throw new NumberFormatException();
}
int ans = 0;
while (!isSpaceChar(buf[now])) {
if (isHex(buf[now])) ans = ans * 16 + toHex(buf[now]);
else throw new NumberFormatException();
if (!move()) break;
}
return (x ? -1 : 1) * ans;
}
public char nextChar() throws IOException {
if (!hasNext()) throw new NullPointerException();
char tmp = buf[now];
move();
return tmp;
}
public int next(char[] s) throws IOException {
if (!hasNext()) throw new NullPointerException();
int len=0;
while (!isSpaceChar(buf[now])&&len<s.length) {
s[len++]=buf[now];
if (!move()) break;
}
return len;
}
public boolean hasNext() throws IOException {
return skip();
}
public boolean hasNextLine() throws IOException {
return now < len || refill();
}
private boolean move() throws IOException {
now++;
return hasNextLine();
}
private boolean skip() throws IOException {
if (!hasNextLine()) return false;
while (isSpaceChar(buf[now])) {
if (!move()) return false;
}
return true;
}
private boolean isSpaceChar(char c) {
return !(c >= 33 && c <= 126);
}
private boolean isNum(char c) {
return c >= '0' && c <= '9';
}
private boolean isHex(char c) {
return c >= '0' && c <= '9' || c >= 'A' && c <= 'F';
}
private int toHex(char c) {
if (c >= '0' && c <= '9') return c - '0';
else return c - 'A' + 10;
}
private boolean refill() throws IOException {
len = reader.read(buf);
now = 0;
return len > 0;
}
}
}
| Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | 3570e928a1b5f9a5e8e561e42053d02f | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 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.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) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader sc = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(1, sc, out);
out.close();
}
static class Task {
public void solve(int testNumber, InputReader sc, PrintWriter out) throws IOException {
int T=sc.nextInt();
while(T-->0) {
int n=sc.nextInt();
char[] str=sc.next().toCharArray();
int[] ida=new int[n+50];
int[] idb=new int[n+50];
int[] idc=new int[n+50];
int sz = n;
boolean flag = false;
int[] ans=new int[n+50];
boolean[] vis=new boolean[n+50];
for (int i = 0; i <= 9; i++){
int la = 0, lb = 0, lc = 0;
char a = '0', b = '0';
for (int j = 0; j < n; j++){
vis[j] = false;
}
for (int j = 0; j < sz; j++){
if (str[j]<'0'+i && str[j]>=a){
a = str[j]; la++; ida[la] = j;
}
}
for (int j = 0; j < sz; j++){
if (str[j]>'0'+i && str[j]>=b){
b = str[j]; lb++; idb[lb] = j;
}
}
if (la == 0){
ida[0] = 0;
}
for (int j = 0; j < sz; j++){
if (str[j] == '0'+i){
if (j > ida[la]){
ida[++la] = j;
vis[j] = true;
}
}
}
for (int j = 0; j < sz; j++){
if (str[j]=='0'+i && !vis[j]){
idc[++lc] = j;
}
}
if (lc == 0){
if (la+lb == sz){
for (int j = 1; j <= la; j++){
ans[ida[j]] = 1;
}
for (int j = 1; j <= lb; j++){
ans[idb[j]] = 2;
}
flag = true;
break;
}
}
else{
if (lb == 0){
if (la+lc == sz){
for (int j = 1; j <= la; j++){
ans[ida[j]] = 1;
}
for (int j = 1; j <= lc; j++){
ans[idc[j]] = 2;
}
flag = true;
break;
}
}
else{
if (idc[lc]<idb[1] && la+lb+lc==sz){
for (int j = 1; j <= la; j++){
ans[ida[j]] = 1;
}
for (int j = 1; j <= lb; j++){
ans[idb[j]] = 2;
}
for (int j = 1; j <= lc; j++){
ans[idc[j]] = 2;
}
flag = true;
break;
}
}
}
}
if (!flag){
out.println("-");
}
else{
for (int i = 0; i < sz; i++){
out.print(ans[i]);
}
out.println();
}
}
}
}
static class Node implements Comparable<Node>{
int index;
int val;
public Node(int index,int val) {
this.index=index;
this.val=val;
}
@Override
public int compareTo(Node o) {
if(this.val==o.val)
return this.index-o.index;
return this.val-o.val;
}
}
static class InputReader {
private InputStreamReader reader;
private char[] buf;
private int len, now;
public InputReader(InputStream stream) {
reader = new InputStreamReader(stream);
buf = new char[1024];
len = 0;
now = 0;
}
public String next() throws IOException {
if (!hasNext()) throw new NullPointerException();
StringBuilder sb = new StringBuilder();
while (!isSpaceChar(buf[now])) {
sb.append(buf[now]);
if (!move()) break;
}
return sb.toString();
}
public int nextInt() throws IOException {
if (!hasNext()) throw new NullPointerException();
boolean x = false;
if (buf[now] == '-') {
x = true;
if (!move()) throw new NumberFormatException();
}
int ans = 0;
while (!isSpaceChar(buf[now])) {
if (isNum(buf[now])) ans = ans * 10 + buf[now] - '0';
else throw new NumberFormatException();
if (!move()) break;
}
return (x ? -1 : 1) * ans;
}
public String nextLine() throws IOException {
if (!hasNextLine()) throw new NullPointerException();
StringBuilder sb = new StringBuilder();
while (buf[now] != '\n') {
sb.append(buf[now]);
if (!move()) return sb.toString();
}
now++;
return sb.toString();
}
public long nextLong() throws IOException {
if (!hasNext()) throw new NullPointerException();
boolean x = false;
if (buf[now] == '-') {
x = true;
if (!move()) throw new NumberFormatException();
}
long ans = 0;
while (!isSpaceChar(buf[now])) {
if (isNum(buf[now])) ans = ans * 10 + buf[now] - '0';
else throw new NumberFormatException();
if (!move()) break;
}
return (x ? -1 : 1) * ans;
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public int nextHexInt() throws IOException {
if (!hasNext()) throw new NullPointerException();
boolean x = false;
if (buf[now] == '-') {
x = true;
if (!move()) throw new NumberFormatException();
}
int ans = 0;
while (!isSpaceChar(buf[now])) {
if (isHex(buf[now])) ans = ans * 16 + toHex(buf[now]);
else throw new NumberFormatException();
if (!move()) break;
}
return (x ? -1 : 1) * ans;
}
public char nextChar() throws IOException {
if (!hasNext()) throw new NullPointerException();
char tmp = buf[now];
move();
return tmp;
}
public int next(char[] s) throws IOException {
if (!hasNext()) throw new NullPointerException();
int len=0;
while (!isSpaceChar(buf[now])&&len<s.length) {
s[len++]=buf[now];
if (!move()) break;
}
return len;
}
public boolean hasNext() throws IOException {
return skip();
}
public boolean hasNextLine() throws IOException {
return now < len || refill();
}
private boolean move() throws IOException {
now++;
return hasNextLine();
}
private boolean skip() throws IOException {
if (!hasNextLine()) return false;
while (isSpaceChar(buf[now])) {
if (!move()) return false;
}
return true;
}
private boolean isSpaceChar(char c) {
return !(c >= 33 && c <= 126);
}
private boolean isNum(char c) {
return c >= '0' && c <= '9';
}
private boolean isHex(char c) {
return c >= '0' && c <= '9' || c >= 'A' && c <= 'F';
}
private int toHex(char c) {
if (c >= '0' && c <= '9') return c - '0';
else return c - 'A' + 10;
}
private boolean refill() throws IOException {
len = reader.read(buf);
now = 0;
return len > 0;
}
}
}
| Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | 22682d556e38e2164d557683b69f0ab4 | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 256 megabytes | //package cf584d12;
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class C {
public static void main(String[] args) {
MyScanner sc = new MyScanner();
int tests = sc.nextInt();
for(int wq = 0; wq < tests; wq++) {
int n = sc.nextInt();
char[] s = sc.nextLine().toCharArray();
int[] fP = new int[n];
TreeMap<Integer, TreeSet<Integer>> map = new TreeMap<Integer, TreeSet<Integer>>();
for(int i = 0; i < 10; i++)
map.put(i + '0', new TreeSet<Integer>());
for(int i = 0; i < n; i++)
map.get((int)s[i]).add(i);
boolean poss = true, swap = false;
int currI = -1;
for(int i = '0'; i < '0' + 10; i++)
if(!map.get(i).isEmpty()){
if(map.get(i).first() > currI) {
currI = map.get(i).last();
for(int x : map.get(i))
fP[x] = swap ? 2 : 1;
} else if(!swap) {
swap = true;
for(int x : map.get(i))
fP[x] = x >= currI ? 1 : 2;
currI = map.get(i).floor(currI - 1);
} else
poss = false;
}
if(poss) {
for(int i : fP)
out.print(i);
out.println();
} else
out.println("-");
}
out.close();
}
public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
public static class MyScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
String next() {
while (st == null || !st.hasMoreElements())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | d0f392e15aa6920ff1d246c4bfda9b47 | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 256 megabytes |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.Stack;
import java.util.regex.Pattern;
public class ROUGH {
public static class FastReader {
BufferedReader br;
StringTokenizer st;
//it reads the data about the specified point and divide the data about it ,it is quite fast
//than using direct
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception r) {
r.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());//converts string to integer
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (Exception r) {
r.printStackTrace();
}
return str;
}
}
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
static long mod = (long) (1e9+7);
static int N = (int) 1e5;
// Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
FastReader sc = new FastReader();
int t = sc.nextInt();
while(t-->0) {
int n = sc.nextInt();
char[] s = sc.next().toCharArray();
Integer[] a = new Integer[n];
for(int i=0;i<n;++i) a[i] = new Integer(s[i]-'0');
Integer[] b = a.clone();
int[] c = new int[n];
Arrays.fill(c, 2);
StringBuffer ans = new StringBuffer();
Arrays.sort(a);
int j = 0;
for(int i=0;i<b.length;++i) {
if(a[j].intValue() == b[i].intValue()) {
c[i] = 1;
++j;
}
}
// out.print(Arrays.toString(c));
if(check(a,c,b)) {
for(int x : c) ans.append(x);
out.println(ans);
}else out.println("-");
}
out.close();
}
private static boolean check(Integer[] a, int[] c,Integer[] b) {
List<Integer> temp = new ArrayList<>();
for(int i=0;i<c.length;++i) {
if(c[i] == 1) temp.add(b[i].intValue());
}
for(int i=0;i<c.length;++i) {
if(c[i] == 2) temp.add(b[i].intValue());
}
for(int i=0;i<a.length;++i) {
if(a[i].intValue() != temp.get(i).intValue())
return false;
}
return true;
}
} | Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | 92c10c1b572ae7be73f564829755d4d6 | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
PrintWriter out = new PrintWriter(System.out);
int tc = sc.nextInt();
while (tc-- > 0) {
int n = sc.nextInt();
char[] s = sc.next().toCharArray();
ArrayList<Integer> indices[] = new ArrayList[10];
for (int i = 0; i < 10; i++) {
indices[i] = new ArrayList();
}
for (int i = 0; i < n; i++)
indices[s[i] - '0'].add(i);
int[] ans = new int[n];
int[] max = new int[2];
max[0] = max[1] = -1;
boolean ok = true;
int put = -1;
out: for (int d = 0; d < 10; d++) {
for (int idx : indices[d]) {
if (idx > max[0] && (put == -1 || put == d)) {
ans[idx] = 1;
max[0] = idx;
} else if (idx > max[1]) {
if (put == -1)
put = d;
ans[idx] = 2;
max[1] = idx;
} else {
ok = false;
break out;
}
}
}
int last = -1;
for (int i = 0; i < n; i++) {
if (ans[i] == 1) {
if (s[i] - '0' < last) {
ok = false;
}
last = s[i] - '0';
}
}
for (int i = 0; i < n; i++) {
if (ans[i] == 2) {
if (s[i] - '0' < last) {
ok = false;
}
last = s[i] - '0';
}
}
if (!ok) {
out.println('-');
} else {
for (int x : ans)
out.print(x);
out.println();
}
}
out.close();
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
Scanner(String fileName) throws FileNotFoundException {
br = new BufferedReader(new FileReader(fileName));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
String nextLine() throws IOException {
return br.readLine();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(next());
}
boolean ready() throws IOException {
return br.ready();
}
}
static void sort(int[] a) {
shuffle(a);
Arrays.sort(a);
}
static void shuffle(int[] a) {
int n = a.length;
Random rand = new Random();
for (int i = 0; i < n; i++) {
int tmpIdx = rand.nextInt(n);
int tmp = a[i];
a[i] = a[tmpIdx];
a[tmpIdx] = tmp;
}
}
}
| Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | 00470fb8211c837a344e9c67b87e60fa | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 256 megabytes | import java.io.*;
import java.util.*;
public class C
{
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tok;
public void go() throws IOException
{
StringTokenizer tok = new StringTokenizer(in.readLine());
int zzz = Integer.parseInt(tok.nextToken());
for (int zz = 0; zz < zzz; zz++)
{
ntok();
int n = ipar();
ntok();
char[] arr = spar().toCharArray();
char[] ans = new char[n];
boolean print = false;
for (char curr = '0'; curr <= '9'; curr++)
{
int min1 = 10;
int min2 = 10;
boolean possible = true;
for (int i = n-1; i >= 0; i--)
{
if (arr[i] <= curr && arr[i]-'0' <= min1)
{
ans[i] = '1';
min1 = arr[i]-'0';
}
else if (arr[i] >= curr && arr[i]-'0' <= min2)
{
ans[i] = '2';
min2 = arr[i]-'0';
}
else
{
possible = false;
break;
}
}
if (possible)
{
out.println(ans);
print = true;
break;
}
else
{
// out.println(" " + Arrays.toString(ans));
}
}
if (!print)
{
out.println("-");
// out.println(" " + Arrays.toString(ans));
}
}
out.flush();
in.close();
}
public void ntok() throws IOException
{
tok = new StringTokenizer(in.readLine());
}
public int ipar()
{
return Integer.parseInt(tok.nextToken());
}
public int[] iapar(int n)
{
int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = ipar();
}
return arr;
}
public long lpar()
{
return Long.parseLong(tok.nextToken());
}
public long[] lapar(int n)
{
long[] arr = new long[n];
for (int i = 0; i < n; i++)
{
arr[i] = lpar();
}
return arr;
}
public double dpar()
{
return Double.parseDouble(tok.nextToken());
}
public String spar()
{
return tok.nextToken();
}
public static void main(String[] args) throws IOException
{
new C().go();
}
}
| Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | d9cf9e8d98f40c350f78c33470dca59e | train_002.jsonl | 1568466300 | You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. | 256 megabytes | /**
* BaZ :D
*/
import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class Main
{
static MyScanner scan;
static PrintWriter pw;
static long MOD = 1_000_000_007;
static long INF = 1_000_000_000_000_000_000L;
static long inf = 2_000_000_000;
public static void main(String[] args) {
new Thread(null, null, "BaZ", 1 << 27) {
public void run() {
try {
solve();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}.start();
}
static char c[];
static int n;
static void solve() throws IOException
{
//initIo(true);
initIo(false);
StringBuilder sb = new StringBuilder();
int t = ni();
while (t-->0) {
n = ni();
c = ne().toCharArray();
int i;
for(i=-1;i<=9;++i) {
if(check(i)) {
break;
}
}
if(i==10) {
pl("-");
}
}
pw.flush();
pw.close();
}
static boolean check(int d) {
StringBuilder ans = new StringBuilder();
int max2 = -1, max1 = -1;
int which[] = new int[n];
for(int i=0;i<n;++i) {
int dig = c[i] - '0';
if(dig<d) {
which[i] = 1;
}
else if(dig>d) {
which[i] = 2;
}
}
for(int i=n-1;i>=0;--i) {
if(c[i] - '0' == d) {
which[i] = 1;
}
else if(c[i] - '0' < d) {
break;
}
}
for(int i=0;i<n;++i) {
if(c[i] - '0' == d) {
which[i] = 2;
}
else if(c[i] - '0' > d) {
break;
}
}
for(int i=0;i<n;++i) {
if(which[i]==0) {
return false;
}
if(which[i]==1) {
if(c[i] - '0' < max1) {
return false;
}
else max1 = c[i] - '0';
}
else if(which[i]==2) {
if(c[i] - '0' < max2) {
return false;
}
else max2 = c[i] - '0';
}
ans.append(which[i]);
}
pl(ans);
return true;
}
static void initIo(boolean isFileIO) throws IOException {
scan = new MyScanner(isFileIO);
if(isFileIO) {
pw = new PrintWriter("/Users/amandeep/Desktop/output.txt");
}
else {
pw = new PrintWriter(System.out, true);
}
}
static int ni() throws IOException
{
return scan.nextInt();
}
static long nl() throws IOException
{
return scan.nextLong();
}
static double nd() throws IOException
{
return scan.nextDouble();
}
static String ne() throws IOException
{
return scan.next();
}
static String nel() throws IOException
{
return scan.nextLine();
}
static void pl()
{
pw.println();
}
static void p(Object o)
{
pw.print(o+" ");
}
static void pl(Object o)
{
pw.println(o);
}
static void psb(StringBuilder sb)
{
pw.print(sb);
}
static void pa(String arrayName, Object arr[])
{
pl(arrayName+" : ");
for(Object o : arr)
p(o);
pl();
}
static void pa(String arrayName, int arr[])
{
pl(arrayName+" : ");
for(int o : arr)
p(o);
pl();
}
static void pa(String arrayName, long arr[])
{
pl(arrayName+" : ");
for(long o : arr)
p(o);
pl();
}
static void pa(String arrayName, double arr[])
{
pl(arrayName+" : ");
for(double o : arr)
p(o);
pl();
}
static void pa(String arrayName, char arr[])
{
pl(arrayName+" : ");
for(char o : arr)
p(o);
pl();
}
static void pa(String listName, List list)
{
pl(listName+" : ");
for(Object o : list)
p(o);
pl();
}
static void pa(String arrayName, Object[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(Object o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, int[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(int o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, long[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(long o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, char[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(char o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, double[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(double o : arr[i])
p(o);
pl();
}
}
static class MyScanner
{
BufferedReader br;
StringTokenizer st;
MyScanner(boolean readingFromFile) throws IOException
{
if(readingFromFile) {
br = new BufferedReader(new FileReader("/Users/amandeep/Desktop/input.txt"));
}
else {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
String nextLine()throws IOException
{
return br.readLine();
}
String next() throws IOException
{
if(st==null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws IOException
{
return Integer.parseInt(next());
}
long nextLong() throws IOException
{
return Long.parseLong(next());
}
double nextDouble() throws IOException
{
return Double.parseDouble(next());
}
}
} | Java | ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"] | 2 seconds | ["121212211211\n1\n222222222\n21\n-"] | NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits. | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 886f773e75fa3c770fb70133ff1b595b | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$. | 1,500 | Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). | standard output | |
PASSED | fea744be19b7b4581c51ee4859380e1e | train_002.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes |
// Problem : C. Prime Number
// Contest : Codeforces Round #209 (Div. 2)
// URL : https://codeforces.com/contest/359/problem/C
// Memory Limit : 256 MB
// Time Limit : 1000 ms
// Powered by CP Editor (https://github.com/cpeditor/cpeditor)
import java.io.*;
import java.util.*;
public class a {
public static void main(String[] args) {
FastReader scan = new FastReader();
PrintWriter out = new PrintWriter(System.out);
Task solver = new Task();
//int t = scan.nextInt();
int t = 1;
for(int i = 1; i <= t; i++) solver.solve(i, scan, out);
out.close();
}
static class Task {
public void solve(int testNumber, FastReader sc, PrintWriter pw) {
int n =sc.nextInt();
int k = sc.nextInt();
int[] arr= new int[n];
long sum = 0;
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
sum+=arr[i];
}
shuffle(arr);
Arrays.sort(arr);
HashMap<Integer,Integer> freq = new HashMap<>();
Queue<Integer> q = new LinkedList<>();
for(int i=n-1;i>=0;i--){
q.add(arr[i]);
}
for(;!q.isEmpty();){
int zz = q.poll();
if(!freq.containsKey(zz)){
freq.put(zz,0);
}
freq.put(zz,freq.get(zz)+1);
if(freq.get(zz)>=k){
freq.put(zz,0);
q.add(zz-1);
}
}
int max = 0;
for(int x : freq.keySet()){
if(freq.get(x)>0){
max=Math.max(x,max);
}
}
//pw.println(max);
//pw.println((1l<<31)%1000000007);
pw.println(binpow(k,sum-max,1000000007));
}
long binpow(long a, long b, long m) {
a %= m;
long res = 1;
while (b > 0) {
if ((b & 1)==1)
res = res * a % m;
a = a * a % m;
b >>= 1;
}
return res;
}
}
static void shuffle(int[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
static void shuffle(long[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
long temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(new File(s)));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 8 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | 53d9736d336f26839a8ed7ea7bf4184d | train_002.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.util.*;
import java.io.*;
public class _0359_C_PrimeNumber {
public static void main(String[] args) throws IOException {
int N = readInt(), B = readInt(), arr[] = new int[N+1]; for(int i = 1; i<=N; i++) arr[i] = readInt();
long sum = 0; for(int i = 1; i<=N; i++) sum += arr[i];
PriorityQueue<Long> pq = new PriorityQueue<>(); boolean chk = true;
for(int i = 1; i<=N; i++) pq.add(sum-arr[i]); if(sum == 0) {println(1); exit();}
while(pq.size() >= B && chk) {
long e = pq.peek(); for(int i = 1; i<=B && chk; i++) if(pq.poll() != e) chk = false;
if(!chk) println(pow(B, Math.min(e, sum))); else pq.add(e+1);
}
if(chk) println(pow(B, Math.min(pq.peek(), sum)));
exit();
}
public static long pow(long B, long e) {
if(e == 1) return B; else if(e == 0) return 1;
long half = pow(B, e/2);
if(e%2 == 0) return (half * half)%1000000007; else return ((half * half)%1000000007*B)%1000000007;
}
final private static int BUFFER_SIZE = 1 << 16;
private static DataInputStream din = new DataInputStream(System.in);
private static byte[] buffer = new byte[BUFFER_SIZE];
private static int bufferPointer = 0, bytesRead = 0;
static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
public static 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 static String read() throws IOException {
byte[] ret = new byte[1024];
int idx = 0;
byte c = Read();
while (c <= ' ') {
c = Read();
}
do {
ret[idx++] = c;
c = Read();
} while (c != -1 && c != ' ' && c != '\n' && c != '\r');
return new String(ret, 0, idx);
}
public static int readInt() 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 static long readLong() 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 static double readDouble() 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 static void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private static byte Read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
static void print(Object o) {
pr.print(o);
}
static void println(Object o) {
pr.println(o);
}
static void flush() {
pr.flush();
}
static void println() {
pr.println();
}
static void exit() throws IOException {
din.close();
pr.close();
System.exit(0);
}
}
| Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 8 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | ff465eefcc68c57db9e76fe2a70a384b | train_002.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes |
import java.io.*;
import java.math.*;
import java.util.*;
import static java.util.Arrays.fill;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;
public class C359
{
public static int mod = 1000000007;
public static long INF = (1L << 60);
static FastScanner2 in = new FastScanner2();
static OutputWriter out = new OutputWriter(System.out);
static class Pair
{
long num;
int freq;
Pair(long num,int freq)
{
this.num=num;
this.freq=freq;
}
}
public static void main(String[] args)
{
int n=in.nextInt();
long x=in.nextLong();
long[] arr=new long[n];
long sum=0;
for(int i=0;i<n;i++)
{
arr[i]=in.nextLong();
sum+=arr[i];
}
LinkedList<Pair> queue=new LinkedList<>();
long[] sumarr=new long[n];
for(int i=0;i<n;i++)
{
sumarr[i]=sum-arr[i];
}
Arrays.sort(sumarr);
for(int i=0;i<n;i++)
{
queue.add(new Pair(sumarr[i], 1));
}
long answer=0;
while(!queue.isEmpty())
{
Pair head=queue.poll();
long headnum=head.num;
int headfreq=head.freq;
while(!queue.isEmpty() && queue.peek().num==headnum)
{
headfreq+=queue.poll().freq;
}
if(headfreq%x==0)
queue.addFirst(new Pair(headnum+1, (int) (headfreq/x)));
else
{
answer=headnum;
break;
}
}
answer=min(answer, sum);
//System.out.println(answer);
out.println(pow(x, answer, mod));
out.close();
}
public static long pow(long x, long n)
{
long res = 1;
for (long p = x; n > 0; n >>= 1, p = (p * p))
{
if ((n & 1) != 0)
{
res = (res * p);
}
}
return res;
}
public static long pow(long x, long n, long mod)
{
long res = 1;
for (long p = x; n > 0; n >>= 1, p = (p * p) % mod)
{
if ((n & 1) != 0)
{
res = (res * p % mod);
}
}
return res;
}
public static long gcd(long n1, long n2)
{
long r;
while (n2 != 0)
{
r = n1 % n2;
n1 = n2;
n2 = r;
}
return n1;
}
public static long lcm(long n1, long n2)
{
long answer = (n1 * n2) / (gcd(n1, n2));
return answer;
}
static class FastScanner2
{
private byte[] buf = new byte[1024];
private int curChar;
private int snumChars;
public int read()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = System.in.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isEndOfLine(c));
return res.toString();
}
public String nextString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n)
{
long[] arr = new long[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
}
static class InputReader
{
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream inputstream)
{
reader = new BufferedReader(new InputStreamReader(inputstream));
tokenizer = null;
}
public String nextLine()
{
String fullLine = null;
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
try
{
fullLine = reader.readLine();
} catch (IOException e)
{
throw new RuntimeException(e);
}
return fullLine;
}
return fullLine;
}
public String next()
{
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
try
{
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e)
{
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong()
{
return Long.parseLong(next());
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n)
{
long a[] = new long[n];
for (int i = 0; i < n; i++)
{
a[i] = nextLong();
}
return a;
}
public int nextInt()
{
return Integer.parseInt(next());
}
}
static class OutputWriter
{
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream)
{
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer)
{
this.writer = new PrintWriter(writer);
}
public void print(Object... objects)
{
for (int i = 0; i < objects.length; i++)
{
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void println(Object... objects)
{
print(objects);
writer.println();
}
public void close()
{
writer.close();
}
public void flush()
{
writer.flush();
}
}
} | Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 8 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | b938818995ba6421a9c1ef6a48ccae8c | train_002.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class B {
static final int mod = (int)1e9 + 7;
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt(), x = sc.nextInt(), a[] = new int[n];
long sum = 0;
for(int i = 0; i < n; ++i)
sum += a[i] = sc.nextInt();
PriorityQueue<Long> pq = new PriorityQueue<Long>();
for(int i = 0; i < n; ++i)
pq.add(sum - a[i]);
long y = 0;
while(!pq.isEmpty())
{
long z = pq.remove() - y, m = 1;
while(!pq.isEmpty() && pq.peek() - y == z)
{
++m;
pq.remove();
}
y += z;
if(m % x != 0)
break;
long zz = 0;
while(m % x == 0)
{
++zz;
m /= x;
}
while(m--> 0)
pq.add(zz + y);
}
out.println(modPow(x, Math.min(sum, y)));
out.flush();
out.close();
}
static int modPow(long p, long e)
{
long res = 1;
p %= mod;
while(e > 0)
{
if((e & 1) == 1)
res = res * p % mod;
p = p * p % mod;
e >>= 1;
}
return (int)res;
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public Scanner(FileReader r){ br = new BufferedReader(r);}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException { return Double.parseDouble(next()); }
public boolean ready() throws IOException {return br.ready();}
}
} | Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 8 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | b94619378fb230dbbc3c6a0e60a8598c | train_002.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 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.Map.Entry;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class P359C {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(in, out);
out.close();
}
static class Task {
public void solve(InputReader in, PrintWriter out) {
int n = in.nextInt();
int x = in.nextInt();
int[] a = new int[n];
TreeMap<Integer, Integer> mp = new TreeMap<>();
long sum = 0;
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
if (!mp.containsKey(a[i]))
mp.put(a[i], 0);
sum += a[i];
mp.put(a[i], mp.get(a[i]) + 1);
}
while (!mp.isEmpty()) {
Entry<Integer, Integer> top = mp.lastEntry();
if (top.getValue() % x == 0) {
int k = top.getKey();
int v = top.getValue();
while (v % x == 0) {
v /= x;
k--;
}
if (!mp.containsKey(k))
mp.put(k, 0);
mp.put(k, mp.get(k) + v);
mp.remove(top.getKey());
} else {
out.println(modPow(x, Math.min(sum, (sum - top.getKey())), 1000000007));
return;
}
}
}
private long modPow(int x, long a, long m) {
if (a == 0)
return 1;
if ((a & 1) == 1)
return (x * modPow(x, a - 1, m)) % m;
else {
long val = modPow(x, a / 2, m);
return (val * val) % m;
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
| Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 8 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | fc82702b5f3f66a705cf784535deb221 | train_002.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class C {
static final int mod = (int) 1e9 + 7;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt(), x = sc.nextInt(), a[] = new int[n];
long sum = 0;
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
sum += a[i];
}
PriorityQueue<Long> pq = new PriorityQueue<Long>();
for (int i = 0; i < n; ++i)
pq.add(sum - a[i]);
long y = 0;
while (!pq.isEmpty()) {
long z = pq.remove() - y, m = 1;
while (!pq.isEmpty() && pq.peek() - y == z) {
m++;
pq.remove();
}
y += z;
if (m % x != 0)
break;
long zz = 0;
while (m % x == 0) {
zz++;
m /= x;
}
while (m-- > 0)
pq.add(zz + y);
}
out.println(modPow(x, Math.min(sum, y)));
out.flush();
out.close();
}
static int modPow(long p, long e) {
long res = 1;
p %= mod;
while (e > 0) {
if ((e & 1) == 1)
res = res * p % mod;
p = p * p % mod;
e >>= 1;
}
return (int) res;
}
static class Scanner {
BufferedReader bf;
StringTokenizer st;
public Scanner(InputStream i) {
bf = new BufferedReader(new InputStreamReader(i));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(bf.readLine());
return st.nextToken();
}
public int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
}
} | Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 8 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | 77653f36a6047f25ded27602b40a2d1a | train_002.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | /*
[ ( ^ _ ^ ) ]
*/
// problem: cf/359/C
// package cf.c;
import java.io.*;
import java.util.*;
public class c {
int INF = (int)1e9;
long MOD = 1000000007;
long pow(long a, long n, long mod) {
long rs = 1;
while (n > 0) {
if (n % 2 == 1) {
rs *= a;
rs %= mod;
}
n >>= 1;
a *= a;
a %= mod;
}
return rs;
}
boolean check(long x, Long[] a, long m) {
// show("checking for", x, m, a);
int n = a.length;
long[] c = new long[n];
c[0] = 1;
if(n==1) {
if(a[0]>=m) return true;
else return false;
}
for(int i=1; i<n; i++) {
// show("i", a[i], c[i]);
if(a[i]==a[i-1]) {
c[i] = c[i-1] + 1;
} else {
c[i] = 1;
if(a[i-1]<m) {
long p = a[i-1];
long cnt = c[i-1];
while(p<a[i] && cnt>0) {
if(p<m && cnt%x!=0) return false;
p++;
cnt /= x;
}
c[i] += cnt;
}
}
}
// show("c", c);
if(a[n-1]<m) {
long p = a[n-1];
long cnt = c[n-1];
while(p<m && cnt>0) {
if(cnt%x!=0) return false;
p++;
cnt = cnt/x;
}
}
// show("ret ture");
return true;
}
void solve(InputReader in, PrintWriter out) throws IOException {
int n = in.nextInt();
long x = in.nextLong();
Long[] a = new Long[n];
long sum = 0;
for(int i=0; i<n; i++) {
a[i] = in.nextLong();
sum += a[i];
}
for(int i=0; i<n; i++) {
a[i] = sum - a[i];
}
Arrays.sort(a);
long l = 0, h = sum;
while(l<h) {
long m = (l+h+1)/2;
if(check(x, a, m)) {
l = m;
} else {
h = m-1;
}
}
out.println(pow(x, l, MOD));
}
public static void main(String[] args) throws IOException {
InputReader in = new InputReader();
PrintWriter out = new PrintWriter(System.out);
int t = 1;//in.nextInt();
while(t-- >0) {
new c().solve(in, out);
}
out.close();
}
public static void show(Object... o) {
System.out.println(Arrays.deepToString(o));
}
static class InputReader {
static BufferedReader br;
static StringTokenizer st;
public InputReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble() { return Double.parseDouble(next()); }
}
} | Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 8 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | a30da1757c0d390471d7915134be87ee | train_002.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.LinkedList;
public class PrimeNumber
{
public static void main(String[] args)
{
new PrimeNumber(System.in, System.out);
}
private static class Solver implements Runnable
{
static final long MOD = (long) 1e9 + 7;
int n;
long x;
int[] a;
InputReader in;
PrintWriter out;
void solve() throws IOException
{
n = in.nextInt();
x = in.nextInt();
a = in.nextIntArray(n);
long tot = 0;
long[] diff = new long[n];
for (int aa : a)
tot += aa;
for (int i = 0; i < n; i++)
diff[i] = tot - a[i];
Arrays.sort(diff);
LinkedList<Pair> linkedList = new LinkedList<>();
for (int i = 0; i < n; i++)
linkedList.add(new Pair(diff[i], 1));
long ans = 0;
while (linkedList.size() > 0)
{
Pair pair = linkedList.poll();
long num = pair.num;
int freq = pair.freq;
while (!linkedList.isEmpty() && linkedList.peek().num == num)
freq += linkedList.poll().freq;
if (freq % x == 0)
linkedList.addFirst(new Pair(num + 1, (int) (freq / x)));
else
{
ans = num;
break;
}
}
ans = Math.min(ans, tot);
out.println(CMath.modPower(x, ans, MOD));
}
class Pair
{
long num;
int freq;
public Pair(long num, int freq)
{
this.num = num;
this.freq = freq;
}
}
Solver(InputReader in, PrintWriter out)
{
this.in = in;
this.out = out;
}
@Override
public void run()
{
try
{
solve();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
private static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
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++];
}
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;
}
int[] nextIntArray(int arraySize)
{
int array[] = new int[arraySize];
for (int i = 0; i < arraySize; i++)
array[i] = nextInt();
return array;
}
boolean isSpaceChar(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
void close()
{
try
{
stream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
InputReader(InputStream stream)
{
this.stream = stream;
}
}
private static class CMath
{
static long modPower(long number, long power, long mod)
{
if (number == 1 || number == 0 || power == 0)
return 1;
number = mod(number, mod);
if (power == 1)
return number;
long square = mod(number * number, mod);
if (power % 2 == 0)
return modPower(square, power / 2, mod);
else
return mod(modPower(square, power / 2, mod) * number, mod);
}
static long mod(long number, long mod)
{
return number - (number / mod) * mod;
}
}
private PrimeNumber(InputStream inputStream, OutputStream outputStream)
{
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Thread thread = new Thread(null, new Solver(in, out), "Solver", 1 << 29);
try
{
thread.start();
thread.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
in.close();
out.flush();
out.close();
}
}
| Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 8 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | f52dd16508143394c57fa3a3198bf284 | train_002.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.AbstractCollection;
import java.util.PriorityQueue;
import java.util.AbstractQueue;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
PrimeNumber solver = new PrimeNumber();
solver.solve(1, in, out);
out.close();
}
static class PrimeNumber {
static long MOD = (long) (Math.pow(10, 9) + 7);
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
long x = in.nextLong();
long a[] = new long[n];
long sum = 0;
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
sum += a[i];
}
PriorityQueue<Long> pq = new PriorityQueue<>();
for (int i = 0; i < n; i++) {
pq.add(sum - a[i]);
}
long ans = 0;
while (!pq.isEmpty()) {
long v = pq.remove();
long count = 1;
while (!pq.isEmpty() && pq.peek() == v) {
count++;
pq.remove();
}
if (count % x != 0) {
ans = v;
break;
} else {
count /= x;
for (int i = 0; i < count; i++) {
pq.add(v + 1);
}
}
}
out.println(pow(x, Math.min(ans, sum)));
}
public long pow(long base, long p) {
if (p == 0) {
return 1;
}
long po = pow(base, p / 2) % MOD;
po = (po * po) % MOD;
if (p % 2 == 0) {
return po;
} else {
return (po * base) % MOD;
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 8 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | a19f6bdadf9e821b150ce5f676453445 | train_002.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | //package a2oj_ladder_C;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.TreeMap;
import java.util.TreeSet;
@SuppressWarnings("unused")
public class Prime359C {
InputStream is;
PrintWriter out;
String INPUT = "";
int mod = (int)(Math.pow(10,9)+7);
void solve()
{
int n = ni();
int x = ni();
int a[] = na(n);
Arrays.sort(a);
long yt = 0;
for(int i : a) yt+=i;
HashMap<Integer , Integer> hm = new HashMap<>();
for(int i : a) {
hm.put(i, hm.getOrDefault(i, 0)+1);
}
int res = -1;
HashMap<Integer , Integer> f = new HashMap<>();
int prev = 0;
int curr = hm.size();
while(prev != curr) {
for(int i : hm.keySet()) {
res = hm.get(i);
int power = 0;
while(res % x == 0) {
res = res/x;
power++;
}
f.put(i-power , f.getOrDefault(i-power, 0)+res);
}
prev = curr;
curr = f.size();
hm = f;
f = new HashMap<>();
}
//out.println(hm);
res = -1;
for(int i : hm.keySet()) {
if(res != -1) res = (int)__gcd(res, hm.get(i));
else res = hm.get(i);
}
//out.println(res);
int power = 0;
while(res % x == 0) {
res = res/x;
power++;
}
//out.println(power);
int max = Integer.MIN_VALUE;
long sum = 0;
for(int i : hm.keySet()) {
sum += i;
max = Math.max(max, i);
}
long comm = Math.min(sum, sum-max+power);
long fin = sum - comm;
//out.println(fin);
out.println(power(x , yt - fin , mod));
//100/(5^500) + 125/(5^501) = 125/5^500 100*5^501 + 125*5^500 5 ^ 500 * 25(4 * 5 + 5)
}
void run() throws Exception
{
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new Prime359C().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int[][] na(int n , int m)
{
int[][] a = new int[n][m];
for(int i = 0;i < n;i++)
for(int j = 0 ; j<m ; j++) a[i][j] = 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();
}
}
void display2D(int a[][]) {
for(int i[] : a) {
for(int j : i) {
out.print(j+" ");
}
out.println();
}
}
int[][] creategraph(int n , int m) {
int g[][] = new int[n+1][];
int from[] = new int[m];
int to[] = new int[m];
int ct[] = new int[n+1];
for(int i = 0 ; i<m; i++) {
from[i] = ni();
to[i] = ni();
ct[from[i]]++;
ct[to[i]]++;
}
int parent[] = new int[n+1];
for(int i = 0 ; i<n+1 ; i++) g[i] = new int[ct[i]];
for(int i = 0 ; i<m ; i++) {
g[from[i]][--ct[from[i]]] = to[i];
g[to[i]][--ct[to[i]]] = from[i];
}
return g;
}
static long __gcd(long a, long b)
{
if(b == 0)
{
return a;
}
else
{
return __gcd(b, a % b);
}
}
// To compute x^y under modulo m
static long power(long x, long y, long p)
{
// Initialize result
long res = 1;
// Update x if it is more than or
// equal to p
x = x % p;
while (y > 0)
{
// If y is odd, multiply x
// with result
if (y % 2 == 1)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
// Function to find modular
// inverse of a under modulo m
// Assumption: m is prime
static long modInverse(long a, int m)
{
if (__gcd(a, m) != 1) {
//System.out.print("Inverse doesn't exist");
return -1;
}
else {
// If a and m are relatively prime, then
// modulo inverse is a^(m-2) mode m
// System.out.println("Modular multiplicative inverse is "
// +power(a, m - 2, m));
return power(a, m - 2, m);
}
}
static long nCrModPFermat(int n, int r,
int p , long fac[])
{
// Base case
if (r == 0)
return 1;
// Fill factorial array so that we
// can find all factorial of r, n
// and n-r
long t = (fac[n]* modInverse(fac[r], p))%p;
return ( (t* modInverse(fac[n-r], p))% p);
}
private static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); }
}
| Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 8 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | 464ac17afedaee818bb017e8a16259b9 | train_002.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.AbstractCollection;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.util.PriorityQueue;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.File;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Atharva Nagarkar
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
JoltyScanner in = new JoltyScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
CPrimeNumber solver = new CPrimeNumber();
solver.solve(1, in, out);
out.close();
}
static class CPrimeNumber {
public void solve(int testNumber, JoltyScanner in, PrintWriter out) {
final int mod = (int) 1e9 + 7;
int n = in.nextInt();
long x = in.nextInt();
int[] a = new int[n];
long tsum = 0;
for (int i = 0; i < n; ++i) tsum += (a[i] = in.nextInt());
PriorityQueue<Long> sums = new PriorityQueue<>(Long::compare);
for (int i = 0; i < n; ++i) sums.add(tsum - a[i]);
long expo = -1;
while (!sums.isEmpty()) {
int count = 1;
expo = sums.poll();
while (!sums.isEmpty() && sums.peek() == expo) {
++count;
sums.poll();
}
if (count % x != 0) {
break;
}
for (int i = 0; i < count / x; ++i) {
sums.add(expo + 1);
}
}
if (expo > tsum) expo = tsum;
long ans = 1;
while (expo > 0) {
if (expo % 2 == 0) {
expo /= 2;
x = (x * x) % mod;
} else {
expo--;
ans = (ans * x) % mod;
}
}
out.println(ans);
}
}
static class JoltyScanner {
public int BS = 1 << 16;
public char NC = (char) 0;
public byte[] buf = new byte[BS];
public int bId = 0;
public int size = 0;
public char c = NC;
public double num = 1;
public BufferedInputStream in;
public JoltyScanner(InputStream is) {
in = new BufferedInputStream(is, BS);
}
public JoltyScanner(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;
}
}
}
| Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 8 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | a5faef47ebe947d12f5d254c5a0aad03 | train_002.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Main extends PrintWriter {
final Random rand = new Random(31);
final int inf = (int) 1e9;
final long linf = (long) 1e18;
final static String IO = "_std";
final int mod = inf + 7;
int modpow(int a, long p) {
if (p == 0) {
return 1;
}
long t = modpow(a, p / 2);
t = (t * t) % mod;
if (p % 2 == 1) {
t = t * a % mod;
}
return (int) t;
}
void solve() throws IOException {
int n = nextInt();
int x = nextInt();
int[] a = nextIntArray(n);
if (n == 1) {
println(1);
return;
}
long sum = 0;
for (int i = 0; i < n; i++) {
sum += a[i];
}
TreeMap<Long, Integer> cnt = new TreeMap<>();
for (int i = 0; i < n; i++) {
long p = sum - a[i];
cnt.compute(p, (key, v) -> v == null ? 1 : v + 1);
}
long low = -1;
while (true) {
low = cnt.ceilingKey(low + 1);
int c = cnt.get(low);
cnt.compute(low + 1, (k, v) -> v == null ? (c / x) : (v + c / x));
if (c % x != 0) {
break;
}
}
println(modpow(x, min(low, sum)));
}
BufferedReader in;
StringTokenizer stok;
Main() {
super(System.out);
in = new BufferedReader(new InputStreamReader(System.in));
}
Main(String fileIn, String fileOut) throws IOException {
super(fileOut);
in = new BufferedReader(new FileReader(fileIn));
}
public static void main(String[] args) throws IOException {
Main main;
if ("_std".equals(IO)) {
main = new Main();
} else if ("_iotxt".equals(IO)) {
main = new Main("input.txt", "output.txt");
} else {
main = new Main(IO + ".in", IO + ".out");
}
main.solve();
main.close();
}
String next() throws IOException {
while (stok == null || !stok.hasMoreTokens()) {
String s = in.readLine();
if (s == null) {
return null;
}
stok = new StringTokenizer(s);
}
return stok.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
int[] nextIntArray(int len) throws IOException {
int[] a = new int[len];
for (int i = 0; i < len; i++) {
a[i] = nextInt();
}
return a;
}
int[] nextIntArraySorted(int len) throws IOException {
int[] a = nextIntArray(len);
shuffle(a);
Arrays.sort(a);
return a;
}
void shuffle(int[] a) {
for (int i = 1; i < a.length; i++) {
int x = rand.nextInt(i + 1);
int _ = a[i];
a[i] = a[x];
a[x] = _;
}
}
void shuffleAndSort(int[] a) {
shuffle(a);
Arrays.sort(a);
}
boolean nextPermutation(int[] p) {
for (int a = p.length - 2; a >= 0; --a) {
if (p[a] < p[a + 1])
for (int b = p.length - 1; ; --b)
if (p[b] > p[a]) {
int t = p[a];
p[a] = p[b];
p[b] = t;
for (++a, b = p.length - 1; a < b; ++a, --b) {
t = p[a];
p[a] = p[b];
p[b] = t;
}
return true;
}
}
return false;
}
<T> List<T>[] createAdjacencyList(int n) {
List<T>[] res = new List[n];
for (int i = 0; i < n; i++) {
res[i] = new ArrayList<>();
}
return res;
}
void println(Object... a) {
for (int i = 0; i < a.length; i++) {
if (i != 0) {
print(" ");
}
print(a[i]);
}
println();
}
} | Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 8 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | 90a03ffa273c461721a6eb08ca503183 | train_002.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Solution implements Runnable{
FastScanner sc;
PrintWriter pw;
final class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
e.printStackTrace();
}
}
public long nlo() {
return Long.parseLong(next());
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
e.printStackTrace();
}
return st.nextToken();
}
public int ni() {
return Integer.parseInt(next());
}
public String nli() {
String line = "";
if (st.hasMoreTokens()) line = st.nextToken();
else try {
return br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
while (st.hasMoreTokens()) line += " " + st.nextToken();
return line;
}
public double nd() {
return Double.parseDouble(next());
}
}
public static void main(String[] args) throws Exception
{
new Thread(null,new Solution(),"codeforces",1<<28).start();
}
public void run()
{
sc=new FastScanner();
pw=new PrintWriter(System.out);
solve();
pw.flush();
pw.close();
}
public long gcd(long a,long b)
{
return b==0L?a:gcd(b,a%b);
}
public long ppow(long a,long b,long mod)
{
if(b==0L)
return 1L;
long tmp=1;
while(b>1L)
{
if((b&1L)==1)
tmp*=a;
a*=a;
a%=mod;
tmp%=mod;
b>>=1;
}
return (tmp*a)%mod;
}
public int gcd(int x,int y)
{
return y==0?x:gcd(y,x%y);
}
//////////////////////////////////
///////////// LOGIC ///////////
////////////////////////////////
public void solve()
{
int n=sc.ni();
long x=sc.ni();
long[] prr=new long[64];
for(int i=0;i<64;i++)
prr[i]=ppow(x,i,Long.MAX_VALUE);
long sum=0;
long[] arr=new long[n];
for(int i=0;i<n;i++)
{
arr[i]=sc.ni();
sum+=arr[i];
}
TreeMap<Long,Long> map=new TreeMap();
for(int i=n-1;i>=0;i--)
{
long k=sum-arr[i];
if(!map.containsKey(k))
map.put(k,0L);
map.put(k,map.get(k)+1L);
}
while(map.size()>0)
{
long s=map.firstKey();
long k=map.get(s);
long p=(long)(Math.log(k)/Math.log(x));
if(k%x!=0)
{
pw.println(ppow(x,Math.min(s,sum),1000000007));
return;
}
for(int l=(int)p;l>0;l--)
{
long j=0;
while(k>=prr[l])
{
j++;
k-=prr[l];
}
if(j>0)
{
long tmp=s+l;
if(!map.containsKey(tmp))
map.put(tmp,0L);
map.put(tmp,map.get(tmp)+j);
}
}
map.remove(s);
}
}
} | Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 8 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | ce9059e8954764ce99e9ea6ed2fd50c9 | train_002.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.util.*;
public class PrimeNumber {
private static final long MOD=1000000007;
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
long n=sc.nextLong(),x=sc.nextLong(),sum=0;
TreeMap<Integer,Integer>pows=new TreeMap<Integer,Integer>();
for(int i=0;i<n;i++){
int a=sc.nextInt();
sum+=a;
boolean b;
do{
b=false;
if(!pows.containsKey(a))
pows.put(a,1);
else
pows.put(a,pows.get(a)+1);
if(pows.get(a)==x&&a>0){
pows.remove(a--);
b=true;
}
}while(b);
}
sc.close();
System.out.println(power(x,(sum-pows.lastKey())%(MOD-1)));
}
public static long power(long base, long pow){
if(pow==0)
return 1;
if(pow==1)
return base;
long p=power(base,pow/2);
return ((p*p)%MOD)*(pow%2==1?base:1)%MOD;
}
} | Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 8 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | 5a738f467df3ed12968c51a69e889305 | train_002.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class PrimeNumber {
static int a[] = new int[100000+5];
static int MOD = 1000 * 1000 * 1000 + 7;
public static void main(String[]args)throws Throwable
{
PriorityQueue<Long> powers = new PriorityQueue();
int x;
long n;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n = new Integer(st.nextToken());
x = new Integer(st.nextToken());
st = new StringTokenizer(br.readLine());
long sum = 0;
for(int i = 0 ; i < n ; ++i)
{
a[i] = new Integer(st.nextToken());
sum += a[i];
}
for(int i = 0 ; i < n ; i++)
{
powers.add(sum - a[i]);
}
long sol = powers.poll();
int cnt = 1;
while(true)
{
while(!powers.isEmpty())
{
long out_p = powers.poll() - sol;
if(out_p == 0) ++cnt;
else
{
powers.add(out_p + sol);
break;
}
}
//sol += (v-sol);
//System.err.println(sol);
if(cnt == 0 || cnt % x != 0) break;
++sol;
cnt /= x;
}
sol = Math.min(sum,sol);
BigInteger res = new BigInteger(x+"");
res = res.modPow(new BigInteger(sol+""), new BigInteger(MOD+""));
System.out.println(res);
}
}
| Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 8 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | 494879c9d1641eeff55aa2d5e858636a | train_002.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | //package com.company;
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
new Main().run();
}
public void run() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
long n,x;
String [] line=in.readLine().split(" ");
n=Long.parseLong(line[0]);
x=Long.parseLong(line[1]);
line=in.readLine().split(" ");
ArrayList <Long> a = new ArrayList(),b=new ArrayList();
long sum=0;
for (int i = 0; i < n;i++){
a.add(Long.parseLong(line[i]));
sum+=a.get(i);
}
for (int i = 0; i < n;i++){
b.add(sum - a.get(i));
}
Collections.sort(b);
Collections.reverse(b);
while (true){
long v=b.get(b.size()-1);
long cnt=0;
while (b.size() > 0 && b.get(b.size() - 1) == v) {
cnt ++;
b.remove(b.size()-1);
}
if (cnt % x != 0) {
v = Math.min(v, sum);
System.out.println(bpow(x, v));
break;
}
else {
cnt /= x;
for(int i = 0; i < cnt; i++)
b.add(v + 1);
}
}
}
long bpow(long x,long v){
if (v == 0)
return 1 % 1000000007;
if (v % 2 == 1)
return (x * bpow(x, v - 1)) % 1000000007;
long r = bpow(x, v / 2);
return (r * r) % 1000000007;
}
}
| Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 8 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | 7e3c2d47d75c377a5392d5073f7c7c2c | train_002.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class problem359C{
public static void main(String[]args)throws IOException{
BufferedReader x=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer(x.readLine());
int n=Integer.parseInt(st.nextToken());
String base=st.nextToken();
int b=Integer.parseInt(base);
st=new StringTokenizer(x.readLine());
long sum=0;
long[]arr=new long[n];
for (int i=0; i<n; i++){
long cur=Long.parseLong(st.nextToken());
sum+=cur;
arr[i]=cur;
}
for (int i=0; i<n; i++){
arr[i]=sum-arr[i];
}
Arrays.sort(arr);
long next=0;
long cur=arr[0];
long ans=0;
boolean done=false;
for (int i=0; i<n; i++){
if (arr[i]==cur){
next++;
}else{
if (next%b==0){
next=next/b;
if (arr[i]!=cur+1){
cur++;
i--;
}else{
cur=arr[i];
next++;
}
}else{
//cur is what you want
ans=cur;
done=true;
break;
}
}
}
if (!done){
ans=arr[n-1];
while (next%b==0){
next=next/b;
ans++;
}
}
if (ans==0)ans=cur;
ans=Math.min(ans,sum);
BigInteger exp=new BigInteger(Long.toString(ans));
System.out.println(new BigInteger(base).modPow(exp, new BigInteger("1000000007")));
}
} | Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 8 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | 997a7eb032d28c148e09fb76ce34f18a | train_002.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.PriorityQueue;
import java.io.IOException;
import java.util.StringTokenizer;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
}
class TaskC {
final long MOD = (long) 1e9 + 7;
final int N = (int) 1e5;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt(), m = in.nextInt();
int a[] = new int[N];
long sum = 0;
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
sum += a[i];
}
PriorityQueue<Long> pe = new PriorityQueue<>();
for (int i = 0; i < n; i++) {
pe.add(sum - a[i]);
}
int size = 1;
long cur = pe.poll();
while((size % m == 0) || (pe.size() > 0 && pe.peek() == cur)) {
while (pe.size() > 0 && pe.peek() == cur) {
size++;
pe.poll();
}
if (size % m == 0) {
size /= m;
cur++;
}
}
out.print(fast_pow(m, Math.min(sum, cur)));
}
public long fast_pow(long x, long pow) {
if (pow == 0) {
return 1;
}
return (fast_pow((x * x) % MOD, pow / 2) * (pow % 2 == 0 ? 1 : x)) % MOD;
}
}
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 | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 8 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | 2d37fb776b4c16941a19acebd9e12f69 | train_002.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 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 Pradyumn Agrawal coderbond007
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, FastReader in, PrintWriter out) {
int n = in.nextInt();
int x = in.nextInt();
int[] a = in.nextIntArray(n);
int mod = 1000000007;
long s = 0;
for (int v : a) s += v;
long[] b = new long[n];
for (int i = 0; i < n; i++) b[i] = s - a[i];
int same = 0;
long val = b[n - 1];
out:
for (int i = n - 1; i >= 0; i--) {
if (b[i] == val) {
same++;
} else {
while (b[i] > val) {
if (same % x != 0) {
break out;
}
same /= x;
val++;
}
same++;
}
}
while (true) {
if (same % x != 0) {
break;
}
same /= x;
val++;
}
val = Math.min(val, s);
out.println(NT.powerMod(x, val, mod));
}
}
static class NT {
public static long powerMod(long a, long n, long mod) {
// a %= mod;
long ret = 1;
int x = 63 - Long.numberOfLeadingZeros(n);
for (; x >= 0; x--) {
ret = ret * ret % mod;
if (n << 63 - x < 0) ret = ret * a % mod;
}
return ret;
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int pnumChars;
private FastReader.SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (pnumChars == -1) {
throw new InputMismatchException();
}
if (curChar >= pnumChars) {
curChar = 0;
try {
pnumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (pnumChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c == ',') {
c = read();
}
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[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = nextInt();
}
return array;
}
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 | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 8 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | 4b4a419d5551a147f7335be776a10f7e | train_002.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | /*
*
* @Author Ajudiya_13(Bhargav Girdharbhai Ajudiya)
* Dhirubhai Ambani Institute of Information And Communication Technology
*
*/
import java.util.*;
import java.io.*;
import java.lang.*;
public class Code332
{
public static void main(String[] args)
{
InputReader in = new InputReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = in.nextInt();
long x = in.nextLong();
long []a = new long[n];
long sum = 0;
for(int i=0;i<n;i++)
{
a[i] = in.nextLong();
sum += a[i];
}
Deque<Long> arr = new LinkedList();
for(int i=0;i<n;i++)
arr.add(sum-a[i]);
while(true)
{
long v = arr.getLast();
long cnt = 0;
while(arr.size()>0 && arr.getLast()==v)
{
cnt++;
arr.removeLast();
}
if(cnt%x!=0)
{
v = Math.min(v, sum);
pw.println(modularExponentiation(x, v, mod));
break;
}
else
{
cnt/=x;
for(int i=0;i<cnt;i++)
arr.addLast(v+1);
}
}
pw.flush();
pw.close();
}
static class InputReader
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int snext()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
public String readString()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static long mod = 1000000007;
public static int d;
public static int p;
public static int q;
public static int[] suffle(int[] a,Random gen)
{
int n = a.length;
for(int i=0;i<n;i++)
{
int ind = gen.nextInt(n-i)+i;
int temp = a[ind];
a[ind] = a[i];
a[i] = temp;
}
return a;
}
public static void swap(int a, int b){
int temp = a;
a = b;
b = temp;
}
public static HashSet<Integer> primeFactorization(int n)
{
HashSet<Integer> a =new HashSet<Integer>();
for(int i=2;i*i<=n;i++)
{
while(n%i==0)
{
a.add(i);
n/=i;
}
}
if(n!=1)
a.add(n);
return a;
}
public static void sieve(boolean[] isPrime,int n)
{
for(int i=1;i<n;i++)
isPrime[i] = true;
isPrime[0] = false;
isPrime[1] = false;
for(int i=2;i*i<n;i++)
{
if(isPrime[i] == true)
{
for(int j=(2*i);j<n;j+=i)
isPrime[j] = false;
}
}
}
public static int GCD(int a,int b)
{
if(b==0)
return a;
else
return GCD(b,a%b);
}
public static long GCD(long a,long b)
{
if(b==0)
return a;
else
return GCD(b,a%b);
}
public static void extendedEuclid(int A,int B)
{
if(B==0)
{
d = A;
p = 1 ;
q = 0;
}
else
{
extendedEuclid(B, A%B);
int temp = p;
p = q;
q = temp - (A/B)*q;
}
}
public static long LCM(long a,long b)
{
return (a*b)/GCD(a,b);
}
public static int LCM(int a,int b)
{
return (a*b)/GCD(a,b);
}
public static int binaryExponentiation(int x,int n)
{
int result=1;
while(n>0)
{
if(n % 2 ==1)
result=result * x;
x=x*x;
n=n/2;
}
return result;
}
public static long binaryExponentiation(long x,long n)
{
long result=1;
while(n>0)
{
if(n % 2 ==1)
result=result * x;
x=x*x;
n=n/2;
}
return result;
}
public static int modularExponentiation(int x,int n,int M)
{
int result=1;
while(n>0)
{
if(n % 2 ==1)
result=(result * x)%M;
x=(x*x)%M;
n=n/2;
}
return result;
}
public static long modularExponentiation(long x,long n,long M)
{
long result=1;
while(n>0)
{
if(n % 2 ==1)
result=(result * x)%M;
x=(x*x)%M;
n=n/2;
}
return result;
}
public static int modInverse(int A,int M)
{
return modularExponentiation(A,M-2,M);
}
public static long modInverse(long A,long M)
{
return modularExponentiation(A,M-2,M);
}
public static boolean isPrime(int n)
{
if (n <= 1) return false;
if (n <= 3) return true;
if (n%2 == 0 || n%3 == 0)
return false;
for (int i=5; i*i<=n; i=i+6)
{
if (n%i == 0 || n%(i+2) == 0)
return false;
}
return true;
}
static class pair implements Comparable<pair>
{
Integer x, y;
pair(int x,int y)
{
this.x=x;
this.y=y;
}
public int compareTo(pair o) {
int result = x.compareTo(o.x);
if(result==0)
result = y.compareTo(o.y);
return result;
}
public String toString()
{
return x+" "+y;
}
public boolean equals(Object o)
{
if (o instanceof pair)
{
pair p = (pair)o;
return (Math.abs(p.x-x)==0 && Math.abs(p.y-y)==0);
}
return false;
}
public int hashCode()
{
return new Long(x).hashCode()*31 + new Long(y).hashCode();
}
}
} | Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 8 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | bcda589bc746e7eebb66fdd36678c7f5 | train_002.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class Main {
IIO io;
Main(IIO io) {
this.io = io;
}
public static void main(String[] args) throws IOException {
ConsoleIO io = new ConsoleIO();
Main m = new Main(io);
m.solve();
io.flush();
// Tester test = new Tester();test.run();
}
public void solve() {
long mod = 1000000007;
int[] l = io.readIntArray();
int n = l[0], x = l[1];
if(x == 1){
io.writeLine("1");
return;
}
l = io.readIntArray();
Arrays.sort(l);
long s = 0;
for (int v : l) s += v;
long m = s - l[l.length - 1];
long res = 1;
long p = x;
for (int i = 0; i < 62; i++, p = (p * p) % mod)
if ((m & (1L << i)) > 0)
res = (res * p) % mod;
HashMap<Integer, Integer> nums = new HashMap<Integer, Integer>();
for(int i = 0;i<l.length;i++) {
if (nums.containsKey(l[i])) nums.put(l[i], nums.get(l[i]) + 1);
else nums.put(l[i], 1);
}
int c = 0;
int d = l[l.length-1];
for(int q = l[l.length-1];q>=0 && d>0;) {
if (nums.containsKey(q)) c += nums.get(q);
if (c % x == 0) {
c /= x;
res = (res * x) % mod;
q--;
d--;
}
else break;
}
io.writeLine(Long.toString(res));
}
}
class ConsoleIO extends BaseIO {
BufferedReader br;
PrintWriter out;
public ConsoleIO(){
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
public void flush(){
this.out.close();
}
public void writeLine(String s) {
this.out.println(s);
}
public void writeInt(int a) {
this.out.print(a);
this.out.print(' ');
}
public void writeWord(String s){
this.out.print(s);
}
public String readLine() {
try {
return br.readLine();
}
catch (Exception ex){
return "";
}
}
public int read(){
try {
return br.read();
}
catch (Exception ex){
return -1;
}
}
}
abstract class BaseIO implements IIO {
public long readLong() {
return Long.parseLong(this.readLine());
}
public int readInt() {
return Integer.parseInt(this.readLine());
}
public int[] readIntArray() {
String line = this.readLine();
String[] nums = line.split(" ");
int[] res = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
res[i] = Integer.parseInt(nums[i]);
}
return res;
}
public long[] readLongArray() {
String line = this.readLine();
String[] nums = line.split(" ");
long[] res = new long[nums.length];
for (int i = 0; i < nums.length; i++) {
res[i] = Long.parseLong(nums[i]);
}
return res;
}
}
interface IIO {
void writeLine(String s);
void writeInt(int a);
void writeWord(String s);
String readLine();
long readLong();
int readInt();
int read();
int[] readIntArray();
long[] readLongArray();
}
| Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 8 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | 557fc9b4d057f7c1ba85365763521438 | train_002.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class Main{
static final int MOD = (int)1e9 + 7;
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
long x = scanner.nextInt();
int[] a = new int[n];
long s = 0;
for(int i = 0; i < n ; ++i) {
a[i] = scanner.nextInt();
s += a[i];
}
List<Long> deg = new ArrayList<>();
for(int i = 0; i < n ; ++i) {
deg.add(s - a[i]);
}
Collections.sort(deg, new Comparator<Long>() {
@Override
public int compare(Long o1, Long o2) {
if(o1 > o2) return -1;
return 1;
}
});
while(true) {
int count = 0;
long d = deg.get(deg.size() - 1);
while(deg.size() > 0 && deg.get(deg.size() - 1) == d) {
++count;
deg.remove(deg.size() - 1);
}
if(count % x != 0) {
long min = Math.min(s, d);
System.out.println(pow(x, min));
return;
}else {
count /= x;
for(int i = 0; i < count; ++i) {
deg.add(d + 1);
}
}
}
}
static long pow(long x, long n) {
if(n == 0) return 1;
if(n % 2 == 0) return pow((x * x) % MOD, n / 2);
return (x * pow((x * x) % MOD, (n - 1) / 2)) % MOD;
}
}
| Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 8 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | 52887b1eb7aa7bfe5e3c47a668efffce | train_002.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Random;
import java.util.StringTokenizer;
public class ProblemB {
public static void main(String [] args) throws IOException{
solve();
}
public static void solve() throws IOException {
Scanner sc = new Scanner(System.in);
int t=sc.nextInt();
all:for(int c=0;c<t;c++) {
int n=sc.nextInt();
if(n==1) {
System.out.println(sc.nextLong());
continue all;
}
long arr[] = new long[n];
long r [] = new long[n];
for(int i=0;i<n;i++) {
arr[i]=sc.nextLong();
}
char lastSeen;
if(arr[0]<0) {
lastSeen ='N';}
else {
lastSeen ='P';
}
int k=0;
r[0]=arr[0];
for(int i=1;i<n;i++) {
if(lastSeen=='N' && arr[i]>r[k] && arr[i]<0) {
r[k]=arr[i];
}else if(lastSeen=='P' && arr[i]>r[k] && arr[i]>0) {
r[k]=arr[i];
}else if(lastSeen=='P' && arr[i]<0) {
k++;
lastSeen='N';
r[k]=arr[i];
}else if(lastSeen=='N' && arr[i]>0) {
k++;
lastSeen='P';
r[k]=arr[i];
}
//System.out.println(Arrays.toString(r));
}
//System.out.println(Arrays.toString(r));
long sum=0;
for(int i=0;i<r.length;i++) {
sum+=r[i];
}
System.out.println(sum);
}
}
static 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;
}
}
static class Pair{
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + end;
result = prime * result + start;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pair other = (Pair) obj;
if (end != other.end)
return false;
if (start != other.start)
return false;
return true;
}
int start;
int end;
public Pair(int s,int e) {
start=s;
end=e;
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException
{
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if(x.charAt(0) == '-')
{
neg = true;
start++;
}
for(int i = start; i < x.length(); i++)
if(x.charAt(i) == '.')
{
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
}
else
{
sb.append(x.charAt(i));
if(dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg?-1:1);
}
public boolean ready() throws IOException {return br.ready();}
}
} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 4416beedc123c75cfeb84121d52ec6fd | train_002.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
import java.lang.*;
public class CodeForcesC {
private static BufferedReader br;
public static void mapToArray(int[][] arr, int q) throws IOException {
String[] str;
for (int i = 0; i < q; i++) {
str = br.readLine().split(" ");
for (int j = 0; j < str.length; j++) {
arr[i][j] = Integer.parseInt(str[j]);
}
}
}
public static void main(String[] args) throws IOException {
// System.setIn(new FileInputStream(new File("input.txt")));
br = new BufferedReader(new InputStreamReader(System.in));
String str[];
ArrayList<Integer> pos = new ArrayList<>();
int n, q, t;
int arr[];
t = Integer.parseInt(br.readLine());
while (t-- > 0) {
n = Integer.parseInt(br.readLine());
arr = new int[n];
str = br.readLine().split(" ");
for (int i = 0; i < str.length; i++) {
int a = Integer.parseInt(str[i]);
arr[i] = a;
}
long sum = 0;
long max = Integer.MIN_VALUE;
boolean isPos = (arr[0] > 0);
sum += arr[0];
int prev = arr[0];
for (int i = 1; i < n; i++) {
if ((arr[i] > 0 && !isPos) || (isPos && arr[i] < 0)) {
sum += arr[i];
prev = arr[i];
isPos = !isPos;
} else {
int temp = Integer.max(prev, arr[i]);
if (temp > prev) {
sum -= prev;
sum += arr[i];
prev = arr[i];
}
}
}
System.out.println(sum);
}
}
} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 721a1b33caa70f81a6e92a26f8f5e4b3 | train_002.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes |
import java.io.*;
import java.util.*;
public class Solution
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int i=0;i<t;i++){
int n = in.nextInt();
int[] arr = new int[n+1];
for(int j=0;j<n;j++){
arr[j]=in.nextInt();
}
arr[n]=0;
int max =1;
int min = -1000000000;
long sum=0;
for(int j =0;j<n;j++){
if(arr[j]>0){
max =Math.max(arr[j],max);
if(arr[j+1]<=0){
sum+=max;
max=1;
}
}else{
min = Math.max(arr[j],min);
if(arr[j+1]>=0){
sum+=min;
min=-1000000000;
}
}
}
System.out.println(sum);
}
}
} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | c83d70a7cd2dd7516623828bcccc1ccd | train_002.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pwr = new PrintWriter(System.out);
int t = Integer.parseInt(br.readLine());
while( t-- > 0){
int n = Integer.parseInt(br.readLine());
String nums[] = br.readLine().split(" ");
int arr[] = new int[n];
arr[0] = Integer.parseInt(nums[0]);
int min = arr[0];
int len = 1;
long sum = 0;
for(int i = 1; i<n; i++){
arr[i] = Integer.parseInt(nums[i]);
if(min > 0 && arr[i] >0 || min<0 && arr[i]<0){
min = Math.max(min, arr[i]);
} else {
++len;
sum += min;
min = arr[i];
}
}
sum += min;
pwr.println(sum);
}
pwr.flush();
}
}
| Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 7ff1562b2429683e45461666590f09d3 | train_002.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
while(t-- > 0){
int n = scan.nextInt();
int num = scan.nextInt();
long sum = 0;
sum += num;
int mx = num;
for(int i = 1; i < n; i++){
num = scan.nextInt();
if(mx > 0 && num < 0){
sum += num;
mx = num;
} else if(mx < 0 && num > 0) {
sum += num;
mx = num;
} else {
sum -= mx;
mx = Math.max(mx, num);
sum += mx;
}
}
System.out.println(sum);
}
scan.close();
}
} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 52319676a2207806ea09fa8dd254f5ec | train_002.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class subseq {
static Queue<Long> q1 = new LinkedList<>();
public static void solve(long no, long[] arr) {
Queue<Long> q = new LinkedList<>();
long maxpo,sum = 0, j;
for ( int i = 0; i< no; ) {
if (arr[i] > 0) {
maxpo = arr[i];
for (j = i + 1; j < no; j++) {
if (arr[(int) j] > 0) {
if (arr[(int) j] > maxpo)
maxpo = arr[(int) j];
}
else {
break;
}
}
q.add(maxpo);
i = (int) j;
}
else if (arr[i] < 0) {
maxpo = arr[i];
for (j = i + 1; j < no; j++) {
if (arr[(int) j] < 0) {
if (arr[(int) j] > maxpo)
maxpo = arr[(int) j];
}
else {
break;
}
}
q.add(maxpo);
i = (int) j;
}
}
for ( Long ele : q)
sum = sum + ele;
q1.add(sum);
}
public static void main(String[] args) {
long n, i = 0, no;
long[] arr;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
while (i<n) {
no = sc.nextInt();
arr = new long[(int) no];
for (int j = 0; j<no;j++)
arr[j] = sc.nextInt();
solve(no, arr);
i++;
}
for ( long ele : q1)
System.out.println(ele);
}
}
| Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | f0145845a3c7a7bbd7e1f760b87dc2e1 | train_002.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class CP {
static long startTime;
static long endTime;
static Boolean [] prime ;
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static int lowerBound
(Integer[] array, int length, int value) {
int l = 0;
int r = length;
while (l < r) {
int mid = (l + r) / 2;
if (value < array[mid]) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
public static long gcd(long a, long b){
if (b == 0)
return a;
else return gcd(b, a % b);
}
public static long countDivs(long n ){
int cn=0;
long sqr = (long)Math.sqrt(n);
for (long i = 1; i<=sqr ; ++i) {
if(n%i==0){
++cn;
}
}
cn*=2;
if(sqr*sqr==n) cn--;
return cn;
}
static void prime(int x) {
//sieve algorithm. nlog(log(n)).
prime=new Boolean[ (x+1)];
Arrays.fill(prime,true);
prime[0] = prime[1] = false;
for (int i = 2; i * i <= x ; i++)
if (prime[i])
for (int j = i * i; j <= x; j += i)
prime[j] = false;
}
static int[] sum;
static void cumulitiveSum( int [] arr){
// make the arrays one indexed.
sum = new int[arr.length];
sum[0]=arr[0];
for (int i = 1; i <arr.length; i++) {
sum[i]=arr[i]+sum[i-1];
}
}
static boolean isEven(long x ){
return x % 2 == 0;
}
static boolean isPrime(long x ){
boolean flag = true;
int sqr = (int)Math.sqrt(x);
if(x<2) return false;
for (int i = 2; i <=sqr; i++) {
if(x%i==0){
flag=false;
break;
}
}
return flag;
}
static long factorial( long x) {
long total = 1;
for (int i = 2; i <= x; i++)
total *= i;
return total;
}
static long pow(long x, long n) {
if (n == 0) {
return 1;
}
long pow = pow(x, n / 2L);
if ((n & 1) == 1) {
return x * pow * pow;
}
return pow * pow;
}
public static void main(String [] args) {
startTime = System.currentTimeMillis();
int T = sc.nextInt();while (T--!=0)
{
solve();
}
endTime = System.currentTimeMillis();
long duration= endTime-startTime;
//System.out.println(duration);
}
static FastReader sc = new FastReader();
// static Scanner sc = new Scanner(System.in);
public static void solve() {
//////////////////////////////////////////////////////////////////////
int n =sc.nextInt();
int [] arr= new int[n];
for (int i = 0; i < n; i++) {
arr[i]=sc.nextInt();
}
int low=0,hi=n-1;
long sum=0;
int po=0,ne=0;
int max=-2000000000;
while(low<=hi) {
if(arr[low]<0){
ne++;
if(po>0){
sum+=max;
max=-2000000000;
po=0;
}
max=Math.max(max,arr[low]);
}
else {
po++;
if(ne>0){
sum+=max;
max=-2000000000;
ne=0;
}
max=Math.max(max,arr[low]);
}
low++;
}
sum+=max;
System.out.println(sum);
///////////////////////////////////////////////////////////////////////
}
} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | ee76a21dc4a1625ec27c74ce10387096 | train_002.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class CP {
static long startTime;
static long endTime;
static Boolean [] prime ;
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static int lowerBound
(Integer[] array, int length, int value) {
int l = 0;
int r = length;
while (l < r) {
int mid = (l + r) / 2;
if (value < array[mid]) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
public static long gcd(long a, long b){
if (b == 0)
return a;
else return gcd(b, a % b);
}
public static long countDivs(long n ){
int cn=0;
long sqr = (long)Math.sqrt(n);
for (long i = 1; i<=sqr ; ++i) {
if(n%i==0){
++cn;
}
}
cn*=2;
if(sqr*sqr==n) cn--;
return cn;
}
static void prime(int x) {
//sieve algorithm. nlog(log(n)).
prime=new Boolean[ (x+1)];
Arrays.fill(prime,true);
prime[0] = prime[1] = false;
for (int i = 2; i * i <= x ; i++)
if (prime[i])
for (int j = i * i; j <= x; j += i)
prime[j] = false;
}
static int[] sum;
static void cumulitiveSum( int [] arr){
// make the arrays one indexed.
sum = new int[arr.length];
sum[0]=arr[0];
for (int i = 1; i <arr.length; i++) {
sum[i]=arr[i]+sum[i-1];
}
}
static boolean isEven(long x ){
return x % 2 == 0;
}
static boolean isPrime(long x ){
boolean flag = true;
int sqr = (int)Math.sqrt(x);
if(x<2) return false;
for (int i = 2; i <=sqr; i++) {
if(x%i==0){
flag=false;
break;
}
}
return flag;
}
static long factorial( long x) {
long total = 1;
for (int i = 2; i <= x; i++)
total *= i;
return total;
}
static long pow(long x, long n) {
if (n == 0) {
return 1;
}
long pow = pow(x, n / 2L);
if ((n & 1) == 1) {
return x * pow * pow;
}
return pow * pow;
}
public static void main(String [] args) {
startTime = System.currentTimeMillis();
int T = sc.nextInt();while (T--!=0)
{
solve();
}
endTime = System.currentTimeMillis();
long duration= endTime-startTime;
//System.out.println(duration);
}
static FastReader sc = new FastReader();
// static Scanner sc = new Scanner(System.in);
public static void solve() {
//////////////////////////////////////////////////////////////////////
int n =sc.nextInt();
int [] arr= new int[n];
for (int i = 0; i < n; i++) {
arr[i]=sc.nextInt();
}
int low=0,hi=n-1;
int po=0,ne=0;
long sum=0;
List<Integer> plis = new ArrayList<>();
List<Integer> nlis = new ArrayList<>();
while(low<=hi){
if(arr[low]<0){
if(!plis.isEmpty()){
Collections.sort(plis);
sum+=plis.get(plis.size()-1);
plis=new ArrayList<>();
}
nlis.add(arr[low]);
}
else {
if(!nlis.isEmpty()){
Collections.sort(nlis);
sum+=nlis.get(nlis.size()-1);
nlis=new ArrayList<>();
}
plis.add(arr[low]);
}
low++;
}
if(!nlis.isEmpty()){
Collections.sort(nlis);
sum+=nlis.get(nlis.size()-1);
}
if(!plis.isEmpty()){
Collections.sort(plis);
sum+=plis.get(plis.size()-1);
}
System.out.println(sum);
///////////////////////////////////////////////////////////////////////
}
} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 5aef5342ce4f372159a8f94c83d2f516 | train_002.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class CP {
static long startTime;
static long endTime;
static Boolean [] prime ;
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static int lowerBound
(Integer[] array, int length, int value) {
int l = 0;
int r = length;
while (l < r) {
int mid = (l + r) / 2;
if (value < array[mid]) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
public static long gcd(long a, long b){
if (b == 0)
return a;
else return gcd(b, a % b);
}
public static long countDivs(long n ){
int cn=0;
long sqr = (long)Math.sqrt(n);
for (long i = 1; i<=sqr ; ++i) {
if(n%i==0){
++cn;
}
}
cn*=2;
if(sqr*sqr==n) cn--;
return cn;
}
static void prime(int x) {
//sieve algorithm. nlog(log(n)).
prime=new Boolean[ (x+1)];
Arrays.fill(prime,true);
prime[0] = prime[1] = false;
for (int i = 2; i * i <= x ; i++)
if (prime[i])
for (int j = i * i; j <= x; j += i)
prime[j] = false;
}
static int[] sum;
static void cumulitiveSum( int [] arr){
// make the arrays one indexed.
sum = new int[arr.length];
sum[0]=arr[0];
for (int i = 1; i <arr.length; i++) {
sum[i]=arr[i]+sum[i-1];
}
}
static boolean isEven(long x ){
return x % 2 == 0;
}
static boolean isPrime(long x ){
boolean flag = true;
int sqr = (int)Math.sqrt(x);
if(x<2) return false;
for (int i = 2; i <=sqr; i++) {
if(x%i==0){
flag=false;
break;
}
}
return flag;
}
static long factorial( long x) {
long total = 1;
for (int i = 2; i <= x; i++)
total *= i;
return total;
}
static long pow(long x, long n) {
if (n == 0) {
return 1;
}
long pow = pow(x, n / 2L);
if ((n & 1) == 1) {
return x * pow * pow;
}
return pow * pow;
}
public static void main(String [] args) {
startTime = System.currentTimeMillis();
int T = sc.nextInt();while (T--!=0)
{
solve();
}
endTime = System.currentTimeMillis();
long duration= endTime-startTime;
//System.out.println(duration);
}
static FastReader sc = new FastReader();
// static Scanner sc = new Scanner(System.in);
public static void solve() {
//////////////////////////////////////////////////////////////////////
int n =sc.nextInt();
int [] arr= new int[n];
for (int i = 0; i < n; i++) {
arr[i]=sc.nextInt();
}
int low=0,hi=n-1;
long sum=0;
int po=0,ne=0;
int mp=0;
int mn=-2000000000;
while(low<=hi) {
if(arr[low]<0){
ne++;
mn=Math.max(mn,arr[low]);
if(po>0){
sum+=mp;
mp=0;
po=0;
}
}
else {
po++;
mp=Math.max(mp,arr[low]);
if(ne>0){
sum+=mn;
mn=-2000000000;
ne=0;
}
}
low++;
}
if(po>0) {
sum += mp;
}
if(ne>0){
sum+=mn;
}
System.out.println(sum);
///////////////////////////////////////////////////////////////////////
}
} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 3807512f0dd194ee7651130fb26c85a5 | train_002.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
public class Solution{
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
StringBuffer sb = new StringBuffer();
while(t-->0){
int n = sc.nextInt();
long[]arr = new long[n];
for(int i = 0;i<n;i++) arr[i]=sc.nextLong();
long max = arr[0];
long sum = 0;
for(int i = 1;i<n;i++){
if((arr[i]*arr[i-1])<0){
sum+=max;
max = Long.MIN_VALUE;
}
if(arr[i]>max) max = arr[i];
}
sum+=max;
sb.append(sum+"\n");
}
System.out.println(sb);
}
} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | b5c2a60e9ebea74839047f200da4bac4 | train_002.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
public class Q3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
long sum = 0;
//int currentSum = sum;
ArrayList<Long> ar = new ArrayList<>();
ArrayList<Long> neg = new ArrayList<>();
long postiveNumber = 0;
long negativeNumber = -1000000000;
for (int i = 0; i < n; i++) {
if (a[i] >= 0) {
postiveNumber = Math.max(postiveNumber , a[i]);
if(!ar.isEmpty())
ar.remove(0);
ar.add(postiveNumber);
if(!neg.isEmpty()){
sum += neg.remove(0);
negativeNumber = -1000000000 ;
}
}
else {
negativeNumber = Math.max(negativeNumber , a[i]);
if(! neg.isEmpty())
neg.remove(0);
neg.add(negativeNumber);
if(!ar.isEmpty())
{
sum += ar.remove(0);
postiveNumber = 0 ;
}
}
//System.out.println(sum);
}
if(!ar.isEmpty()){
postiveNumber = 0 ;
while (!ar.isEmpty()) {
postiveNumber = Math.max(postiveNumber, ar.remove(0));
}
sum += postiveNumber ;
}
if (! neg.isEmpty()) {
negativeNumber = -1000000000 ;
while (!neg.isEmpty()) {
negativeNumber = Math.max(negativeNumber, neg.remove(0));
}
sum += negativeNumber;
}
System.out.println(sum);
}
}
} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 6b84b8d880b8bc072a633db5160fca8a | train_002.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.StringTokenizer;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;
import java.io.FileOutputStream;
public class AlternatingSub{
public static void main(String[] args)throws IOException{
FastReader sc = new FastReader();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(java.io.FileDescriptor.out),"ASCII"),512);
int t = sc.nextInt();
while(t-- > 0){
int n = sc.nextInt();
int[] a = new int[n];
for(int i=0;i<n;i++) a[i] = sc.nextInt();
long ms = a[0];
long last = a[0];
for(int i=1;i<n;i++){
if(last*a[i] < 0){
ms += a[i];
last = a[i];
}else if(a[i] > last){
ms = ms - last + a[i];
last = a[i];
}
}
out.write(ms + "");
out.write('\n');
out.flush();
}
}
}
class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while (st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}
catch (IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try{
str = br.readLine();
}
catch (IOException e){
e.printStackTrace();
}
return str;
}
} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 48258cda2cb696a5a1449ad47bd53252 | train_002.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class Abhi {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int t = s.nextInt();
for(int k = 0; k<t; k++) {
int n = s.nextInt();
int[] a = new int[n];
int[] b = new int[n];
int m = 0;
for(int i = 0; i<n; i++) {
a[i] = s.nextInt();
}
for(int i = 0; i<n; i++) {
if(a[i] > 0) {
int j = i;
int max = 0;
while(a[j] > 0) {
if(max < a[j]) {
max = a[j];
}
if(j == n-1) {
i = j;
break;
}
j++;
i = j-1;
}
b[m] = max;
m++;
}
if(a[i] < 0) {
int j = i;
int max1 = Integer.MIN_VALUE;
while(a[j] < 0) {
if(max1 < a[j]) {
max1 = a[j];
}
if(j == n-1) {
i = j;
break;
}
j++;
i = j-1;
}
b[m] = max1;
m++;
}
}
long sum = 0;
for(int i = 0; i<n; i++) {
if(b[i] == 0) {
break;
}
else {
sum += b[i];
}
}
System.out.println(sum);
}
}
} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | eca83ffbcb34ca8f7608f12d86a0cca2 | train_002.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
public class kefas{
public static int sig(long x){
if(x>0) return 1;
else return -1;
}
public static void main(String[] args) {
Scanner q=new Scanner(System.in);
long testcases=q.nextLong();
while(testcases-->0){
int n=q.nextInt();
long[] a=new long[n];
for(int i=0;i<n;i++){
a[i]=q.nextLong();
}
long sum=0;
for(int i=0;i<n;i++){
long curr=a[i];
int j=i;
while(j<n && sig(a[i])==sig(a[j])){
curr=Math.max(curr,a[j]);
j++;
}
sum+=curr;
i=j-1;
}
System.out.println(sum);
}
}
} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 946908070b3a83c37e459db8679dafd1 | train_002.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
import java.util.stream.*;
public class Solution {
/*get indexes
List<Integer> indexes = IntStream.range(0, a.length).boxed()
.filter(r -> a[r]==c).collect(Collectors.toList());
*/
/*
form string to array int
Integer[] a = Arrays.stream(scanner.nextLine().trim().split(" ")).map(e -> Integer.parseInt(e)).toArray(Integer[]::new);
*/
public static void main(String[] args) throws IOException {
// System.out.println("success");
Scanner scanner = new Scanner(System.in);
String tl = scanner.nextLine().trim();
int s = Integer.parseInt(tl);
for(int i=0;i<s;i++){
int n = Integer.parseInt(scanner.nextLine());
Integer[] a = Arrays.stream(scanner.nextLine().trim().split(" ")).map(e -> Integer.parseInt(e)).toArray(Integer[]::new);
long max=0;
Integer tmp=0;
for(int k=0;k<n;k++){
if(k==0){
tmp=a[k];
}
else {
if( (a[k]>0 && a[k-1]>0) || (a[k]<0 && a[k-1]<0)){
if(a[k]>tmp){
tmp=a[k];
}
}
else {
//System.out.println("added "+tmp);
max+=(long)tmp;
tmp=a[k];
}
}
}
//System.out.println("fional add "+tmp);
System.out.println(max+(long)tmp);
}
}
}
| Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 0fd31532945d496d48d729ca1594e003 | train_002.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class As_1343C {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
for (int i = 0; i < t; i++) {
int n = scanner.nextInt();
long[] x;
x = new long[n];
long sum = 0;
for (int j = 0; j < n; j++) {
x[j] = scanner.nextLong();
}
int count = 1;
double maxPos = 0;
double maxNeg = -1000000000;
if (x[0] > 0)
maxPos = x[0];
else
maxNeg = x[0];
while(count < n){
// boolean alt = false;
if (x[count] * x[count - 1] < 0) {
if (x[count] < 0) {
sum += maxPos;
maxPos = 0;
maxNeg = x[count];
// alt = true;
// System.out.println(sum);
// System.out.println(maxPos);
}
else {
// System.out.println(maxNeg);
sum += maxNeg;
maxPos = x[count];
maxNeg = -1000000000;
// alt = true;
}
} else {
if (x[count] > maxPos) {
maxPos = x[count];
}
if (x[count] > maxNeg && x[count] < 0) {
maxNeg = x[count];
}
}
count++;
// System.out.println(sum);
}
if (x[count - 1] < 0)
sum += maxNeg;
else
sum += maxPos;
System.out.println(sum);
}
scanner.close();
}
}
| Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 185302e9bb20b27b8e410b202ed92aba | train_002.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.PrintWriter;
import java.util.*;
import java.util.Scanner;
public class AltSubsequence {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int t = sc.nextInt();
for (int i1 = 0; i1 < t; i1 ++){
int n = sc.nextInt();
int[] sequence = new int[n];
for (int i2 = 0; i2 < n; i2 ++){
sequence[i2] = sc.nextInt();
}
long sum = 0;
ArrayList<Integer> elements = new ArrayList<>();
elements.add(sequence[0]);
for (int i3 = 1; i3 < n; i3 ++){
if (Integer.signum(sequence[i3]) == Integer.signum(sequence[i3 - 1])){
elements.add(sequence[i3]);
} else {
sum += Collections.max(elements);
elements.clear();
elements.add(sequence[i3]);
}
}
sum += Collections.max(elements);
pw.println(sum);
}
pw.close();
}
}
| Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 306afb8dcc11c96a049a124b69c77eeb | train_002.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.PrintWriter;
import java.util.*;
import java.util.Scanner;
public class AltSubsequence {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int t = sc.nextInt();
for (int i1 = 0; i1 < t; i1 ++){
int n = sc.nextInt();
int[] sequence = new int[n];
for (int i2 = 0; i2 < n; i2 ++){
sequence[i2] = sc.nextInt();
}
long sum = 0;
ArrayList<Integer> elements = new ArrayList<>();
elements.add(sequence[0]);
for (int i3 = 1; i3 < n; i3 ++){
if (Integer.signum(sequence[i3]) == Integer.signum(sequence[i3 - 1])){
elements.add(sequence[i3]);
} else {
sum += Collections.max(elements);
elements.clear();
elements.add(sequence[i3]);
}
// if (i3 == sequence.length - 1){
// sum += Collections.max(elements);
// }
}
sum += Collections.max(elements);
pw.println(sum);
}
pw.close();
}
}
| Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 3f571a53862d301ddb3185bc1fb9b588 | train_002.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.PrintWriter;
import java.util.*;
import java.util.Scanner;
public class AltSubsequence {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int t = sc.nextInt();
for (int i1 = 0; i1 < t; i1 ++){
int n = sc.nextInt();
int[] sequence = new int[n];
for (int i2 = 0; i2 < n; i2 ++){
sequence[i2] = sc.nextInt();
}
long sum = 0;
int last = sequence[0];
for (int i3 = 1; i3 < n; i3 ++){
if (Integer.signum(sequence[i3]) == Integer.signum(last)){
last = Math.max(sequence[i3], last);
} else {
sum += last;
last = sequence[i3];
}
}
sum += last;
pw.println(sum);
}
pw.close();
}
}
| Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | c167f40ac8cbee6ccc9519aa1f04e86b | train_002.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | //package com.company;
//-------------------------------------------># DEVIL CODER # -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
import javax.swing.*;
import java.lang.reflect.Array;
import java.util.*;
import java.lang.*;
import java.io.*;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
//-------------------Main function ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
public class Main {
//---------------Reader class for Fast Input------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
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;
}
// ----------------------Down-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
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);
}
// Down---------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
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;
}
// Down---------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
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;
}
// Down---------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
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;
}
// Down---------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>---------------------------------------------------------------------------------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
// Down---------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
// Down---------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
// ---------------->>>>>>>>>seieve of erathoshenes ------------------------------------------------------------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
static ArrayList<Integer> sieveOfEratosthenes(int n) {
boolean prime[] = new boolean[n + 1];
for (int i = 0; i < n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++) {
// If prime[p] is not changed, then it is a prime
if (prime[p] == true) {
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
ArrayList<Integer> l = new ArrayList<>();
for (int i = 2; i <= n; i++) {
if (prime[i] == true)
l.add(i);
}
return l;
}
// ---------------------------------GCD>>>>>>>>>>>>>>>>>>>>>>>>>>>>-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
static int gcd(int a, int b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
static ArrayList<Integer> factor(int n) {
ArrayList<Integer> l = new ArrayList<>();
for (int i = n; i <= 1e5; i++) {
if (i % n == 0)
l.add(n);
}
return l;
}
// ---------------->>>>>>>>>Coding begins ------------------------------------------------------------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//----<<<<<<<<<------------>>>>>>>>>>>>>### $$$solve ### devil_coder$$$#######<<<<<<<------------------>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//----------------Main function----------------------------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>------------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>-------------------------------------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
public static void main(String[] args) throws java.lang.Exception {
Reader sc = new Reader();
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int A[] = new int[n];
for (int i = 0; i < n; i++)
A[i] = sc.nextInt();
int dp[] = new int[n];
int top = 0;
int pre = 0;
int sum = 0;
long ans = 0;
if (A[0] >= 0) {
dp[top] = A[0];
sum += A[0];
top++;
pre = 1;
} else {
dp[top] = A[0];
sum += A[0];
top++;
pre = -1;
}
for (int i = 1; i < n; i++) {
if (A[i] >= 0) {
if (pre == -1) {
pre = +1;
dp[top] = A[i];
top++;
} else {
top--;
dp[top] = Math.max(dp[top], A[i]);
top++;
}
} else {
if (pre == +1) {
pre = -1;
dp[top] = A[i];
top++;
} else {
top--;
dp[top] = Math.max(dp[top], A[i]);
top++;
}
}
}
for (int i = 0; i < dp.length; i++)
{
ans += dp[i];
}
//System.out.println(Arrays.toString(dp));
System.out.println(ans);
}
}
}
| Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 631c0b94299ea45a22aeea6eb7a010eb | train_002.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | //I AM THE CREED
/* //I AM THE CREED
/* package codechef; // don't place package name! */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.*;
public class Main{
public static void main(String[] args) throws IOException
{
Scanner input = new Scanner(System.in);
input.nextInt();
while(input.hasNext()){
int n=input.nextInt();
long[] l=new long[n];
for(int i=0;i<n;i++){
l[i]=input.nextLong();
}
long max=Long.MIN_VALUE;
int len1=0;
long sum=0;
long curr=-1;
for(int i=0;i<n;i++){
if(len1==0){
if(l[i]>=0){
curr=l[i];
sum+=curr;
len1++;
continue;
}
continue;
}
if((l[i]<0 && curr<0)||(l[i]>=0 && curr>=0)){
if(l[i]>curr){
sum-=curr;
sum+=l[i];
curr=l[i];
continue;
}
continue;
}
curr=l[i];
sum+=l[i];
len1++;
}
if(len1>0){
max=sum;
}
sum=0;
curr=-1;
int len2=0;
for(int i=0;i<n;i++){
if(len2==0){
if(l[i]<0){
curr=l[i];
sum+=curr;
len2++;
continue;
}
continue;
}
if((l[i]<0 && curr<0)||(l[i]>=0 && curr>=0)){
if(l[i]>curr){
sum-=curr;
sum+=l[i];
curr=l[i];
continue;
}
continue;
}
sum+=l[i];
curr=l[i];
len2++;
}
if(len2>len1){
max=sum;
}
if(len2==len1){
max=Math.max(max, sum);
}
System.out.println(max);
}
}
} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 5d616776db5483f7e71f0f96e2605d31 | train_002.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes |
/* package codechef; // don't place package name! */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.*;
import java.awt.*;
public class HelloWorld{
public static void main(String[] args) throws IOException
{
Scanner input = new Scanner(System.in);
input.nextInt();
while(input.hasNext()){
int n=input.nextInt();
int[] l=new int[n];
for(int i=0;i<n;i++){
l[i]=input.nextInt();
}
long s=0;
long curr=l[0];
for(int i=1;i<l.length;i++){
if(l[i]<0 && curr<0){
curr=Math.max(curr, l[i]);
continue;
}
if(l[i]>0 && curr>0){
curr=Math.max(curr, l[i]);
continue;
}
s+=curr;
curr=l[i];
}
s+=curr;
System.out.println(s);
}
}
} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | c9e522c308b844ead6a6c93240bd8544 | train_002.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class AltenatingSequence {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scn = new Scanner(System.in);
int t = scn.nextInt();
while(t-->0)
{
int n = scn.nextInt();
long[] arr = new long[n];
for(int i = 0; i< arr.length; i++)
{
arr[i] = scn.nextLong();
}
long ans = 0;
long a = 0;
long curr = 0;
for(int i = 0; i< arr.length; i++)
{
curr = arr[i];
if(i == 0)
{
a = curr;
}
if(a*curr > 0 && a < curr)
{
a = curr;
}
if(a*curr < 0)
{
ans += a;
a = curr;
}
}
System.out.println(ans + a);
}
}
}
| Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 0fe154271e0ab4a97e360c2e9349c9be | train_002.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in =new Scanner(System.in);
int t=in.nextInt();
while(t-->0)
{
int s=in.nextInt();
long a[]=new long[s];
int i;
for(i=0;i<s;i++)
a[i]=in.nextLong();
int start=0;
int end=0;
long max=a[0];
long sum=a[0];
while(end<s)
{
if(a[start]*a[end]>=0)
{
sum=sum-max;
max=Math.max(a[end],max);
sum=sum+max;
end++;
}
else
{
start=end;
max=a[start];
sum=sum+max;
}
}
System.out.println(sum);
}
}
} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | f2fe2baa67eaf8303bb1d072c9534ab3 | train_002.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pwr = new PrintWriter(System.out);
int t = Integer.parseInt(br.readLine());
while( t-- > 0){
int n = Integer.parseInt(br.readLine());
String nums[] = br.readLine().split(" ");
int arr[] = new int[n];
arr[0] = Integer.parseInt(nums[0]);
int min = arr[0];
int len = 1;
long sum = 0;
for(int i = 1; i<n; i++){
arr[i] = Integer.parseInt(nums[i]);
if(min > 0 && arr[i] >0 || min<0 && arr[i]<0){
min = Math.max(min, arr[i]);
} else {
++len;
sum += min;
min = arr[i];
}
}
sum += min;
pwr.println(sum);
}
pwr.flush();
}
}
| Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 763df2f836de67aa62ec3244bbe42d78 | train_002.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pwr = new PrintWriter(System.out);
int t = Integer.parseInt(br.readLine());
while( t-- > 0){
int n = Integer.parseInt(br.readLine());
String nums[] = br.readLine().split(" ");
int min = Integer.parseInt(nums[0]);
int len = 1;
long sum = 0;
for(int i = 1; i<n; i++){
int num = Integer.parseInt(nums[i]);
if(min > 0 && num >0 || min<0 && num<0){
min = Math.max(min, num);
} else {
++len;
sum += min;
min = num;
}
}
sum += min;
pwr.println(sum);
}
pwr.flush();
}
}
| Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 6aa8c12fdf2462b1ce0cfd81b4a7d601 | train_002.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | /* package codechef; // 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 Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner input = new Scanner(System.in);
int test = input.nextInt();
while(test-->0){
int n = input.nextInt();
int arr[] =new int[n];
for(int i =0;i<n;i++)arr[i] = input.nextInt();
Stack<Integer>stack = new Stack<>();
int f1 = 0,f2= 0;
long sum =0;
stack.push(arr[0]);
// System.out.println(stack);
for(int i =1;i<n;i++){
if(!stack.isEmpty() && stack.peek()>0 && arr[i]>0){
while(!stack.isEmpty() && stack.peek()>0 && arr[i]>0 && stack.peek()<arr[i]){
stack.pop();
f1 =1;
}
if(f1 == 1){
stack.push(arr[i]);
f1 =0;
}
}
if(!stack.isEmpty() && stack.peek()<0 && arr[i]<0){
while(!stack.isEmpty() && stack.peek()<0 && arr[i]<0 && stack.peek()<arr[i]){
stack.pop();
f2 = 1;
}
if(f2 == 1){
stack.push(arr[i]);
f2 =0;
}
}
if(!stack.isEmpty() && stack.peek()<0 && arr[i]>0){
stack.push(arr[i]);
}else if(!stack.isEmpty() && stack.peek()>0 && arr[i]<0){
stack.push(arr[i]);
}
//System.out.println(stack);
}
while(!stack.isEmpty())sum+=stack.pop();
System.out.println(sum);
}
}
}
| Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 0ca06f1ffea383138421947ea80edb1d | train_002.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes |
import java.util.*;
public class CodeForces {
static int max = 200005;
static int moves =1;
static ArrayList<Integer>list;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int test = input.nextInt();
while(test-->0){
int n = input.nextInt();
long sum =0;
long arr[] = new long[n];
for(int i =0;i<n;i++)arr[i] = input.nextInt();
Stack<Long>stack = new Stack<>();
stack.add(arr[0]);
for(int i =1;i<n;i++){
if(arr[i]<0){
if(stack.peek()>0){
stack.push(arr[i]);
}else{
if(arr[i]>stack.peek()){
stack.pop();
stack.push(arr[i]);
}
}
}else{
if(stack.peek()<0)stack.push(arr[i]);
else{
if(arr[i]>stack.peek()){
stack.pop();
stack.push(arr[i]);
}
}
}
}
while(!stack.isEmpty())sum+=stack.pop();
System.out.println(sum);
}
}
public static boolean perf(long sum){
long curr = 1;
long power = 1;
while(true){
if(curr == sum)break;
if(curr>sum)break;
curr+=power;
power*=2;
}
return curr == sum;
}
public static void solve(char c[]){
String s ="";
for(char it:c)s+=it;
StringBuilder sb = new StringBuilder(s);
int count =0;
System.out.println(sb);
while(true){
if(count == 10)break;
if(sb.length() == 0)break;
for(int i =0;i<sb.length()-1;i++){
if(sb.charAt(i) == sb.charAt(i+1)){
list.add(i+1);
//break;
}
}
count++;
}
}
//}
public static void solve(char look,char c[]){
for(int i =0;i<c.length-1;i++){
if(c[i] == look){
if(c[i] != c[i+1]){
while(i+1<c.length && c[i] != c[i+1]){
swap(i,i+1,c);
list.add(i+1);
i++;
}
list.add(i+1);
i++;
}else{
list.add(i+1);
i++;
}
}
}
}
public static void swap(int a,int b,char c[]){
char temp = c[a];
c[a] = c[b];
c[b] =temp;
}
}
class Pair{
int a, b;
public Pair(int a,int b){
this.a = a;
this.b = b;
}
}
/*
1.make sure to include continue or return if u are handling a specific case separately!!!!
and check the constraints of every alphabet(missed to check for case 0)!!!!!!!!!
2.when u have transitions between states and its not dp try dfs (also think of topo sort)
*/
| Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.