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
|
0c2a8c87b36d4c420fc29e7266c87b3b
|
train_000.jsonl
|
1606228500
|
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class EdD {
static long[] mods = {1000000007, 998244353, 1000000009};
static long mod = mods[0];
public static MyScanner sc;
public static PrintWriter out;
static ArrayList<ArrayList<Integer>> tree;
static int[] depth;
static int[] parent;
public static void main(String[] omkar) throws Exception{
// TODO Auto-generated method stub
sc = new MyScanner();
out = new PrintWriter(System.out);
int t = sc.nextInt();
for(int i = 0;i<t;i++){
tree = new ArrayList<ArrayList<Integer>>();
Set<Integer> seen = new HashSet<Integer>();
int n = sc.nextInt();
int finalv1 = 0;
int finalv2 = 0;
depth = new int[n+1];
parent = new int[n+1];
for(int j =0 ;j<=n;j++){
tree.add(new ArrayList<Integer>());
}
for(int j =0;j<n;j++){
int v1 = sc.nextInt();
int v2 = sc.nextInt();
tree.get(v1).add(v2);
tree.get(v2).add(v1);
}
seen.add(1);
Stack<Integer> dfscycle = new Stack<Integer>();
dfscycle.add(1);
parent[1] = -1;
while(!dfscycle.isEmpty()){
int v = dfscycle.pop();
for(int j : tree.get(v)){
if (j != parent[v]){
parent[j] = v;
dfscycle.add(j);
if (seen.contains(j)){
finalv1 = j;
finalv2 = v;
dfscycle.clear();
break;
}
else{
seen.add(j);
}
}
}
}
tree.get(finalv1).remove(new Integer(finalv2));
tree.get(finalv2).remove(new Integer(finalv1));
dfs(finalv1, -1);
Set<Integer> seen1 = new HashSet<Integer>();
seen1.add(finalv1);
seen1.add(finalv2);
int temp = parent[finalv2];
while(temp != finalv1){
seen1.add(temp);
temp = parent[temp];
}
long sum = (long)(n)*(long)(n-1);
Set<Integer> seen2 = new HashSet<Integer>();
seen2.addAll(seen1);
for(int j: seen1){
ArrayDeque<Integer> q = new ArrayDeque<Integer>();
q.add(j);
int count = 1;
while(!q.isEmpty()){
int v = q.remove();
for(int child: tree.get(v)){
if (!seen2.contains(child)){
q.add(child);
seen2.add(child);
count++;
}
}
}
sum-=(long)(count)*(long)(count-1)/2L;
}
System.out.println(sum);
// for(int j = 0;j<array.length;j++){
// out.print(array[j] + " ");
// }
// out.println();
}
System.out.println();
System.out.close();
}
public static void dfs(int v, int p){
for(int child : tree.get(v)){
if (child == p)
continue;
depth[child] = depth[v]+1;
parent[child] = v;
dfs(child, v);
}
}
public static void sort(int[] array){
ArrayList<Integer> copy = new ArrayList<Integer>();
for (int i : array)
copy.add(i);
Collections.sort(copy);
for(int i = 0;i<array.length;i++)
array[i] = copy.get(i);
}
static String[] readArrayString(int n){
String[] array = new String[n];
for(int j =0 ;j<n;j++)
array[j] = sc.next();
return array;
}
static int[] readArrayInt(int n){
int[] array = new int[n];
for(int j = 0;j<n;j++)
array[j] = sc.nextInt();
return array;
}
static int[] readArrayInt1(int n){
int[] array = new int[n+1];
for(int j = 1;j<=n;j++){
array[j] = sc.nextInt();
}
return array;
}
static long[] readArrayLong(int n){
long[] array = new long[n];
for(int j =0 ;j<n;j++)
array[j] = sc.nextLong();
return array;
}
static double[] readArrayDouble(int n){
double[] array = new double[n];
for(int j =0 ;j<n;j++)
array[j] = sc.nextDouble();
return array;
}
static int minIndex(int[] array){
int minValue = Integer.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static int minIndex(long[] array){
long minValue = Long.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static int minIndex(double[] array){
double minValue = Double.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static long power(long x, long y){
if (y == 0)
return 1;
if (y%2 == 1)
return (x*power(x, y-1))%mod;
return power((x*x)%mod, y/2)%mod;
}
static void verdict(boolean a){
out.println(a ? "YES" : "NO");
}
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;
}
}
}
//StringJoiner sj = new StringJoiner(" ");
//sj.add(strings)
//sj.toString() gives string of those stuff w spaces or whatever that sequence is
|
Java
|
["3\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
|
2 seconds
|
["6\n11\n18"]
|
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
|
Java 8
|
standard input
|
[
"combinatorics",
"dfs and similar",
"trees",
"graphs"
] |
1277cf54097813377bf37be445c06e7e
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
| null |
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
|
standard output
| |
PASSED
|
d459fce5838d8921d4ea7aa0d557d270
|
train_000.jsonl
|
1606228500
|
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
|
256 megabytes
|
import java.util.*;
import java.io.*;
//import java.math.*;
public class Task{
// ..............code begins here..............
static long mod=(long)1e9+7;
static List<int[]>[] g;
static boolean[] b;
static List<Integer> cycle;
static int[] mark,bap;
static void dfs(int u,int p) throws IOException{
if(mark[u]==2) return;
if(mark[u]==1){
cycle.add(u);
int curr=p;
while(curr!=u){
cycle.add(curr);
curr=bap[curr];
}
cycle.add(u);
return;
}
mark[u]=1;bap[u]=p;
for(int[] c:g[u]){
int v=c[0];
if(v!=p) dfs(v,u);
}
mark[u]=2;
}
static int dfs1( int s){
int sz=1;b[s]=true;
for(int[] x:g[s]){
int c=x[0];
if(!b[c]&&x[1]!=0){
sz+=dfs1(c);
}
}
return sz;
}
static void solve() throws IOException {
int n=int_v(read());
g=new ArrayList[n+1];
for(int i=0;i<=n;i++) g[i]=new ArrayList<>();
cycle=new ArrayList<>();
for(int i=0;i<n;i++){
int[] e=int_arr();
g[e[0]].add(new int[]{e[1],1});
g[e[1]].add(new int[]{e[0],1});
}
b=new boolean[n+1]; mark=new int[n+1];
bap=new int[n+1];
dfs(1,1);
for(int i=0;i<cycle.size()-1;i++){
int x=cycle.get(i),y=cycle.get(i+1);
for(int j=0;j<g[x].size();j++){
if(g[x].get(j)[0]==y){
g[x].get(j)[1]=0;break;
}
}
for(int j=0;j<g[y].size();j++){
if(g[y].get(j)[0]==x){
g[y].get(j)[1]=0;break;
}
}
}
long res=(long)n*(n-1);
Arrays.fill(b,false);b[0]=true;
for(int i=1;i<=n;i++){
if(b[i]) continue;
int sz=dfs1(i);
res-=(long)sz*(sz-1)/2l;
}
out.write(res+"\n");
}
public static void main(String[] args) throws IOException{
assign();
int t=int_v(read());
while(t--!=0) solve();
out.flush();
}
// taking inputs
static long pow1(long a,int p){long res=1;while(p>0){if((p&1)!=0){res=(res*a);}p >>=1;a=(a*a);}return res;}
static BufferedReader s1;
static BufferedWriter out;
static String read() throws IOException{String line="";while(line.length()==0){line=s1.readLine();continue;}return line;}
static int int_v (String s1){return Integer.parseInt(s1);}
static long long_v(String s1){return Long.parseLong(s1);}
static void sort(int[] a){List<Integer> l=new ArrayList<>();for(int x:a){l.add(x);}Collections.sort(l);for(int i=0;i<a.length;i++){a[i]=l.get(i);}}
static int[] int_arr() throws IOException{String[] a=read().split(" ");int[] b=new int[a.length];for(int i=0;i<a.length;i++){b[i]=int_v(a[i]);}return b;}
static long[] long_arr() throws IOException{String[] a=read().split(" ");long[] b=new long[a.length];for(int i=0;i<a.length;i++){b[i]=long_v(a[i]);}return b;}
static void assign(){s1=new BufferedReader(new InputStreamReader(System.in));out=new BufferedWriter(new OutputStreamWriter(System.out));}
//static String setpreciosion(double d,int k){BigDecimal d1 = new BigDecimal(Double.toString(d));return d1.setScale(k,RoundingMode.HALF_UP).toString();}//UP DOWN HALF_UP
static int gcd(int a,int b){if(b==0){return a;}return gcd(b,a%b);}
static long Modpow(long a,long p,long m){long res=1;while(p>0){if((p&1)!=0){res=(res*a)%m;}p >>=1;a=(a*a)%m;}return res%m;}
static long Modmul(long a,long b,long m){return ((a%m)*(b%m))%m;}
static long ModInv(long a,long m){return Modpow(a,m-2,m);}
//static long nck(int n,int r,long m){if(r>n){return 0l;}return Modmul(f[n],ModInv(Modmul(f[n-r],f[r],m),m),m);}
//static long[] f;
}
|
Java
|
["3\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
|
2 seconds
|
["6\n11\n18"]
|
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
|
Java 8
|
standard input
|
[
"combinatorics",
"dfs and similar",
"trees",
"graphs"
] |
1277cf54097813377bf37be445c06e7e
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
| null |
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
|
standard output
| |
PASSED
|
89da62cbd984c02840d50d7a95d9e424
|
train_000.jsonl
|
1606228500
|
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
|
256 megabytes
|
import java.util.*;
import java.io.*;
//import java.math.*;
public class Task{
// ..............code begins here..............
static long mod=(long)1e9+7;
static List<int[]>[] g;
static int[] in,low;
static boolean[] b;
static int timer=0;
static int tmp=0;
static void dfs(int u,int p){
in[u]=low[u]=timer++;
b[u]=true;
for(int i=0;i<g[u].size();i++){
int v=g[u].get(i)[0];
if(v==p) continue;
if(!b[v]){
dfs(v,u);
low[u]=Math.min(low[u],low[v]);
if(low[v]>in[u]){
g[u].get(i)[1]=1;tmp++;
}
}
else{
low[u]=Math.min(low[u],in[v]);
}
}
}
static int dfs1( int s){
int sz=1;b[s]=true;
for(int[] x:g[s]){
int c=x[0];
if(!b[c]&&x[1]!=0){
sz+=dfs1(c);
}
}
return sz;
}
static void solve() throws IOException {
int n=int_v(read());
g=new ArrayList[n+1];
for(int i=0;i<=n;i++) g[i]=new ArrayList<>();
for(int i=0;i<n;i++){
int[] e=int_arr();
g[e[0]].add(new int[]{e[1],0});
g[e[1]].add(new int[]{e[0],0});
}
b=new boolean[n+1];tmp=0;
in=new int[n+1]; low=new int[n+1];
dfs(1,-1);
long res=(long)n*(n-1);
Arrays.fill(b,false);b[0]=true;
for(int i=1;i<=n;i++){
if(b[i]) continue;
int sz=dfs1(i);
res-=(long)sz*(sz-1)/2l;
}
out.write(res+"\n");
}
public static void main(String[] args) throws IOException{
assign();
int t=int_v(read());
while(t--!=0) solve();
out.flush();
}
// taking inputs
static long pow1(long a,int p){long res=1;while(p>0){if((p&1)!=0){res=(res*a);}p >>=1;a=(a*a);}return res;}
static BufferedReader s1;
static BufferedWriter out;
static String read() throws IOException{String line="";while(line.length()==0){line=s1.readLine();continue;}return line;}
static int int_v (String s1){return Integer.parseInt(s1);}
static long long_v(String s1){return Long.parseLong(s1);}
static void sort(int[] a){List<Integer> l=new ArrayList<>();for(int x:a){l.add(x);}Collections.sort(l);for(int i=0;i<a.length;i++){a[i]=l.get(i);}}
static int[] int_arr() throws IOException{String[] a=read().split(" ");int[] b=new int[a.length];for(int i=0;i<a.length;i++){b[i]=int_v(a[i]);}return b;}
static long[] long_arr() throws IOException{String[] a=read().split(" ");long[] b=new long[a.length];for(int i=0;i<a.length;i++){b[i]=long_v(a[i]);}return b;}
static void assign(){s1=new BufferedReader(new InputStreamReader(System.in));out=new BufferedWriter(new OutputStreamWriter(System.out));}
//static String setpreciosion(double d,int k){BigDecimal d1 = new BigDecimal(Double.toString(d));return d1.setScale(k,RoundingMode.HALF_UP).toString();}//UP DOWN HALF_UP
static int gcd(int a,int b){if(b==0){return a;}return gcd(b,a%b);}
static long Modpow(long a,long p,long m){long res=1;while(p>0){if((p&1)!=0){res=(res*a)%m;}p >>=1;a=(a*a)%m;}return res%m;}
static long Modmul(long a,long b,long m){return ((a%m)*(b%m))%m;}
static long ModInv(long a,long m){return Modpow(a,m-2,m);}
//static long nck(int n,int r,long m){if(r>n){return 0l;}return Modmul(f[n],ModInv(Modmul(f[n-r],f[r],m),m),m);}
//static long[] f;
}
|
Java
|
["3\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
|
2 seconds
|
["6\n11\n18"]
|
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
|
Java 8
|
standard input
|
[
"combinatorics",
"dfs and similar",
"trees",
"graphs"
] |
1277cf54097813377bf37be445c06e7e
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
| null |
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
|
standard output
| |
PASSED
|
fb6a20409914339ea44704b14aaf04d9
|
train_000.jsonl
|
1606228500
|
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
|
256 megabytes
|
import java.util.*;
import java.io.*;
//import java.math.*;
public class Task{
// ..............code begins here..............
static long mod=(long)1e9+7;
static List<int[]>[] g;
static boolean[] b;
static List<Integer> cycle;
static int[] mark,bap;
static void dfs(int u,int p) throws IOException{
if(mark[u]==2) return;
if(mark[u]==1){ // visited but in system
cycle.add(u);
int curr=p;
while(curr!=u){
cycle.add(curr);
curr=bap[curr];
}
cycle.add(u);
return;
}
mark[u]=1;bap[u]=p;
for(int[] c:g[u]){
int v=c[0];
if(v!=p) dfs(v,u);
}
mark[u]=2;// finished
}
static int dfs1( int s){
int sz=1;b[s]=true;
for(int[] x:g[s]){
int c=x[0];
if(!b[c]&&x[1]!=0){
sz+=dfs1(c);
}
}
return sz;
}
static void solve() throws IOException {
int n=int_v(read());
g=new ArrayList[n+1];
for(int i=0;i<=n;i++) g[i]=new ArrayList<>();
cycle=new ArrayList<>();
for(int i=0;i<n;i++){
int[] e=int_arr();
g[e[0]].add(new int[]{e[1],1});
g[e[1]].add(new int[]{e[0],1});
}
b=new boolean[n+1]; mark=new int[n+1];
bap=new int[n+1];
dfs(1,-1);
for(int i=0;i<cycle.size()-1;i++){
int x=cycle.get(i),y=cycle.get(i+1);
for(int j=0;j<g[x].size();j++){
if(g[x].get(j)[0]==y){
g[x].get(j)[1]=0;break;
}
}
for(int j=0;j<g[y].size();j++){
if(g[y].get(j)[0]==x){
g[y].get(j)[1]=0;break;
}
}
}
long res=(long)n*(n-1);
Arrays.fill(b,false);b[0]=true;
for(int i=1;i<=n;i++){
if(b[i]) continue;
int sz=dfs1(i);
res-=(long)sz*(sz-1)/2l;
}
out.write(res+"\n");
}
public static void main(String[] args) throws IOException{
assign();
int t=int_v(read());
while(t--!=0) solve();
out.flush();
}
// taking inputs
static long pow1(long a,int p){long res=1;while(p>0){if((p&1)!=0){res=(res*a);}p >>=1;a=(a*a);}return res;}
static BufferedReader s1;
static BufferedWriter out;
static String read() throws IOException{String line="";while(line.length()==0){line=s1.readLine();continue;}return line;}
static int int_v (String s1){return Integer.parseInt(s1);}
static long long_v(String s1){return Long.parseLong(s1);}
static void sort(int[] a){List<Integer> l=new ArrayList<>();for(int x:a){l.add(x);}Collections.sort(l);for(int i=0;i<a.length;i++){a[i]=l.get(i);}}
static int[] int_arr() throws IOException{String[] a=read().split(" ");int[] b=new int[a.length];for(int i=0;i<a.length;i++){b[i]=int_v(a[i]);}return b;}
static long[] long_arr() throws IOException{String[] a=read().split(" ");long[] b=new long[a.length];for(int i=0;i<a.length;i++){b[i]=long_v(a[i]);}return b;}
static void assign(){s1=new BufferedReader(new InputStreamReader(System.in));out=new BufferedWriter(new OutputStreamWriter(System.out));}
//static String setpreciosion(double d,int k){BigDecimal d1 = new BigDecimal(Double.toString(d));return d1.setScale(k,RoundingMode.HALF_UP).toString();}//UP DOWN HALF_UP
static int gcd(int a,int b){if(b==0){return a;}return gcd(b,a%b);}
static long Modpow(long a,long p,long m){long res=1;while(p>0){if((p&1)!=0){res=(res*a)%m;}p >>=1;a=(a*a)%m;}return res%m;}
static long Modmul(long a,long b,long m){return ((a%m)*(b%m))%m;}
static long ModInv(long a,long m){return Modpow(a,m-2,m);}
//static long nck(int n,int r,long m){if(r>n){return 0l;}return Modmul(f[n],ModInv(Modmul(f[n-r],f[r],m),m),m);}
//static long[] f;
}
|
Java
|
["3\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
|
2 seconds
|
["6\n11\n18"]
|
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
|
Java 8
|
standard input
|
[
"combinatorics",
"dfs and similar",
"trees",
"graphs"
] |
1277cf54097813377bf37be445c06e7e
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
| null |
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
|
standard output
| |
PASSED
|
9447dcc2cd76dd51d3e08c568f62bf7d
|
train_000.jsonl
|
1606228500
|
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
|
256 megabytes
|
import java.util.*;
import java.io.*;
//import java.math.*;
public class Task{
// ..............code begins here..............
static long mod=(long)1e9+7;
static List<int[]>[] g;
static boolean[] b;
static List<Integer> cycle;
static int[] mark,bap;
static void dfs(int u,int p) throws IOException{
//if(mark[u]==2) return;
if(mark[u]==1){
cycle.add(u);
int curr=p;
while(curr!=u){
cycle.add(curr);
curr=bap[curr];
}
cycle.add(u);
return;
}
mark[u]=1;bap[u]=p;
for(int[] c:g[u]){
int v=c[0];
if(v!=p) dfs(v,u);
}
mark[u]=2;
}
static int dfs1( int s){
int sz=1;b[s]=true;
for(int[] x:g[s]){
int c=x[0];
if(!b[c]&&x[1]!=0){
sz+=dfs1(c);
}
}
return sz;
}
static void solve() throws IOException {
int n=int_v(read());
g=new ArrayList[n+1];
for(int i=0;i<=n;i++) g[i]=new ArrayList<>();
cycle=new ArrayList<>();
for(int i=0;i<n;i++){
int[] e=int_arr();
g[e[0]].add(new int[]{e[1],1});
g[e[1]].add(new int[]{e[0],1});
}
b=new boolean[n+1]; mark=new int[n+1];
bap=new int[n+1];
dfs(1,1);
for(int i=0;i<cycle.size()-1;i++){
int x=cycle.get(i),y=cycle.get(i+1);
for(int j=0;j<g[x].size();j++){
if(g[x].get(j)[0]==y){
g[x].get(j)[1]=0;break;
}
}
for(int j=0;j<g[y].size();j++){
if(g[y].get(j)[0]==x){
g[y].get(j)[1]=0;break;
}
}
}
long res=(long)n*(n-1);
Arrays.fill(b,false);b[0]=true;
for(int i=1;i<=n;i++){
if(b[i]) continue;
int sz=dfs1(i);
res-=(long)sz*(sz-1)/2l;
}
out.write(res+"\n");
}
public static void main(String[] args) throws IOException{
assign();
int t=int_v(read());
while(t--!=0) solve();
out.flush();
}
// taking inputs
static long pow1(long a,int p){long res=1;while(p>0){if((p&1)!=0){res=(res*a);}p >>=1;a=(a*a);}return res;}
static BufferedReader s1;
static BufferedWriter out;
static String read() throws IOException{String line="";while(line.length()==0){line=s1.readLine();continue;}return line;}
static int int_v (String s1){return Integer.parseInt(s1);}
static long long_v(String s1){return Long.parseLong(s1);}
static void sort(int[] a){List<Integer> l=new ArrayList<>();for(int x:a){l.add(x);}Collections.sort(l);for(int i=0;i<a.length;i++){a[i]=l.get(i);}}
static int[] int_arr() throws IOException{String[] a=read().split(" ");int[] b=new int[a.length];for(int i=0;i<a.length;i++){b[i]=int_v(a[i]);}return b;}
static long[] long_arr() throws IOException{String[] a=read().split(" ");long[] b=new long[a.length];for(int i=0;i<a.length;i++){b[i]=long_v(a[i]);}return b;}
static void assign(){s1=new BufferedReader(new InputStreamReader(System.in));out=new BufferedWriter(new OutputStreamWriter(System.out));}
}
|
Java
|
["3\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
|
2 seconds
|
["6\n11\n18"]
|
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
|
Java 8
|
standard input
|
[
"combinatorics",
"dfs and similar",
"trees",
"graphs"
] |
1277cf54097813377bf37be445c06e7e
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
| null |
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
|
standard output
| |
PASSED
|
39c1519f8a190ece9a368dfa4e10a7fe
|
train_000.jsonl
|
1606228500
|
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
|
256 megabytes
|
//package codeforces.round686div3;
import java.io.*;
import java.util.*;
public class E {
static InputReader in;
static PrintWriter out;
public static void main(String[] args) {
//initReaderPrinter(true);
initReaderPrinter(false);
solve(in.nextInt());
//solve(1);
}
static int n, endNode;
static final int UNVISITED = 0;
static final int VISITING = 1;
static final int VISITED = 2;
static List<Integer>[] adj;
static ArrayDeque<Integer> dq;
static int[] state;
static boolean[] inCycle;
static void solve(int testCnt) {
for (int testNumber = 0; testNumber < testCnt; testNumber++) {
n = in.nextInt();
adj = new List[n + 1];
for(int i = 0; i <= n; i++) {
adj[i] = new ArrayList<>();
}
for(int i = 0; i < n; i++) {
int u = in.nextInt();
int v = in.nextInt();
adj[u].add(v);
adj[v].add(u);
}
dq = new ArrayDeque<>();
state = new int[n + 1];
dfs(1, 0);
inCycle = new boolean[n + 1];
while(dq.peekLast() != endNode) {
inCycle[dq.removeLast()] = true;
}
inCycle[endNode] = true;
long ans = (long)n * (n - 1);
for(int i = 1; i <= n; i++) {
if(inCycle[i]) {
long cnt = bfs(i);
ans -= cnt * (cnt - 1) / 2;
}
}
out.println(ans);
}
out.close();
}
static int bfs(int start) {
int cnt = 0;
ArrayDeque<Integer> q = new ArrayDeque<>();
ArrayDeque<Integer> p = new ArrayDeque<>();
q.addLast(start);
p.addLast(0);
while(q.size() > 0) {
int curr = q.removeFirst();
int parent = p.removeFirst();
cnt++;
for(int next : adj[curr]) {
if(!inCycle[next] && next != parent) {
q.addLast(next);
p.addLast(curr);
}
}
}
return cnt;
}
static boolean dfs(int curr, int parent) {
if(state[curr] == VISITED) {
return false;
}
if(state[curr] == VISITING) {
endNode = curr;
return true;
}
state[curr] = VISITING;
dq.addLast(curr);
for(int next : adj[curr]) {
if(next == parent) continue;
if(dfs(next, curr)) {
return true;
}
}
dq.removeLast();
state[curr] = VISITED;
return false;
}
static void initReaderPrinter(boolean test) {
if (test) {
try {
in = new InputReader(new FileInputStream("src/input.in"));
out = new PrintWriter(new FileOutputStream("src/output.out"));
} catch (IOException e) {
e.printStackTrace();
}
} else {
in = new InputReader(System.in);
out = new PrintWriter(System.out);
}
}
static class InputReader {
BufferedReader br;
StringTokenizer st;
InputReader(InputStream stream) {
try {
br = new BufferedReader(new InputStreamReader(stream), 32768);
} catch (Exception e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
Integer[] nextIntArray(int n) {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
Long[] nextLongArray(int n) {
Long[] a = new Long[n];
for (int i = 0; i < n; i++) {
a[i] = nextLong();
}
return a;
}
}
}
|
Java
|
["3\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
|
2 seconds
|
["6\n11\n18"]
|
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
|
Java 8
|
standard input
|
[
"combinatorics",
"dfs and similar",
"trees",
"graphs"
] |
1277cf54097813377bf37be445c06e7e
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
| null |
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
|
standard output
| |
PASSED
|
ec507f5e14c27a6e4d24995f4cb3e772
|
train_000.jsonl
|
1316098800
|
Little John aspires to become a plumber! Today he has drawn a grid consisting of n rows and m columns, consisting of n × m square cells.In each cell he will draw a pipe segment. He can only draw four types of segments numbered from 1 to 4, illustrated as follows: Each pipe segment has two ends, illustrated by the arrows in the picture above. For example, segment 1 has ends at top and left side of it.Little John considers the piping system to be leaking if there is at least one pipe segment inside the grid whose end is not connected to another pipe's end or to the border of the grid. The image below shows an example of leaking and non-leaking systems of size 1 × 2. Now, you will be given the grid that has been partially filled by Little John. Each cell will either contain one of the four segments above, or be empty. Find the number of possible different non-leaking final systems after Little John finishes filling all of the empty cells with pipe segments. Print this number modulo 1000003 (106 + 3).Note that rotations or flipping of the grid are not allowed and so two configurations that are identical only when one of them has been rotated or flipped either horizontally or vertically are considered two different configurations.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.util.Map.*;
import java.math.*;
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);
Task solver = new E();
solver.solve(1, in, out);
out.close();
}
}
interface Task {
public void solve(int testNumber, InputReader in, OutputWriter out);
}
class A implements Task {
public void solve(int testNumber, InputReader in, OutputWriter out){
int n=in.readInt(), x, y, ret=0, cap=0;
while (n-->0) {
x=in.readInt();
y=in.readInt();
cap+=y-x;
ret=Math.max(ret, cap);
}
out.printLine(ret);
}
}
class B implements Task {
String[] arr;
int[] dx={-1, 0, 0, 1}, dy={0, -1, 1, 0};
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n=in.readInt(), m=in.readInt(), ret=0;
arr=new String[n];
for (int i=0; i<n; i++) arr[i]=in.next();
for (int i=0; i<n; i++) for (int j=0; j<m; j++) if (arr[i].charAt(j)=='W') {
boolean val=false;
for (int k=0; k<4; k++) {
int i2=i+dx[k], j2=j+dy[k];
if (i2>=0 && i2<n && j2>=0 && j2<m && arr[i2].charAt(j2)=='P') val=true;
}
if (val) ret++;
}
out.printLine(ret);
}
}
class C implements Task {
int[] pai, arr;
public void solve(int testNumber, InputReader in, OutputWriter out){
int n=in.readInt(), ret=0;
pai=new int[n+1];
arr=new int[n+1];
for (int i=1; i<=n; i++) pai[i]=in.readInt();
for (int i=1; i<=n; i++) ret=Math.max(ret, f(i));
out.printLine(ret);
}
int f(int x) {
if (arr[x]!=0) return arr[x];
if (pai[x]==-1) return arr[x]=1;
return arr[x]=f(pai[x])+1;
}
}
class Polygon {
public final Point[] vertices;
private Segment[] sides;
public Polygon(Point...vertices) {
this.vertices = vertices.clone();
}
public double square() {
double sum = 0;
for (int i = 1; i < vertices.length; i++)
sum += (vertices[i].x - vertices[i - 1].x) * (vertices[i].y + vertices[i - 1].y);
sum += (vertices[0].x - vertices[vertices.length - 1].x) * (vertices[0].y + vertices[vertices.length - 1].y);
return Math.abs(sum) / 2;
}
public Point center() {
double sx = 0;
double sy = 0;
for (Point point : vertices) {
sx += point.x;
sy += point.y;
}
return new Point(sx / vertices.length, sy / vertices.length);
}
public static boolean over(Point a, Point b, Point c) {
return a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y) < -GeometryUtils.epsilon;
}
private static boolean under(Point a, Point b, Point c) {
return a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y) > GeometryUtils.epsilon;
}
public static Polygon convexHull(Point[] points) {
if (points.length == 1)
return new Polygon(points);
Arrays.sort(points);
Point left = points[0];
Point right = points[points.length - 1];
List<Point> up = new ArrayList<Point>();
List<Point> down = new ArrayList<Point>();
for (Point point : points) {
if (point == left || point == right || !under(left, point, right)) {
while (up.size() >= 2 && under(up.get(up.size() - 2), up.get(up.size() - 1), point))
up.remove(up.size() - 1);
up.add(point);
}
if (point == left || point == right || !over(left, point, right)) {
while (down.size() >= 2 && over(down.get(down.size() - 2), down.get(down.size() - 1), point))
down.remove(down.size() - 1);
down.add(point);
}
}
Point[] result = new Point[up.size() + down.size() - 2];
int index = 0;
for (Point point : up)
result[index++] = point;
for (int i = down.size() - 2; i > 0; i--)
result[index++] = down.get(i);
return new Polygon(result);
}
public boolean contains(Point point) {
return contains(point, false);
}
public boolean contains(Point point, boolean strict) {
for (Segment segment : sides()) {
if (segment.contains(point, true))
return !strict;
}
double totalAngle = GeometryUtils.canonicalAngle(Math.atan2(vertices[0].y - point.y, vertices[0].x - point.x) -
Math.atan2(vertices[vertices.length - 1].y - point.y, vertices[vertices.length - 1].x - point.x));
for (int i = 1; i < vertices.length; i++) {
totalAngle += GeometryUtils.canonicalAngle(Math.atan2(vertices[i].y - point.y, vertices[i].x - point.x) -
Math.atan2(vertices[i - 1].y - point.y, vertices[i - 1].x - point.x));
}
return Math.abs(totalAngle) > Math.PI;
}
public Segment[] sides() {
if (sides == null) {
sides = new Segment[vertices.length];
for (int i = 0; i < vertices.length - 1; i++)
sides[i] = new Segment(vertices[i], vertices[i + 1]);
sides[sides.length - 1] = new Segment(vertices[vertices.length - 1], vertices[0]);
}
return sides;
}
public static double triangleSquare(Point a, Point b, Point c) {
return Math.abs((a.x - b.x) * (a.y + b.y) + (b.x - c.x) * (b.y + c.y) + (c.x - a.x) * (c.y + a.y)) / 2;
}
public double perimeter() {
double result = vertices[0].distance(vertices[vertices.length - 1]);
for (int i = 1; i < vertices.length; i++)
result += vertices[i].distance(vertices[i - 1]);
return result;
}
}
class Segment {
public final Point a;
public final Point b;
private double distance = Double.NaN;
private Line line = null;
public Segment(Point a, Point b) {
this.a = a;
this.b = b;
}
public double length() {
if (Double.isNaN(distance))
distance = a.distance(b);
return distance;
}
public double distance(Point point) {
double length = length();
double left = point.distance(a);
if (length < GeometryUtils.epsilon)
return left;
double right = point.distance(b);
if (left * left > right * right + length * length)
return right;
if (right * right > left * left + length * length)
return left;
return point.distance(line());
}
public Point intersect(Segment other, boolean includeEnds) {
Line line = line();
Line otherLine = other.a.line(other.b);
if (line.parallel(otherLine))
return null;
Point intersection = line.intersect(otherLine);
if (contains(intersection, includeEnds) && other.contains(intersection, includeEnds))
return intersection;
else
return null;
}
public boolean contains(Point point, boolean includeEnds) {
if (a.equals(point) || b.equals(point))
return includeEnds;
if (a.equals(b))
return false;
Line line = line();
if (!line.contains(point))
return false;
Line perpendicular = line.perpendicular(a);
double aValue = perpendicular.value(a);
double bValue = perpendicular.value(b);
double pointValue = perpendicular.value(point);
return aValue < pointValue && pointValue < bValue || bValue < pointValue && pointValue < aValue;
}
public Line line() {
if (line == null)
line = a.line(b);
return line;
}
public Point middle() {
return new Point((a.x + b.x) / 2, (a.y + b.y) / 2);
}
public Point[] intersect(Circle circle) {
Point[] result = line().intersect(circle);
if (result.length == 0)
return result;
if (result.length == 1) {
if (contains(result[0], true))
return result;
return new Point[0];
}
if (contains(result[0], true)) {
if (contains(result[1], true))
return result;
return new Point[]{result[0]};
}
if (contains(result[1], true))
return new Point[]{result[1]};
return new Point[0];
}
public Point intersect(Line line) {
Line selfLine = line();
Point intersect = selfLine.intersect(line);
if (intersect == null)
return null;
if (contains(intersect, true))
return intersect;
return null;
}
public double distance(Segment other) {
Line line = line();
Line otherLine = other.line();
Point p = line == null || otherLine == null ? null : line.intersect(otherLine);
if (p != null && contains(p, true) && other.contains(p, true))
return 0;
return Math.min(Math.min(other.distance(a), other.distance(b)), Math.min(distance(other.a), distance(other.b)));
}
}
class Vector {
public final double x;
public final double y;
public final Point point;
public Vector(double x, double y) {
this.x = x;
this.y = y;
point = new Point(x, y);
}
public Vector(Point point) {
this.x = point.x;
this.y = point.y;
this.point = point;
}
public Vector(Point from, Point to) {
this(to.x - from.x, to.y - from.y);
}
public double angleTo(Vector other) {
return GeometryUtils.canonicalAngle(other.point.angle() - point.angle());
}
public double length() {
return point.value();
}
public double angle() {
return point.angle();
}
}
class Point implements Comparable<Point>{
public static final Point ORIGIN = new Point(0, 0);
public final double x;
public final double y;
public int compareTo(Point o2) {
int value = Double.compare(this.x, o2.x);
if (value != 0)
return value;
return Double.compare(this.y, o2.y);
}
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public Line line(Point other) {
if (equals(other))
return null;
double a = other.y - y;
double b = x - other.x;
double c = -a * x - b * y;
return new Line(a, b, c);
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Point point = (Point) o;
return Math.abs(x - point.x) <= GeometryUtils.epsilon && Math.abs(y - point.y) <= GeometryUtils.epsilon;
}
@Override
public int hashCode() {
int result;
long temp;
temp = x != +0.0d ? Double.doubleToLongBits(x) : 0L;
result = (int) (temp ^ (temp >>> 32));
temp = y != +0.0d ? Double.doubleToLongBits(y) : 0L;
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
public double distance(Point other) {
return GeometryUtils.fastHypot(x - other.x, y - other.y);
}
public double distance(Line line) {
return Math.abs(line.a * x + line.b * y + line.c);
}
public double value() {
return GeometryUtils.fastHypot(x, y);
}
public double angle() {
return Math.atan2(y, x);
}
public static Point readPoint(InputReader in) {
double x = in.readDouble();
double y = in.readDouble();
return new Point(x, y);
}
public Point rotate(double angle) {
double nx = x * Math.cos(angle) - y * Math.sin(angle);
double ny = y * Math.cos(angle) + x * Math.sin(angle);
return new Point(nx, ny);
}
}
class Angle {
public final Point o;
public final Point a;
public final Point b;
public Angle(Point o, Point a, Point b) {
this.o = o;
this.a = a;
this.b = b;
}
public double value() {
double ab = a.distance(b);
double ao = a.distance(o);
double bo = b.distance(o);
return Math.acos((ao * ao + bo * bo - ab * ab) / (2 * ao * bo));
}
}
class GeometryUtils {
public static double epsilon = 1e-8;
public static double fastHypot(double...x) {
if (x.length == 0)
return 0;
else if (x.length == 1)
return Math.abs(x[0]);
else {
double sumSquares = 0;
for (double value : x)
sumSquares += value * value;
return Math.sqrt(sumSquares);
}
}
public static double fastHypot(double x, double y) {
return Math.sqrt(x * x + y * y);
}
public static double fastHypot(double[] x, double[] y) {
if (x.length == 0)
return 0;
else if (x.length == 1)
return Math.abs(x[0]- y[0]);
else {
double sumSquares = 0;
for (int i = 0; i < x.length; i++) {
double diff = x[i] - y[i];
sumSquares += diff * diff;
}
return Math.sqrt(sumSquares);
}
}
public static double fastHypot(int[] x, int[] y) {
if (x.length == 0)
return 0;
else if (x.length == 1)
return Math.abs(x[0]- y[0]);
else {
double sumSquares = 0;
for (int i = 0; i < x.length; i++) {
double diff = x[i] - y[i];
sumSquares += diff * diff;
}
return Math.sqrt(sumSquares);
}
}
public static double missileTrajectoryLength(double v, double angle, double g) {
return (v * v * Math.sin(2 * angle)) / g;
}
public static double sphereVolume(double radius) {
return 4 * Math.PI * radius * radius * radius / 3;
}
public static double triangleSquare(double first, double second, double third) {
double p = (first + second + third) / 2;
return Math.sqrt(p * (p - first) * (p - second) * (p - third));
}
public static double canonicalAngle(double angle) {
while (angle > Math.PI)
angle -= 2 * Math.PI;
while (angle < -Math.PI)
angle += 2 * Math.PI;
return angle;
}
public static double positiveAngle(double angle) {
while (angle > 2 * Math.PI - GeometryUtils.epsilon)
angle -= 2 * Math.PI;
while (angle < -GeometryUtils.epsilon)
angle += 2 * Math.PI;
return angle;
}
}
class Line {
public final double a;
public final double b;
public final double c;
public Line(Point p, double angle) {
a = Math.sin(angle);
b = -Math.cos(angle);
c = -p.x * a - p.y * b;
}
public Line(double a, double b, double c) {
double h = GeometryUtils.fastHypot(a, b);
this.a = a / h;
this.b = b / h;
this.c = c / h;
}
public Point intersect(Line other) {
if (parallel(other))
return null;
double determinant = b * other.a - a * other.b;
double x = (c * other.b - b * other.c) / determinant;
double y = (a * other.c - c * other.a) / determinant;
return new Point(x, y);
}
public boolean parallel(Line other) {
return Math.abs(a * other.b - b * other.a) < GeometryUtils.epsilon;
}
public boolean contains(Point point) {
return Math.abs(value(point)) < GeometryUtils.epsilon;
}
public Line perpendicular(Point point) {
return new Line(-b, a, b * point.x - a * point.y);
}
public double value(Point point) {
return a * point.x + b * point.y + c;
}
public Point[] intersect(Circle circle) {
double distance = distance(circle.center);
if (distance > circle.radius + GeometryUtils.epsilon)
return new Point[0];
Point intersection = intersect(perpendicular(circle.center));
if (Math.abs(distance - circle.radius) < GeometryUtils.epsilon)
return new Point[]{intersection};
double shift = Math.sqrt(circle.radius * circle.radius - distance * distance);
return new Point[]{new Point(intersection.x + shift * b, intersection.y - shift * a),
new Point(intersection.x - shift * b, intersection.y + shift * a)};
}
public double distance(Point center) {
return Math.abs(value(center));
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Line line = (Line) o;
if (!parallel(line)) return false;
if (Math.abs(a * line.c - c * line.a) > GeometryUtils.epsilon || Math.abs(b * line.c - c * line.b) > GeometryUtils.epsilon) return false;
return true;
}
}
class Circle {
public final Point center;
public final double radius;
public Circle(Point center, double radius) {
this.center = center;
this.radius = radius;
}
public boolean contains(Point point) {
return center.distance(point) < radius + GeometryUtils.epsilon;
}
public boolean strictContains(Point point) {
return center.distance(point) < radius - GeometryUtils.epsilon;
}
public Point[] findTouchingPoints(Point point) {
double distance = center.distance(point);
if (distance < radius - GeometryUtils.epsilon)
return new Point[0];
if (distance < radius + GeometryUtils.epsilon)
return new Point[]{point};
Circle power = new Circle(point, Math.sqrt((distance - radius) * (distance + radius)));
return intersect(power);
}
public Point[] intersect(Circle other) {
double distance = center.distance(other.center);
if (distance > radius + other.radius + GeometryUtils.epsilon || Math.abs(radius - other.radius) > distance + GeometryUtils.epsilon)
return new Point[0];
double p = (radius + other.radius + distance) / 2;
double height = 2 * Math.sqrt(p * (p - radius) * (p - other.radius) * (p - distance)) / distance;
double l1 = Math.sqrt(radius * radius - height * height);
double l2 = Math.sqrt(other.radius * other.radius - height * height);
if (radius * radius + distance * distance < other.radius * other.radius)
l1 = -l1;
if (radius * radius > distance * distance + other.radius * other.radius)
l2 = -l2;
Point middle = new Point((center.x * l2 + other.center.x * l1) / (l1 + l2),
(center.y * l2 + other.center.y * l1) / (l1 + l2));
Line line = center.line(other.center).perpendicular(middle);
return line.intersect(this);
}
}
class D implements Task {
int[] mini, maxi;
public void solve(int testNumber, InputReader in, OutputWriter out){
int n=in.readInt(), m=in.readInt(), ret=0, x=0, y=-1, i2, j2, f=-1;
String str;
mini=new int[n];
maxi=new int[n];
for (int i=0; i<n; i++) {
str=in.next();
mini[i]=1000;
maxi[i]=-1000;
for (int j=0; j<m; j++) if (str.charAt(j)=='W') {
mini[i]=Math.min(mini[i], j);
maxi[i]=Math.max(maxi[i], j);
if (f==-1) f=i;
}
}
if (f!=-1) ret+=f;
for (int i=0; i<n; i++) {
i2=1000;
j2=-1000;
if (i==f && i%2==1) ret+=x=maxi[i];
for (int j=i+1; j<n; j++) if (mini[j]!=i2 && maxi[j]!=j2) {
i2=mini[j];
j2=maxi[j];
y=j;
break;
}
if (mini[i]!=1000 && maxi[i]!=-1000) {
ret+=i%2==0?maxi[i]-x:x-mini[i];
x=i%2==0?maxi[i]:mini[i];
if (i2!=1000 && j2!=-1000) {
ret+=y-i+Math.abs(x-(y%2==0?i2:j2));
x=y%2==0?i2:j2;
}
}
}
out.printLine(ret);
}
}
class E implements Task {
String[] arr;
int[] pot=new int[500010];
public void solve(int testNumber, InputReader in, OutputWriter out){
int n=in.readInt(), m=in.readInt(), ret=0, prev;
char c1, c2;
boolean val=true, val2;
arr=new String[n];
pot[0]=1;
for (int i=1; i<500010; i++) pot[i]=pot[i-1]*2%1000003;
for (int i=0; i<n; i++) arr[i]=in.next();
for (int i=0; i<n; i++) {
val2=true;
prev=-1;
for (int j=0; j<m; j++) if (arr[i].charAt(j)!='.') {
if (prev!=-1 && ((j-prev)%2==1)==((arr[i].charAt(j)-'1')/2==(arr[i].charAt(prev)-'1')/2)) {
val=false;
}
val2=false;
prev=j;
}
if (val2) ret++;
}
//out.printLine(val?pot[ret]:0);
for (int j=0; j<m; j++) {
val2=true;
prev=-1;
for (int i=0; i<n; i++) if (arr[i].charAt(j)!='.') {
if (prev!=-1) {
c1=arr[i].charAt(j);
c2=arr[prev].charAt(j);
if (((i-prev)%2==1)==((c1=='1' || c1=='4')==(c2=='1' || c2=='4'))) val=false;
}
val2=false;
prev=i;
}
if (val2) ret++;
}
out.printLine(val?pot[ret]:0);
}
}
interface Edge {
public int getSource();
public int getDestination();
public long getWeight();
public long getCapacity();
public long getFlow();
public void pushFlow(long flow);
public boolean getFlag(int bit);
public void setFlag(int bit);
public void removeFlag(int bit);
public int getTransposedID();
public Edge getTransposedEdge();
public int getReverseID();
public Edge getReverseEdge();
public int getID();
public void remove();
public void restore();
}
class Graph {
public static final int REMOVED_BIT = 0;
protected int vertexCount;
protected int edgeCount;
private int[] firstOutbound;
private int[] firstInbound;
private Edge[] edges;
private int[] nextInbound;
private int[] nextOutbound;
private int[] from;
private int[] to;
private long[] weight;
private long[] capacity;
private int[] reverseEdge;
private int[] flags;
public Graph(int vertexCount) {
this(vertexCount, vertexCount);
}
public Graph(int vertexCount, int edgeCapacity) {
this.vertexCount = vertexCount;
firstOutbound = new int[vertexCount];
Arrays.fill(firstOutbound, -1);
from = new int[edgeCapacity];
to = new int[edgeCapacity];
nextOutbound = new int[edgeCapacity];
flags = new int[edgeCapacity];
}
public static Graph createGraph(int vertexCount, int[] from, int[] to) {
Graph graph = new Graph(vertexCount, from.length);
for (int i = 0; i < from.length; i++)
graph.addSimpleEdge(from[i], to[i]);
return graph;
}
public static Graph createWeightedGraph(int vertexCount, int[] from, int[] to, long[] weight) {
Graph graph = new Graph(vertexCount, from.length);
for (int i = 0; i < from.length; i++)
graph.addWeightedEdge(from[i], to[i], weight[i]);
return graph;
}
public static Graph createFlowGraph(int vertexCount, int[] from, int[] to, long[] capacity) {
Graph graph = new Graph(vertexCount, from.length * 2);
for (int i = 0; i < from.length; i++)
graph.addFlowEdge(from[i], to[i], capacity[i]);
return graph;
}
public static Graph createFlowWeightedGraph(int vertexCount, int[] from, int[] to, long[] weight, long[] capacity) {
Graph graph = new Graph(vertexCount, from.length * 2);
for (int i = 0; i < from.length; i++)
graph.addFlowWeightedEdge(from[i], to[i], weight[i], capacity[i]);
return graph;
}
public static Graph createTree(int[] parent) {
Graph graph = new Graph(parent.length + 1, parent.length);
for (int i = 0; i < parent.length; i++)
graph.addSimpleEdge(parent[i], i + 1);
return graph;
}
public int addEdge(int fromID, int toID, long weight, long capacity, int reverseEdge) {
ensureEdgeCapacity(edgeCount + 1);
if (firstOutbound[fromID] != -1)
nextOutbound[edgeCount] = firstOutbound[fromID];
else
nextOutbound[edgeCount] = -1;
firstOutbound[fromID] = edgeCount;
if (firstInbound != null) {
if (firstInbound[toID] != -1)
nextInbound[edgeCount] = firstInbound[toID];
else
nextInbound[edgeCount] = -1;
firstInbound[toID] = edgeCount;
}
this.from[edgeCount] = fromID;
this.to[edgeCount] = toID;
if (capacity != 0) {
if (this.capacity == null)
this.capacity = new long[from.length];
this.capacity[edgeCount] = capacity;
}
if (weight != 0) {
if (this.weight == null)
this.weight = new long[from.length];
this.weight[edgeCount] = weight;
}
if (reverseEdge != -1) {
if (this.reverseEdge == null) {
this.reverseEdge = new int[from.length];
Arrays.fill(this.reverseEdge, 0, edgeCount, -1);
}
this.reverseEdge[edgeCount] = reverseEdge;
}
if (edges != null)
edges[edgeCount] = createEdge(edgeCount);
return edgeCount++;
}
protected final GraphEdge createEdge(int id) {
return new GraphEdge(id);
}
public final int addFlowWeightedEdge(int from, int to, long weight, long capacity) {
if (capacity == 0) {
return addEdge(from, to, weight, 0, -1);
} else {
int lastEdgeCount = edgeCount;
addEdge(to, from, -weight, 0, lastEdgeCount + entriesPerEdge());
return addEdge(from, to, weight, capacity, lastEdgeCount);
}
}
protected int entriesPerEdge() {
return 1;
}
public final int addFlowEdge(int from, int to, long capacity) {
return addFlowWeightedEdge(from, to, 0, capacity);
}
public final int addWeightedEdge(int from, int to, long weight) {
return addFlowWeightedEdge(from, to, weight, 0);
}
public final int addSimpleEdge(int from, int to) {
return addWeightedEdge(from, to, 0);
}
public final int vertexCount() {
return vertexCount;
}
public final int edgeCount() {
return edgeCount;
}
protected final int edgeCapacity() {
return from.length;
}
public final Edge edge(int id) {
initEdges();
return edges[id];
}
public final int firstOutbound(int vertex) {
int id = firstOutbound[vertex];
while (id != -1 && isRemoved(id))
id = nextOutbound[id];
return id;
}
public final int nextOutbound(int id) {
id = nextOutbound[id];
while (id != -1 && isRemoved(id))
id = nextOutbound[id];
return id;
}
public final int firstInbound(int vertex) {
initInbound();
int id = firstInbound[vertex];
while (id != -1 && isRemoved(id))
id = nextInbound[id];
return id;
}
public final int nextInbound(int id) {
initInbound();
id = nextInbound[id];
while (id != -1 && isRemoved(id))
id = nextInbound[id];
return id;
}
public final int source(int id) {
return from[id];
}
public final int destination(int id) {
return to[id];
}
public final long weight(int id) {
if (weight == null)
return 0;
return weight[id];
}
public final long capacity(int id) {
if (capacity == null)
return 0;
return capacity[id];
}
public final long flow(int id) {
if (reverseEdge == null)
return 0;
return capacity[reverseEdge[id]];
}
public final void pushFlow(int id, long flow) {
if (flow == 0)
return;
if (flow > 0) {
if (capacity(id) < flow)
throw new IllegalArgumentException("Not enough capacity");
} else {
if (flow(id) < -flow)
throw new IllegalArgumentException("Not enough capacity");
}
capacity[id] -= flow;
capacity[reverseEdge[id]] += flow;
}
public int transposed(int id) {
return -1;
}
public final int reverse(int id) {
if (reverseEdge == null)
return -1;
return reverseEdge[id];
}
public final void addVertices(int count) {
ensureVertexCapacity(vertexCount + count);
Arrays.fill(firstOutbound, vertexCount, vertexCount + count, -1);
if (firstInbound != null)
Arrays.fill(firstInbound, vertexCount, vertexCount + count, -1);
vertexCount += count;
}
protected final void initEdges() {
if (edges == null) {
edges = new Edge[from.length];
for (int i = 0; i < edgeCount; i++)
edges[i] = createEdge(i);
}
}
public final void removeVertex(int vertex) {
int id = firstOutbound[vertex];
while (id != -1) {
removeEdge(id);
id = nextOutbound[id];
}
initInbound();
id = firstInbound[vertex];
while (id != -1) {
removeEdge(id);
id = nextInbound[id];
}
}
private void initInbound() {
if (firstInbound == null) {
firstInbound = new int[firstOutbound.length];
Arrays.fill(firstInbound, 0, vertexCount, -1);
nextInbound = new int[from.length];
for (int i = 0; i < edgeCount; i++) {
nextInbound[i] = firstInbound[to[i]];
firstInbound[to[i]] = i;
}
}
}
public final boolean flag(int id, int bit) {
return (flags[id] >> bit & 1) != 0;
}
public final void setFlag(int id, int bit) {
flags[id] |= 1 << bit;
}
public final void removeFlag(int id, int bit) {
flags[id] &= -1 - (1 << bit);
}
public final void removeEdge(int id) {
setFlag(id, REMOVED_BIT);
}
public final void restoreEdge(int id) {
removeFlag(id, REMOVED_BIT);
}
public final boolean isRemoved(int id) {
return flag(id, REMOVED_BIT);
}
public final Iterable<Edge> outbound(final int id) {
initEdges();
return new Iterable<Edge>() {
public Iterator<Edge> iterator() {
return new EdgeIterator(id, firstOutbound, nextOutbound);
}
};
}
public final Iterable<Edge> inbound(final int id) {
initEdges();
initInbound();
return new Iterable<Edge>() {
public Iterator<Edge> iterator() {
return new EdgeIterator(id, firstInbound, nextInbound);
}
};
}
protected void ensureEdgeCapacity(int size) {
if (from.length < size) {
int newSize = Math.max(size, 2 * from.length);
if (edges != null)
edges = resize(edges, newSize);
from = resize(from, newSize);
to = resize(to, newSize);
nextOutbound = resize(nextOutbound, newSize);
if (nextInbound != null)
nextInbound = resize(nextInbound, newSize);
if (weight != null)
weight = resize(weight, newSize);
if (capacity != null)
capacity = resize(capacity, newSize);
if (reverseEdge != null)
reverseEdge = resize(reverseEdge, newSize);
flags = resize(flags, newSize);
}
}
private void ensureVertexCapacity(int size) {
if (firstOutbound.length < size) {
int newSize = Math.max(size, 2 * from.length);
firstOutbound = resize(firstOutbound, newSize);
if (firstInbound != null)
firstInbound = resize(firstInbound, newSize);
}
}
protected final int[] resize(int[] array, int size) {
int[] newArray = new int[size];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
private long[] resize(long[] array, int size) {
long[] newArray = new long[size];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
private Edge[] resize(Edge[] array, int size) {
Edge[] newArray = new Edge[size];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
public final boolean isSparse() {
return vertexCount == 0 || edgeCount * 20 / vertexCount <= vertexCount;
}
protected class GraphEdge implements Edge {
protected int id;
protected GraphEdge(int id) {
this.id = id;
}
public int getSource() {
return source(id);
}
public int getDestination() {
return destination(id);
}
public long getWeight() {
return weight(id);
}
public long getCapacity() {
return capacity(id);
}
public long getFlow() {
return flow(id);
}
public void pushFlow(long flow) {
Graph.this.pushFlow(id, flow);
}
public boolean getFlag(int bit) {
return flag(id, bit);
}
public void setFlag(int bit) {
Graph.this.setFlag(id, bit);
}
public void removeFlag(int bit) {
Graph.this.removeFlag(id, bit);
}
public int getTransposedID() {
return transposed(id);
}
public Edge getTransposedEdge() {
int reverseID = getTransposedID();
if (reverseID == -1)
return null;
initEdges();
return edge(reverseID);
}
public int getReverseID() {
return reverse(id);
}
public Edge getReverseEdge() {
int reverseID = getReverseID();
if (reverseID == -1)
return null;
initEdges();
return edge(reverseID);
}
public int getID() {
return id;
}
public void remove() {
removeEdge(id);
}
public void restore() {
restoreEdge(id);
}
}
public class EdgeIterator implements Iterator<Edge> {
private int edgeID;
private final int[] next;
private int lastID = -1;
public EdgeIterator(int id, int[] first, int[] next) {
this.next = next;
edgeID = nextEdge(first[id]);
}
private int nextEdge(int id) {
while (id != -1 && isRemoved(id))
id = next[id];
return id;
}
public boolean hasNext() {
return edgeID != -1;
}
public Edge next() {
if (edgeID == -1)
throw new NoSuchElementException();
lastID = edgeID;
edgeID = nextEdge(next[lastID]);
return edges[lastID];
}
public void remove() {
if (lastID == -1)
throw new IllegalStateException();
removeEdge(lastID);
lastID = -1;
}
}
}
abstract class IntervalTree {
protected int size;
protected IntervalTree(int size) {
this(size, true);
}
public IntervalTree(int size, boolean shouldInit) {
this.size = size;
int nodeCount = Math.max(1, Integer.highestOneBit(size) << 2);
initData(size, nodeCount);
if (shouldInit)
init();
}
protected abstract void initData(int size, int nodeCount);
protected abstract void initAfter(int root, int left, int right, int middle);
protected abstract void initBefore(int root, int left, int right, int middle);
protected abstract void initLeaf(int root, int index);
protected abstract void updatePostProcess(int root, int left, int right, int from, int to, long delta, int middle);
protected abstract void updatePreProcess(int root, int left, int right, int from, int to, long delta, int middle);
protected abstract void updateFull(int root, int left, int right, int from, int to, long delta);
protected abstract long queryPostProcess(int root, int left, int right, int from, int to, int middle, long leftResult, long rightResult);
protected abstract void queryPreProcess(int root, int left, int right, int from, int to, int middle);
protected abstract long queryFull(int root, int left, int right, int from, int to);
protected abstract long emptySegmentResult();
public void init() {
if (size == 0)
return;
init(0, 0, size - 1);
}
private void init(int root, int left, int right) {
if (left == right) {
initLeaf(root, left);
} else {
int middle = (left + right) >> 1;
initBefore(root, left, right, middle);
init(2 * root + 1, left, middle);
init(2 * root + 2, middle + 1, right);
initAfter(root, left, right, middle);
}
}
public void update(int from, int to, long delta) {
update(0, 0, size - 1, from, to, delta);
}
protected void update(int root, int left, int right, int from, int to, long delta) {
if (left > to || right < from)
return;
if (left >= from && right <= to) {
updateFull(root, left, right, from, to, delta);
return;
}
int middle = (left + right) >> 1;
updatePreProcess(root, left, right, from, to, delta, middle);
update(2 * root + 1, left, middle, from, to, delta);
update(2 * root + 2, middle + 1, right, from, to, delta);
updatePostProcess(root, left, right, from, to, delta, middle);
}
public long query(int from, int to) {
return query(0, 0, size - 1, from, to);
}
protected long query(int root, int left, int right, int from, int to) {
if (left > to || right < from)
return emptySegmentResult();
if (left >= from && right <= to)
return queryFull(root, left, right, from, to);
int middle = (left + right) >> 1;
queryPreProcess(root, left, right, from, to, middle);
long leftResult = query(2 * root + 1, left, middle, from, to);
long rightResult = query(2 * root + 2, middle + 1, right, from, to);
return queryPostProcess(root, left, right, from, to, middle, leftResult, rightResult);
}
}
abstract class ReadOnlyIntervalTree extends IntervalTree {
protected long[] value;
protected long[] array;
protected ReadOnlyIntervalTree(long[] array) {
super(array.length, false);
this.array = array;
init();
}
@Override
protected void initData(int size, int nodeCount) {
value = new long[nodeCount];
}
@Override
protected void initAfter(int root, int left, int right, int middle) {
value[root] = joinValue(value[2 * root + 1], value[2 * root + 2]);
}
@Override
protected void initBefore(int root, int left, int right, int middle) {
}
@Override
protected void initLeaf(int root, int index) {
value[root] = array[index];
}
@Override
protected void updatePostProcess(int root, int left, int right, int from, int to, long delta, int middle) {
throw new UnsupportedOperationException();
}
@Override
protected void updatePreProcess(int root, int left, int right, int from, int to, long delta, int middle) {
throw new UnsupportedOperationException();
}
@Override
protected void updateFull(int root, int left, int right, int from, int to, long delta) {
throw new UnsupportedOperationException();
}
@Override
protected long queryPostProcess(int root, int left, int right, int from, int to, int middle, long leftResult, long rightResult) {
return joinValue(leftResult, rightResult);
}
@Override
protected void queryPreProcess(int root, int left, int right, int from, int to, int middle) {
}
@Override
protected long queryFull(int root, int left, int right, int from, int to) {
return value[root];
}
@Override
protected long emptySegmentResult() {
return neutralValue();
}
@Override
public void update(int from, int to, long delta) {
throw new UnsupportedOperationException();
}
@Override
protected void update(int root, int left, int right, int from, int to, long delta) {
throw new UnsupportedOperationException();
}
protected abstract long neutralValue();
protected abstract long joinValue(long left, long right);
}
class LCA {
private final long[] order;
private final int[] position;
private final Graph graph;
private final IntervalTree lcaTree;
private final int[] level;
public LCA(Graph graph) {
this(graph, 0);
}
public LCA(Graph graph, int root) {
this.graph = graph;
order = new long[2 * graph.vertexCount() - 1];
position = new int[graph.vertexCount()];
level = new int[graph.vertexCount()];
int[] index = new int[graph.vertexCount()];
for (int i = 0; i < index.length; i++)
index[i] = graph.firstOutbound(i);
int[] last = new int[graph.vertexCount()];
int[] stack = new int[graph.vertexCount()];
stack[0] = root;
int size = 1;
int j = 0;
last[root] = -1;
Arrays.fill(position, -1);
while (size > 0) {
int vertex = stack[--size];
if (position[vertex] == -1)
position[vertex] = j;
order[j++] = vertex;
if (last[vertex] != -1)
level[vertex] = level[last[vertex]] + 1;
while (index[vertex] != -1 && last[vertex] == graph.destination(index[vertex]))
index[vertex] = graph.nextOutbound(index[vertex]);
if (index[vertex] != -1) {
stack[size++] = vertex;
stack[size++] = graph.destination(index[vertex]);
last[graph.destination(index[vertex])] = vertex;
index[vertex] = graph.nextOutbound(index[vertex]);
}
}
lcaTree = new ReadOnlyIntervalTree(order) {
@Override
protected long joinValue(long left, long right) {
if (left == -1)
return right;
if (right == -1)
return left;
if (level[((int) left)] < level[((int) right)])
return left;
return right;
}
@Override
protected long neutralValue() {
return -1;
}
};
lcaTree.init();
}
public int getPosition(int vertex) {
return position[vertex];
}
public int getLCA(int first, int second) {
return (int) lcaTree.query(Math.min(position[first], position[second]), Math.max(position[first], position[second]));
}
public int getLevel(int vertex) {
return level[vertex];
}
public int getPathLength(int first, int second) {
return level[first] + level[second] - 2 * level[getLCA(first, second)];
}
private int calculate(int vertex, int last, int currentPosition) {
if (last != -1)
level[vertex] = level[last] + 1;
position[vertex] = currentPosition;
order[currentPosition++] = vertex;
for (int i = graph.firstOutbound(vertex); i != -1; i = graph.nextOutbound(i)) {
int to = graph.destination(i);
if (to != last) {
currentPosition = calculate(to, vertex, currentPosition);
order[currentPosition++] = vertex;
}
}
return currentPosition;
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1)
return -1;
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0)
return -1;
}
return buf[curChar];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c))
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r')
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines)
return readLine();
else
return readLine0();
}
public BigInteger readBigInteger() {
try {
return new BigInteger(readString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1)
read();
return value == -1;
}
public String next() {
return readString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(char[] array) {
writer.print(array);
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void print(int[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(array[i]);
}
}
public void print(long[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(array[i]);
}
}
public void printLine(int[] array) {
print(array);
writer.println();
}
public void printLine(long[] array) {
print(array);
writer.println();
}
public void printLine() {
writer.println();
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void print(char i) {
writer.print(i);
}
public void printLine(char i) {
writer.println(i);
}
public void printLine(char[] array) {
writer.println(array);
}
public void printFormat(String format, Object...objects) {
writer.printf(format, objects);
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
public void print(long i) {
writer.print(i);
}
public void printLine(long i) {
writer.println(i);
}
public void print(int i) {
writer.print(i);
}
public void printLine(int i) {
writer.println(i);
}
}
|
Java
|
["2 2\n13\n..", "3 1\n1\n4\n.", "2 2\n3.\n.1"]
|
3 seconds
|
["2", "0", "1"]
|
NoteFor the first example, the initial configuration of the grid is as follows. The only two possible final non-leaking pipe configurations are as follows: For the second example, the initial grid is already leaking, so there will be no final grid that is non-leaking.For the final example, there's only one possible non-leaking final grid as follows.
|
Java 8
|
standard input
|
[] |
07cbcf6e1f1e7f1a6ec45241cf9ac2a9
|
The first line will contain two single-space separated integers n and m (1 ≤ n, m, n·m ≤ 5·105) — the number of rows and columns respectively. Then n lines follow, each contains exactly m characters — the description of the grid. Each character describes a cell and is either one of these: "1" - "4" — a pipe segment of one of four types as described above "." — an empty cell
| 2,200 |
Print a single integer denoting the number of possible final non-leaking pipe systems modulo 1000003 (106 + 3). If there are no such configurations, print 0.
|
standard output
| |
PASSED
|
bde1b80807898c3bcf60ffcb0736c2e7
|
train_000.jsonl
|
1316098800
|
Little John aspires to become a plumber! Today he has drawn a grid consisting of n rows and m columns, consisting of n × m square cells.In each cell he will draw a pipe segment. He can only draw four types of segments numbered from 1 to 4, illustrated as follows: Each pipe segment has two ends, illustrated by the arrows in the picture above. For example, segment 1 has ends at top and left side of it.Little John considers the piping system to be leaking if there is at least one pipe segment inside the grid whose end is not connected to another pipe's end or to the border of the grid. The image below shows an example of leaking and non-leaking systems of size 1 × 2. Now, you will be given the grid that has been partially filled by Little John. Each cell will either contain one of the four segments above, or be empty. Find the number of possible different non-leaking final systems after Little John finishes filling all of the empty cells with pipe segments. Print this number modulo 1000003 (106 + 3).Note that rotations or flipping of the grid are not allowed and so two configurations that are identical only when one of them has been rotated or flipped either horizontally or vertically are considered two different configurations.
|
256 megabytes
|
import java.util.*;
public class cf115c {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
char[][] v = new char[n][];
for(int i=0; i<n; i++)
v[i] = in.next().trim().toCharArray();
int ret = 1;
int mod = (int)1e6+3;
boolean[] ok = new boolean[2];
for(int i=0; i<n; i++) {
ok[0] = ok[1] = true;
for(int j=0; j<m; j++) {
if(v[i][j]=='1'||v[i][j]=='2')
ok[j%2] = false;
if(v[i][j]=='3'||v[i][j]=='4')
ok[(j+1)%2] = false;
}
int mult = (ok[0]?1:0) + (ok[1]?1:0);
ret = (ret*mult)%mod;
}
for(int j=0; j<m; j++) {
ok[0] = ok[1] = true;
for(int i=0; i<n; i++) {
if(v[i][j]=='1'||v[i][j]=='4')
ok[i%2] = false;
if(v[i][j]=='2'||v[i][j]=='3')
ok[(i+1)%2] = false;
}
int mult = (ok[0]?1:0) + (ok[1]?1:0);
ret = (ret*mult)%mod;
}
System.out.println(ret);
}
}
|
Java
|
["2 2\n13\n..", "3 1\n1\n4\n.", "2 2\n3.\n.1"]
|
3 seconds
|
["2", "0", "1"]
|
NoteFor the first example, the initial configuration of the grid is as follows. The only two possible final non-leaking pipe configurations are as follows: For the second example, the initial grid is already leaking, so there will be no final grid that is non-leaking.For the final example, there's only one possible non-leaking final grid as follows.
|
Java 6
|
standard input
|
[] |
07cbcf6e1f1e7f1a6ec45241cf9ac2a9
|
The first line will contain two single-space separated integers n and m (1 ≤ n, m, n·m ≤ 5·105) — the number of rows and columns respectively. Then n lines follow, each contains exactly m characters — the description of the grid. Each character describes a cell and is either one of these: "1" - "4" — a pipe segment of one of four types as described above "." — an empty cell
| 2,200 |
Print a single integer denoting the number of possible final non-leaking pipe systems modulo 1000003 (106 + 3). If there are no such configurations, print 0.
|
standard output
| |
PASSED
|
9f4d03d90012c825b7bd010793006682
|
train_000.jsonl
|
1316098800
|
Little John aspires to become a plumber! Today he has drawn a grid consisting of n rows and m columns, consisting of n × m square cells.In each cell he will draw a pipe segment. He can only draw four types of segments numbered from 1 to 4, illustrated as follows: Each pipe segment has two ends, illustrated by the arrows in the picture above. For example, segment 1 has ends at top and left side of it.Little John considers the piping system to be leaking if there is at least one pipe segment inside the grid whose end is not connected to another pipe's end or to the border of the grid. The image below shows an example of leaking and non-leaking systems of size 1 × 2. Now, you will be given the grid that has been partially filled by Little John. Each cell will either contain one of the four segments above, or be empty. Find the number of possible different non-leaking final systems after Little John finishes filling all of the empty cells with pipe segments. Print this number modulo 1000003 (106 + 3).Note that rotations or flipping of the grid are not allowed and so two configurations that are identical only when one of them has been rotated or flipped either horizontally or vertically are considered two different configurations.
|
256 megabytes
|
import java.util.*;
public class A {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = 3;
int ans = 1;
boolean f = true;
int m = in.nextInt();
String s[] = new String[n];
in.nextLine();
for (int i = 0;i<n;i++){
s[i] = in.nextLine();
}
for (int i = 0;i<n;i++){
k=3;
for (int j = 0;j<m;j++){
if (s[i].charAt(j)=='1'||s[i].charAt(j)=='2')
{
k = k&(1+j%2);
}
if (s[i].charAt(j)=='3'||s[i].charAt(j)=='4')
{
k = k&(2-j%2);
}
}
if (k==3) {ans = ans *2 % 1000003;}
if (k==0) {ans = 0;f = false;}
}
if (f){
for (int j = 0;j<m;j++){
k=3;
for (int i = 0;i<n;i++){
if (s[i].charAt(j)=='1'||s[i].charAt(j)=='4')
{
k = k&(1+i%2);
}
if (s[i].charAt(j)=='3'||s[i].charAt(j)=='2')
{
k = k&(2-i%2);
}
}
if (k==3) {ans = ans *2%1000003;}
if (k==0) {ans = 0;}
}
}
System.out.print(ans);
}
}
|
Java
|
["2 2\n13\n..", "3 1\n1\n4\n.", "2 2\n3.\n.1"]
|
3 seconds
|
["2", "0", "1"]
|
NoteFor the first example, the initial configuration of the grid is as follows. The only two possible final non-leaking pipe configurations are as follows: For the second example, the initial grid is already leaking, so there will be no final grid that is non-leaking.For the final example, there's only one possible non-leaking final grid as follows.
|
Java 6
|
standard input
|
[] |
07cbcf6e1f1e7f1a6ec45241cf9ac2a9
|
The first line will contain two single-space separated integers n and m (1 ≤ n, m, n·m ≤ 5·105) — the number of rows and columns respectively. Then n lines follow, each contains exactly m characters — the description of the grid. Each character describes a cell and is either one of these: "1" - "4" — a pipe segment of one of four types as described above "." — an empty cell
| 2,200 |
Print a single integer denoting the number of possible final non-leaking pipe systems modulo 1000003 (106 + 3). If there are no such configurations, print 0.
|
standard output
| |
PASSED
|
070100667b502172c68cd87ed2c1113a
|
train_000.jsonl
|
1448636400
|
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
|
256 megabytes
|
//package proje;
//import java.io.BufferedReader;
//import java.io.BufferedWriter;
//import java.io.InputStreamReader;
import java.io.*;
import java.util.*;
public class jk
{
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
String f = sc.next();
OutputStream outputstream = System.out;
PrintWriter out = new PrintWriter(outputstream);
//String f = in.readLine();
//char[] alphab = new char[26];
int[] alpha = new int[26];
//char[] temp=f.toCharArray();
for(int y=0; y<f.length(); y++)
{
//char g = temp[y];
alpha[f.charAt(y)-97]++;
//alphab[g-97]=g;
}
StringBuilder gm =new StringBuilder();
LinkedList<Integer> odd = new LinkedList<Integer>();
for(int y=0; y<26; y++)
{
//int lf=0;
if(alpha[y]%2==1)
{
odd.add(y);
}
}
Integer[] newa = new Integer[odd.size()] ;
odd.toArray(newa);
for(int mp=0; mp<newa.length/2; mp++)
{
alpha[newa[mp]]++;
alpha[newa[newa.length-1-mp]]--;
}
int oddin = 0;
for(int y=0; y<26; y++)
{
if(alpha[y]%2==1)
{
oddin=y;
}
}
for(int i=0; i<26; i++)
{
if(alpha[i]>0)
{
for(int m=1; m<=alpha[i]/2; m++)
{
gm.append((char)(i+(int)'a'));
}
}
}
StringBuilder buffer = new StringBuilder();
//temp=gm.toCharArray();
buffer.append(gm);
if(f.length()%2==1)
gm.append((char)(oddin+(int)'a'));
gm=gm.append(buffer.reverse());
out.println(gm);
out.flush();
out.close();
}
}
|
Java
|
["aabc", "aabcd"]
|
2 seconds
|
["abba", "abcba"]
| null |
Java 8
|
standard input
|
[
"constructive algorithms",
"greedy",
"strings"
] |
f996224809df700265d940b12622016f
|
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
| 1,800 |
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
|
standard output
| |
PASSED
|
4b1186947ee9cd629cae207dbb5d849d
|
train_000.jsonl
|
1448636400
|
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args)throws IOException, URISyntaxException {
Reader.init(System.in);
StringBuilder s=new StringBuilder();
int[] f = new int[26];
String str = Reader.nextLine();
for(int i = 0; i < str.length(); i++)
f[str.charAt(i) - 'a']++;
ArrayList<Integer> arr = new ArrayList<Integer>();
for(int i = 0; i < 26; i++)
if(f[i] % 2 == 1)
arr.add(i);
if(arr.size() > 0) {
int i = 0, l = arr.size() - 1;
while(i < l) {
f[arr.get(i)]++;
f[arr.get(l)]--;
i++;
l--;
}
}
char[] res = new char[str.length()];
int l = 0, r = res.length - 1;
for(int i = 0; i < 26; i++) {
if(f[i] % 2 == 1) {
res[res.length / 2] = (char) (i + 'a');
f[i]--;
}
while(f[i] > 0) {
res[l] = res[r] = (char) (i + 'a');
l++;
r--;
f[i] -= 2;
}
}
for(char c : res)
s.append(c);
s.append('\n');
System.out.print(s);
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) throws UnsupportedEncodingException {
reader = new BufferedReader(
new InputStreamReader(input, "UTF-8") );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static String nextLine() throws IOException {
return reader.readLine();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
static long nextLong() throws IOException {
return Long.parseLong( next() );
}
}
|
Java
|
["aabc", "aabcd"]
|
2 seconds
|
["abba", "abcba"]
| null |
Java 8
|
standard input
|
[
"constructive algorithms",
"greedy",
"strings"
] |
f996224809df700265d940b12622016f
|
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
| 1,800 |
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
|
standard output
| |
PASSED
|
d7f33db495430e890ad9835fe10e7164
|
train_000.jsonl
|
1448636400
|
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
|
256 megabytes
|
/**
* ******* Created on 12/11/19 1:44 PM*******
*/
import java.io.*;
import java.util.*;
public class C600 implements Runnable {
private static final int MAX = (int) 1e5 + 10;
private static final int MOD = (int) 1e9 + 7;
private void solve() throws IOException {
int t = 1;
while (t-- > 0) {
String s = reader.next();
int[] freq = new int[26];
Arrays.fill(freq,0);
int len = s.length();
for(int i=0;i<s.length();i++)
freq[s.charAt(i)-'a']++;
int l =0,r = 25;
while(l < r){
if(freq[l]%2==0)l++;
else if (freq[r]%2==0)r--;
else{
freq[l]++;freq[r]--;
l++;r--;
}
}
StringBuilder sb = new StringBuilder();
StringBuilder sb1 = new StringBuilder();
for(int i=0;i<26;i++)
while(freq[i]>=2)
{
sb.append((char)(i+'a'));
freq[i]-=2;
sb1.append((char)(i+'a'));
}
for(int i=0;i<26;i++)
if(freq[i]==1)
sb.append((char)(i+'a'));
writer.println(sb.toString()+sb1.reverse().toString()
);
}
}
private void printString(int[] a, int len ) {
StringBuilder sb = new StringBuilder();
String middle="";
for(int i=0;i<25;i++)
{
if(a[i]%2==0){
a[i]/=2;
while(a[i]>0){
sb.append(Character.valueOf((char) (i+'a')));
a[i]--;
}
}else{
middle = String.valueOf((char) (i+'a'));
a[i]/=2;
while(a[i]>0){
sb.append(Character.valueOf((char) (i+'a')));
a[i]--;
}
}
}
writer.println(sb.toString()+middle+sb.reverse().toString());
}
public static void main(String[] args) throws IOException {
try (Input reader = new StandardInput(); PrintWriter writer = new PrintWriter(System.out)) {
new C600().run();
}
}
StandardInput reader;
PrintWriter writer;
@Override
public void run() {
try {
reader = new StandardInput();
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
interface Input extends Closeable {
String next() throws IOException;
default int nextInt() throws IOException {
return Integer.parseInt(next());
}
default long nextLong() throws IOException {
return Long.parseLong(next());
}
default double nextDouble() throws IOException {
return Double.parseDouble(next());
}
default int[] readIntArray() throws IOException {
return readIntArray(nextInt());
}
default int[] readIntArray(int size) throws IOException {
int[] array = new int[size];
for (int i = 0; i < array.length; i++) {
array[i] = nextInt();
}
return array;
}
default long[] readLongArray(int size) throws IOException {
long[] array = new long[size];
for (int i = 0; i < array.length; i++) {
array[i] = nextLong();
}
return array;
}
}
private static class StandardInput implements Input {
private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
private StringTokenizer stringTokenizer;
@Override
public void close() throws IOException {
reader.close();
}
@Override
public String next() throws IOException {
if (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
stringTokenizer = new StringTokenizer(reader.readLine());
}
return stringTokenizer.nextToken();
}
}
}
|
Java
|
["aabc", "aabcd"]
|
2 seconds
|
["abba", "abcba"]
| null |
Java 8
|
standard input
|
[
"constructive algorithms",
"greedy",
"strings"
] |
f996224809df700265d940b12622016f
|
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
| 1,800 |
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
|
standard output
| |
PASSED
|
856ee7d15346def50ac81c4a376938fc
|
train_000.jsonl
|
1448636400
|
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
|
256 megabytes
|
import java.util.Scanner;
//import java.lang.StringBuilder;
public class Main {
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
int a = str.length();
char[] c = str.toCharArray();
int[] d = new int[26];
for (char i : c) {
d[i-97]++;
}
int i = 0, j = 25;
while (i < j) {
while (d[i] % 2 == 0) {
i++;
if (i > 24) { break; }
}
while (d[j] % 2 == 0) {
j--;
if (j < 1) { break; }
}
if (i < j) {
d[j]--;
d[i]++;
}
}
j = 0;
i = 0;
if (a % 2 == 1) {
while (d[i] % 2 != 1) {
i++;
}
c[a/2] = (char) (i + 97);
d[i]--;
}
for (i = 0; i < 26; i++) {
while (d[i] > 0) {
char x = (char) (i + 97);
c[j] = x;
c[a-j-1] = x;
d[i] -= 2;
j++;
}
}
for (char y : c) {
System.out.print(y);
}
}
}
|
Java
|
["aabc", "aabcd"]
|
2 seconds
|
["abba", "abcba"]
| null |
Java 8
|
standard input
|
[
"constructive algorithms",
"greedy",
"strings"
] |
f996224809df700265d940b12622016f
|
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
| 1,800 |
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
|
standard output
| |
PASSED
|
c712b12d73de1a402a64c8b639e1c5d2
|
train_000.jsonl
|
1448636400
|
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class EDU2C {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
String line = sc.next();
int [] cChars = new int[26];
for(int i=0; i<line.length(); i++)
cChars[line.charAt(i)-'a']++;
int odd = 0;
int even = 0;
int firstOdd = -1;
ArrayList<Entry> oddPos = new ArrayList<Entry>();
for(int i=0; i<26; i++)
if(cChars[i]%2==0)
even++;
else{
odd++;
oddPos.add(new Entry(cChars[i],i));
}
//if(oddPos.size()%2==0){
//System.out.println(oddPos);
for(int k=0; k<oddPos.size();k++ ){
int j = oddPos.size()-1 - k;
if(k>=j)
break;
oddPos.get(k).occ = oddPos.get(k).occ+1;
oddPos.get(j).occ = oddPos.get(j).occ-1;
}
//System.out.println(oddPos);
for(int i=0; i<oddPos.size(); i++)
cChars[oddPos.get(i).l] = oddPos.get(i).occ;
//}
// else
// {
// for(int k=0; k<oddPos.size()-1;k++ ){
// int j = oddPos.size()-1 - k;
// if(k>=j)
// break;
// oddPos.set(k, oddPos.get(k)+1);
// oddPos.set(j, oddPos.get(j)-1);
//
// }
// }
//System.out.println(Arrays.toString(cChars));
char [] res = new char[line.length()];
int pos1 = 0;
int pos2 = res.length-1;
while(pos1<pos2){
for(int i=0; i<26; i++){
while(cChars[i]>1){
res[pos1++] = (char)('a'+i);
cChars[i]--;
if(cChars[i]==0)
break;
res[pos2--] = (char)('a'+i);
cChars[i]--;
}
}
}
for(int i=0; i<26; i++){
if(cChars[i] == 1){
res[res.length/2] = (char)(i+'a');
break;
}
}
System.out.println(new String(res));
}
static class Entry{
int occ;
int l;
public Entry(int x, int y){occ = x; l = y;}
public String toString(){
return this.occ+" "+(char)(l+'a');
}
}
static class Scanner{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
String next() throws IOException
{
while(st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws NumberFormatException, IOException{
return Integer.parseInt(next());
}
}
}
|
Java
|
["aabc", "aabcd"]
|
2 seconds
|
["abba", "abcba"]
| null |
Java 8
|
standard input
|
[
"constructive algorithms",
"greedy",
"strings"
] |
f996224809df700265d940b12622016f
|
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
| 1,800 |
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
|
standard output
| |
PASSED
|
f3f1b65eb0bd1103c9781de1a7e6c49d
|
train_000.jsonl
|
1448636400
|
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
|
256 megabytes
|
import java.util.*;
public class a{
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String s=in.next();
char[] ar=s.toCharArray();
int[] freq=new int[26];
for(int i=0;i<ar.length;i++) freq[ar[i]-'a']++;
TreeMap<Character,Integer> map=new TreeMap<Character,Integer>();
StringBuffer temp=new StringBuffer();
for(int i=0;i<26;i++){
if(freq[i]/2!=0){
map.put((char)(i+97),(freq[i]/2)*2);
freq[i]=freq[i]%2;
}
if(freq[i]!=0){
temp.append((char)(i+97));
freq[i]=0;
}
}
ar=temp.toString().toCharArray();
if(ar.length%2==1) freq[ar[ar.length/2]-'a']++;
for(int i=0;i<ar.length/2;i++){
ar[ar.length-1-i]=ar[i];
freq[ar[i]-'a']+=2;
}
// System.out.println(Arrays.toString(freq));
for(int i=0;i<26;i++){
if(freq[i]!=0){
char c=(char)(i+97);
map.put(c,map.getOrDefault(c,0)+freq[i]);
}
}
//System.out.println(map);
StringBuffer sb=new StringBuffer();
char mid=' ';
for(Map.Entry<Character,Integer> entry: map.entrySet()){
// System.out.println(entry.getKey()+" "+entry.getValue());
if(entry.getValue()%2==1){
mid=entry.getKey();
}
for(int j=0;j<entry.getValue()/2;j++) sb.append(entry.getKey());
}
StringBuffer rev=new StringBuffer(sb);
rev.reverse();
if(mid!=' ')sb.append(mid);
System.out.print(sb);
System.out.print(rev);
}
}
|
Java
|
["aabc", "aabcd"]
|
2 seconds
|
["abba", "abcba"]
| null |
Java 8
|
standard input
|
[
"constructive algorithms",
"greedy",
"strings"
] |
f996224809df700265d940b12622016f
|
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
| 1,800 |
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
|
standard output
| |
PASSED
|
279d76183656e6c9a6ecec1e27690eb7
|
train_000.jsonl
|
1448636400
|
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
|
256 megabytes
|
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* @author Mohammad Hadi
*/
public class ED2C {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s = in.nextLine();
int[] mark = new int['z' - 'a' + 1];
for (int i = 0; i < s.length(); i++) {
mark[s.charAt(i) - 'a']++;
}
ArrayList<Integer> odd = new ArrayList();
for (int i = 0; i < mark.length; i++) {
if (mark[i] % 2 == 1) {
odd.add(i);
}
}
if (odd.size() % 2 == 1) {
for (int i = 0; i < odd.size() / 2; i++) {
mark[odd.get(i)]++;
mark[odd.get(odd.size() - i - 1)]--;
}
int mid = odd.get(odd.size() / 2);
mark[mid]--;
StringBuilder res = new StringBuilder();
for (int i = 0; i < mark.length; i++) {
for (int j = 0; j < mark[i] / 2; j++) {
res.append((char) (i + 'a'));
}
}
System.out.println(res.toString() + (char)('a' + mid) + res.reverse());
} else {
if (odd.size() > 0) {
for (int i = 0; i < odd.size() / 2; i++) {
mark[odd.get(i)]++;
mark[odd.get(odd.size() - i - 1)]--;
}
}
StringBuilder res = new StringBuilder();
for (int i = 0; i < mark.length; i++) {
for (int j = 0; j < mark[i] / 2; j++) {
res.append((char) (i + 'a'));
}
}
System.out.println(res.toString() + res.reverse());
}
}
}
|
Java
|
["aabc", "aabcd"]
|
2 seconds
|
["abba", "abcba"]
| null |
Java 8
|
standard input
|
[
"constructive algorithms",
"greedy",
"strings"
] |
f996224809df700265d940b12622016f
|
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
| 1,800 |
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
|
standard output
| |
PASSED
|
2926a16b0dd2850424d03d37dc0dd370
|
train_000.jsonl
|
1448636400
|
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
|
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.HashSet;
import java.util.InputMismatchException;
public class Solution123 implements Runnable
{
static final int MAX = 1000000007;
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 Solution123(),"Solution123",1<<26).start();
}
static long[] ans = new long[1000001];
static int[] temp;
static long[][] count = new long[1000001][9];
static int[] freq;
static HashSet<Integer> pw2 = new HashSet();
static ArrayList<Integer> ar[] = new ArrayList[9];
public void run()
{
InputReader sc= new InputReader(System.in);
PrintWriter w= new PrintWriter(System.out);
String s = sc.next();
int[] arr= new int[26];
for(int i = 0;i < s.length();i++){
arr[s.charAt(i)-97]++;
}
int changes = 0;
ArrayList<Integer> ar= new ArrayList();
if(s.length() % 2 == 0){
for(int i = 0;i < 26;i++){
if(arr[i] % 2 != 0){
changes++;
ar.add(i);
}
}
}else{
for(int i = 0;i < 26;i++){
if(arr[i]%2!= 0){
changes++;
ar.add(i);
}
}
changes-=1;
}
changes = changes/2;
for(int i = 0;i < ar.size()/2;i++){
arr[ar.get(i)]++;
arr[ar.get(ar.size()-i-1)]--;
}
StringBuilder st = new StringBuilder();
int index = -1;
for(int i = 0;i < 26;i++){
if(arr[i]%2 == 0){
for(int j = 0;j < arr[i]/2;j++){
st.append((char)(i+97));
}
}else{
for(int j = 0;j < arr[i]/2;j++){
st.append((char)(i+97));
}
index = i;
}
}
if(index != -1){
st.append((char)(index + 97));
}
for(int i = 25;i >= 0;i--){
if(arr[i]%2 == 0){
for(int j = 0;j < arr[i]/2;j++){
st.append((char)(i+97));
}
}else{
for(int j = 0;j < arr[i]/2;j++){
st.append((char)(i+97));
}
}
}
w.println(st.toString());
w.close();
}
static void fun(){
ans[1] = 2;
for(int i = 2;i <= ans.length-1;i++){
ans[i] = (ans[i-1] % MAX + ans[i-1] % MAX - (i/2) + ((i % 2 == 0) ? dpe[(i-2)/2]%MAX : dpo[(i-2)/2]%MAX))%MAX;
}
}
static long[] num = new long[1000001];
static long[] dpo = new long[500001];
static long[] dpe = new long[500001];
static void power(){
dpe[0] = 0;
for(int i = 1;i < num.length;i++){
num[i] = i-1;
if(i == 1){
dpo[0] = (num[i]);
}else if(i == 2){
dpe[1] = num[i];
}else if(i % 2 != 0){
dpo[i/2] = dpo[i/2-1] + num[i];
}else{
dpe[i/2] = dpe[i/2-1] + num[i];
}
}
}
static class Pair{
int a;
int b;
int c;
Pair(int a,int b,int c){
this.a = a;
this.b = b;
this.c = c;
}
}
}
|
Java
|
["aabc", "aabcd"]
|
2 seconds
|
["abba", "abcba"]
| null |
Java 8
|
standard input
|
[
"constructive algorithms",
"greedy",
"strings"
] |
f996224809df700265d940b12622016f
|
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
| 1,800 |
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
|
standard output
| |
PASSED
|
0ab5b77d3aee4b9a48c99d923970d09a
|
train_000.jsonl
|
1448636400
|
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
|
256 megabytes
|
import java.io.IOException;
public class CF600C {
public static void main(String[] args) throws IOException {
int[] cnt = new int[26];
int ch;
int len = 0;
do {
ch = System.in.read();
if (ch >= 'a' && ch <= 'z') {
cnt[ch - 'a']++;
len++;
}
} while (ch != -1 && ch != 10);
int l = 0;
int r = cnt.length - 1;
while (l < r) {
while (l < cnt.length && cnt[l] % 2 == 0) l++;
while (r > 0 && cnt[r] % 2 == 0) r--;
if (l < r) {
cnt[l]++;
cnt[r]--;
l++;
r--;
}
}
StringBuilder sb = new StringBuilder(len);
char middle = 0;
for (int i = 0; i < cnt.length; i++) {
char local = (char) ('a' + i);
if (cnt[i] % 2 == 1) {
middle = local;
cnt[i]--;
}
for (int j = 0; j < cnt[i] / 2; j++) {
sb.append(local);
}
}
if (middle != 0) sb.append(middle);
for (int i = cnt.length -1; i >= 0; i--) {
char local = (char) ('a' + i);
for (int j = 0; j < cnt[i] / 2; j++) {
sb.append(local);
}
}
System.out.println(sb.toString());
}
}
|
Java
|
["aabc", "aabcd"]
|
2 seconds
|
["abba", "abcba"]
| null |
Java 8
|
standard input
|
[
"constructive algorithms",
"greedy",
"strings"
] |
f996224809df700265d940b12622016f
|
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
| 1,800 |
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
|
standard output
| |
PASSED
|
a1af1aec835552668871ab4d5523a61e
|
train_000.jsonl
|
1448636400
|
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
|
256 megabytes
|
//package com.himanshu.practice.aug14.educationalround;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
/**
* Created by himanshubhardwaj on 13/08/18.
*/
public class MakePalindrome {
static char[] string;
static int frequency[] = new int[26];
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
string = br.readLine().toCharArray();
for (char c : string) {
frequency[c - 'a']++;
}
System.out.println(getString());
}
public static String getString() {
LinkedList<Integer> linkedList = new LinkedList<>();
for (int i = 0; i < frequency.length; i++) {
if (frequency[i] % 2 == 1) {
linkedList.addLast(i);
}
}
char ch[] = new char[string.length];
int start = 0;
int end = ch.length - 1;
for (int i = 0; i < frequency.length; i++) {
if (linkedList.size() >= 2 && i == linkedList.peek()) {
linkedList.poll();
frequency[i]++;
frequency[linkedList.getLast()]--;
linkedList.removeLast();
}
while (frequency[i] > 1) {
ch[start] = (char) ('a' + i);
ch[end] = (char) ('a' + i);
frequency[i] = frequency[i] - 2;
start++;
end--;
}
if (start == end && !linkedList.isEmpty()) {
ch[start] = (char) ('a' + linkedList.poll());
}
}
// for (char c : ch) {
// System.out.print(c);
// }
// System.out.println();
return new String(ch);
}
}
|
Java
|
["aabc", "aabcd"]
|
2 seconds
|
["abba", "abcba"]
| null |
Java 8
|
standard input
|
[
"constructive algorithms",
"greedy",
"strings"
] |
f996224809df700265d940b12622016f
|
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
| 1,800 |
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
|
standard output
| |
PASSED
|
f6683f089f52a67dc66e90f3636cf897
|
train_000.jsonl
|
1448636400
|
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
|
256 megabytes
|
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class C600C {
public static void main(String[] args) throws Exception {
new C600C().run();
out.close();
}
void run() throws Exception {
String s = nextToken();
int[] num = new int['z' - 'a' + 1];
for (int i = 0; i < s.length(); ++i) {
++num[s.charAt(i) - 'a'];
}
ArrayList<Character> head = new ArrayList<>();
String middle = "";
int r = num.length - 1;
for (int l = 0; l < num.length; ++l) {
char ch = (char) ('a' + l);
if (num[l] % 2 == 1) {
while (r > l && num[r] % 2 == 0) {
--r;
}
if (l == r) {
middle = "" + ch;
}
++num[l];
--num[r];
}
for (int i = 0; i < num[l] / 2; ++i) {
head.add(ch);
}
}
for (int i = 0; i < head.size(); ++i) {
out.print(head.get(i));
}
out.print(middle);
for (int i = head.size() - 1; i >= 0; --i) {
out.print(head.get(i));
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~ template ~~~~~~~~~~~~~~~~~~~~~~~~~~~
int[] nextIntArray(int n) throws IOException {
int[] res = new int[n];
for (int i = 0; i < n; ++i) {
res[i] = nextInt();
}
return res;
}
int[][] nextIntArray(int nx, int ny) throws IOException {
int[][] res = new int[nx][ny];
for (int i = 0; i < nx; ++i) {
for (int j = 0; j < ny; ++j) {
res[i][j] = nextInt();
}
}
return res;
}
long[] nextLongArray(int n) throws IOException {
long[] res = new long[n];
for (int i = 0; i < n; ++i) {
res[i] = nextLong();
}
return res;
}
long[][] nextLongArray(int nx, int ny) throws IOException {
long[][] res = new long[nx][ny];
for (int i = 0; i < nx; ++i) {
for (int j = 0; j < ny; ++j) {
res[i][j] = nextLong();
}
}
return res;
}
void fill(int[][] arr, int val) {
for (int i = 0; i < arr.length; ++i) {
Arrays.fill(arr[i], val);
}
}
void fill(int[][][] arr, int val) {
for (int i = 0; i < arr.length; ++i) {
fill(arr[i], val);
}
}
int[][] newIntArray(int nx, int ny, int val) {
int[][] res = new int[nx][ny];
fill(res, val);
return res;
}
int[][][] newIntArray(int nx, int ny, int nz, int val) {
int[][][] res = new int[nx][ny][nz];
fill(res, val);
return res;
}
long[][] newLongArray(int nx, int ny, long val) {
long[][] res = new long[nx][ny];
for (int i = 0; i < nx; ++i) {
Arrays.fill(res[i], val);
}
return res;
}
long[][][] newLongArray(int nx, int ny, int nz, long val) {
long[][][] res = new long[nx][ny][nz];
for (int i = 0; i < nx; ++i) {
for (int j = 0; j < ny; ++j) {
Arrays.fill(res[i][j], val);
}
}
return res;
}
<T> ArrayList<T>[] newArrayListArray(int sz) {
ArrayList<T>[] res = new ArrayList[sz];
for (int i = 0; i < sz; ++i) {
res[i] = new ArrayList<>();
}
return res;
}
String nextToken() throws IOException {
while (strTok == null || !strTok.hasMoreTokens()) {
String line = in.readLine();
if (line == null) {
return null;
}
strTok = new StringTokenizer(line);
}
return strTok.nextToken();
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
static StringTokenizer strTok;
final static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
final static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
}
|
Java
|
["aabc", "aabcd"]
|
2 seconds
|
["abba", "abcba"]
| null |
Java 8
|
standard input
|
[
"constructive algorithms",
"greedy",
"strings"
] |
f996224809df700265d940b12622016f
|
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
| 1,800 |
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
|
standard output
| |
PASSED
|
179522f88d8f49d3cbce4c4f2aeb1d6e
|
train_000.jsonl
|
1448636400
|
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
|
256 megabytes
|
import java.io.*;
import java.util.*;
/*
* Heart beats fast
* Colors and promises
* How to be brave
* How can I love when I am afraid to fall...
*/
//read the question correctly (is y a vowel? what are the exact constraints?)
//look out for SPECIAL CASES (n=1?) and overflow (ll vs int?)
public class Main
{
public static void main(String[] args)
{
String a=ns();
int[]co=new int[26];
for(int i=0; i<a.length(); i++)
co[a.charAt(i)-'a']++;
int odd=0;
for(int i=0; i<26; i++)
if(co[i]%2!=0)
odd++;
while(odd>1)
{
for(int i=0; i<26; i++)
if(co[i]%2!=0)
{
co[i]++;
break;
}
for(int i=25; i>=0; i--)
if(co[i]%2!=0)
{
co[i]--;
break;
}
odd=0;
for(int i=0; i<26; i++)
if(co[i]%2!=0)
odd++;
}
StringBuilder ans=new StringBuilder();
for(int i=0; i<26; i++)
ans.append(pr((char)(i+'a')+"",co[i]/2));
if(odd==1)
{
for(int i=0; i<26; i++)
if(co[i]%2!=0)
{
String temp=ans.toString();
p(temp+(char)(i+'a')+ans.reverse());
}
}
else
{
p(ans);
p(ans.reverse());
}
System.out.print(output);
}
////////////////////////////////////
///////////////////////////////////////////
///////////////////////////////////////////
///template from here
static final int mod=1000000007;
static final double eps=1e-8;
static final long inf=100000000000000000L;
static Reader in=new Reader();
static StringBuilder output=new StringBuilder();
static Random rn=new Random();
//output functions////////////////
static void pr(Object a){output.append(a+"\n");}
static void pr(){output.append("\n");}
static void p(Object a){output.append(a);}
static void pra(int[]a){for(int i:a)output.append(i+" ");output.append("\n");}
static void pra(long[]a){for(long i:a)output.append(i+" ");output.append("\n");}
static void pra(String[]a){for(String i:a)output.append(i+" ");output.append("\n");}
static void pra(double[]a){for(double i:a)output.append(i+" ");output.append("\n");}
static void sop(Object a){System.out.println(a);}
static void flush(){System.out.println(output);output=new StringBuilder();}
//////////////////////////////////
//input functions/////////////////
static int ni(){return in.nextInt();}
static long nl(){return Long.parseLong(in.next());}
static String ns(){return in.next();}
static double nd(){return Double.parseDouble(in.next());}
static int[] nia(int n){int a[]=new int[n];for(int i=0; i<n; i++)a[i]=ni();return a;}
static int[] pnia(int n){int a[]=new int[n+1];for(int i=1; i<=n; i++)a[i]=ni();return a;}
static long[] nla(int n){long a[]=new long[n];for(int i=0; i<n; i++)a[i]=nl();return a;}
static String[] nsa(int n){String a[]=new String[n];for(int i=0; i<n; i++)a[i]=ns();return a;}
static double[] nda(int n){double a[]=new double[n];for(int i=0; i<n; i++)a[i]=nd();return a;}
//////////////////////////////////
//some utility functions
static void exit(){System.exit(0);}
static void psort(int[][] a)
{
Arrays.sort(a, new Comparator<int[]>()
{
@Override
public int compare(int[]a,int[]b)
{
if(a[0]>b[0])
return 1;
else if(b[0]>a[0])
return -1;
return 0;
}
});
}
static String pr(String a, long b)
{
String c="";
while(b>0)
{
if(b%2==1)
c=c.concat(a);
a=a.concat(a);
b>>=1;
}
return c;
}
static long powm(long a, long b, long m)
{
long an=1;
long c=a;
while(b>0)
{
if(b%2==1)
an=(an*c)%m;
c=(c*c)%m;
b>>=1;
}
return an;
}
static int gcd(int a, int b)
{
if(b==0)
return a;
else
return gcd(b, a%b);
}
/////////////////////////
static class Reader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public Reader() {
reader = new BufferedReader(new InputStreamReader(System.in), 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 double nextDouble() {
return Double.parseDouble(next());
}
}
}
|
Java
|
["aabc", "aabcd"]
|
2 seconds
|
["abba", "abcba"]
| null |
Java 8
|
standard input
|
[
"constructive algorithms",
"greedy",
"strings"
] |
f996224809df700265d940b12622016f
|
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
| 1,800 |
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
|
standard output
| |
PASSED
|
a9b80484d5aecb33d81c50cdebc46782
|
train_000.jsonl
|
1448636400
|
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
|
256 megabytes
|
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
String[] ar;
StringBuilder sb = new StringBuilder();
//-----------------------------------------------------------------------
char[] a = br.readLine().toCharArray();
int n = a.length;
int[] f = new int[26];
for (int i = 0; i < n; i++) {
f[a[i] - 'a']++;
}
int i = 0, j = 25;
while (i < j) {
if (f[i] % 2 == 1 && f[j] % 2 == 1) {
f[i]++;
f[j]--;
i++;
j--;
} else if (f[i] % 2 == 1) {
j--;
} else {
i++;
}
}
for (int k = 0; k < 26; k++) {
int x = f[k] / 2;
f[k] -= x * 2;
for (int kk = 0; kk < x; kk++) {
sb.append((char) (k + 'a'));
}
}
String ss = rev(sb.toString());
if (f[i] == 1) {
sb.append((char) (i + 'a'));
}
sb.append(ss);
System.out.println(sb);
}
static String rev(String s) {
char[] c = s.toCharArray();
StringBuilder sb = new StringBuilder();
for (int i = c.length - 1; i >= 0; i--) {
sb.append(c[i]);
}
return sb.toString();
}
}
|
Java
|
["aabc", "aabcd"]
|
2 seconds
|
["abba", "abcba"]
| null |
Java 8
|
standard input
|
[
"constructive algorithms",
"greedy",
"strings"
] |
f996224809df700265d940b12622016f
|
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
| 1,800 |
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
|
standard output
| |
PASSED
|
7874e848a89f1be56f4dba12f256ae99
|
train_000.jsonl
|
1448636400
|
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
|
256 megabytes
|
import java.io.*;
import java.math.*;
import java.util.*;
/**
*
* @author Saju
*
*/
public class Main {
private static int dx[] = { 1, 0, -1, 0 };
private static int dy[] = { 0, -1, 0, 1 };
private static final long INF = Long.MAX_VALUE;
private static final int INT_INF = Integer.MAX_VALUE;
private static final long NEG_INF = Long.MIN_VALUE;
private static final int NEG_INT_INF = Integer.MIN_VALUE;
private static final double EPSILON = 1e-10;
private static final long MAX = (long) 1e12;
private static final long MOD = 100000007;
private static final int MAXN = 300005;
private static final int MAXA = 100007;
private static final int MAXLOG = 22;
private static final double PI = Math.acos(-1);
public static void main(String[] args) throws IOException {
InputReader in = new InputReader(System.in);
// Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
// InputReader in = new InputReader(new FileInputStream("src/test.in"));
// PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("src/test.out")));
/*
*/
char[] ch = in.next().toCharArray();
int n = ch.length;
int[] cnt = new int[26];
for(int i = 0; i < n; i++) {
int a = ch[i] - 'a';
cnt[a]++;
}
int odd = 0;
List<Integer> odds = new ArrayList<>();
for(int i = 0; i < cnt.length; i++) {
if(cnt[i] % 2 == 1) {
odd++;
odds.add(i);
}
}
// for(int e : odds) {
// System.out.println(e);
// }
for (int i = 0; i < odd / 2; i++) {
int f = odds.get(i);
int s = odds.get(odd - i - 1);
cnt[f]++;
cnt[s]--;
}
StringBuilder sb1 = new StringBuilder();
for (int i = 0; i < cnt.length; i++) {
if (cnt[i] > 0) {
char ch1 = (char) (i + 'a');
for (int j = 1; j <= cnt[i] / 2; j++) {
sb1.append(ch1);
}
}
if(cnt[i] % 2 == 1) {
cnt[i] = 1;
}
}
String str = sb1.toString();
String str1 = sb1.reverse().toString();
sb1 = new StringBuilder();
if(n % 2 == 1) {
for(int i = 0; i < cnt.length; i++) {
if(cnt[i] % 2 == 1) {
char ch1 = (char)(i + 'a');
for(int j = 0; j < cnt[i]; j++) {
sb1.append(ch1);
}
}
}
}
String ans = str + "" + sb1.toString() + "" + str1;
out.println(ans);
in.close();
out.flush();
out.close();
System.exit(0);
}
/*
* return the number of elements in list that are less than or equal to the val
*/
private static long upperBound(List<Long> list, long val) {
int start = 0;
int len = list.size();
int end = len - 1;
int mid = 0;
while (true) {
if (start > end) {
break;
}
mid = (start + end) / 2;
long v = list.get(mid);
if (v == val) {
start = mid;
while(start < end) {
mid = (start + end) / 2;
if(list.get(mid) == val) {
if(mid + 1 < len && list.get(mid + 1) == val) {
start = mid + 1;
}
else {
return mid + 1;
}
}
else {
end = mid - 1;
}
}
return start + 1;
}
if (v > val) {
end = mid - 1;
} else {
start = mid + 1;
}
}
if (list.get(mid) < val) {
return mid + 1;
}
return mid;
}
private static boolean isPalindrome(String str) {
StringBuilder sb = new StringBuilder();
sb.append(str);
String str1 = sb.reverse().toString();
return str.equals(str1);
}
private static String getBinaryStr(long n, int j) {
String str = Long.toBinaryString(n);
int k = str.length();
for (int i = 1; i <= j - k; i++) {
str = "0" + str;
}
return str;
}
private static long modInverse(long r) {
return bigMod(r, MOD - 2, MOD);
}
private static long bigMod(long n, long k, long m) {
long ans = 1;
while (k > 0) {
if ((k & 1) == 1) {
ans = (ans * n) % m;
}
n = (n * n) % m;
k >>= 1;
}
return ans;
}
private static long ceil(long n, long x) {
long div = n / x;
if(div * x != n) {
div++;
}
return div;
}
private static int ceil(int n, int x) {
int div = n / x;
if(div * x != n) {
div++;
}
return div;
}
private static int abs(int x) {
if (x < 0) {
return -x;
}
return x;
}
private static double abs(double x) {
if (x < 0) {
return -x;
}
return x;
}
private static long abs(long x) {
if(x < 0) {
return -x;
}
return x;
}
private static int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
private static int gcd(int a, int b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
private static long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
private static int log(long x, int base) {
return (int) (Math.log(x) / Math.log(base));
}
private static long min(long a, long b) {
if (a < b) {
return a;
}
return b;
}
private static int min(int a, int b) {
if (a < b) {
return a;
}
return b;
}
private static long max(long a, long b) {
if (a < b) {
return b;
}
return a;
}
private static int max(int a, int b) {
if (a < b) {
return b;
}
return a;
}
private static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
try {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
} catch (IOException e) {
return null;
}
return tokenizer.nextToken();
}
public String nextLine() {
String line = null;
try {
tokenizer = null;
line = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return line;
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public boolean hasNext() {
try {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
} catch (Exception e) {
return false;
}
return true;
}
public int[] nextIntArr(int n) {
int arr[] = new int[n];
for(int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArr(int n) {
long arr[] = new long[n];
for(int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
public int[] nextIntArr1(int n) {
int arr[] = new int[n + 1];
for(int i = 1; i <= n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArr1(int n) {
long arr[] = new long[n + 1];
for(int i = 1; i <= n; i++) {
arr[i] = nextLong();
}
return arr;
}
public void close() {
try {
if(reader != null) {
reader.close();
}
}
catch(Exception e) {
}
}
}
}
|
Java
|
["aabc", "aabcd"]
|
2 seconds
|
["abba", "abcba"]
| null |
Java 8
|
standard input
|
[
"constructive algorithms",
"greedy",
"strings"
] |
f996224809df700265d940b12622016f
|
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
| 1,800 |
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
|
standard output
| |
PASSED
|
06029aef711c34f0a14e40168c44304e
|
train_000.jsonl
|
1448636400
|
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
|
256 megabytes
|
import java.io.*;
import java.util.StringTokenizer;
@SuppressWarnings("WeakerAccess")
public class Main {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
public static void main(String[] args) {
new Main().run();
}
void init() throws FileNotFoundException {
if (ONLINE_JUDGE) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
public void run() {
try {
long t1 = System.currentTimeMillis();
init();
solve();
out.close();
long t2 = System.currentTimeMillis();
System.err.println("Time = " + (t2 - t1));
} catch (Exception e) {
e.printStackTrace(System.err);
System.exit(-1);
}
}
public void solve() throws IOException {
String line = readString();
int n = line.length();
char[] answer = line.toCharArray();
char[] c = new char['z' + 1];
for (int i = 0; i < n; i++) {
c[line.charAt(i)]++;
}
char left = 'a';
char right = 'z';
while (left < right) {
if (c[left] % 2 != 0) {
if (c[right] % 2 != 0) {
c[left]++;
c[right]--;
left++;
}
right--;
}else{
left++;
}
}
if (n % 2 != 0) {
answer[n / 2] = left;
}
char j = 'a';
int i = 0;
while (j <='z' && i < n/2) {
if (c[j] > 1) {
answer[i] = j;
answer[n - i - 1] = j;
c[j]-=2;
i++;
}else{
j++;
}
}
out.println(answer);
}
}
|
Java
|
["aabc", "aabcd"]
|
2 seconds
|
["abba", "abcba"]
| null |
Java 8
|
standard input
|
[
"constructive algorithms",
"greedy",
"strings"
] |
f996224809df700265d940b12622016f
|
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
| 1,800 |
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
|
standard output
| |
PASSED
|
a4a65bfaa4eacc66d8749da5bcd5dfc3
|
train_000.jsonl
|
1448636400
|
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
|
256 megabytes
|
import java.util.Arrays;
import java.io.*;
import java.util.*;
public class Queries {
public static void main(String args[]) {
MyScanner in = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
String line = in.nextLine();
char[] arr = makePali(line);
System.out.println(new String(arr));
out.close();
}
static char[] makePali(String line) {
int[] arr = new int[26];
for (char cur : line.toCharArray()) {
arr[cur - 'a']++;
}
int back = 25;
int front = 0;
while (back > front) {
while (arr[back] % 2 != 1 && back > front) {
back--;
}
while (arr[front] % 2 != 1 && back > front) {
front++;
}
arr[back]--;
arr[front]++;
}
char[] value = new char[line.length()];
front = 0;
boolean odd = line.length() % 2 == 1;
int len = line.length() - 1;
if (!odd) {
for (int i = 0; i <= len / 2; i++) {
while (arr[front] <= 1) {
front++;
}
value[i] = (char) (front + 'a');
value[len - i] = (char) (front + 'a');
arr[front] -= 2;
}
return value;
} else {
char x = 'a';
for (int i = 0; i < 26; i++) {
if (arr[i] % 2 == 1) {
x = (char) (i + 'a');
break;
}
}
for (int i = 0; i < len / 2; i++) {
while (arr[front] <= 1) {
front++;
}
value[i] = (char) (front + 'a');
value[len - i] = (char) (front + 'a');
arr[front] -= 2;
}
value[len / 2] = x;
return value;
}
}
static void heapSort(int[] arr) {
makeHeap(arr);
int len = arr.length - 1;
int max;
for (int i = 0; i < arr.length; i++) {
max = arr[0];
arr[0] = arr[len];
arr[len] = max;
len--;
bubbleDown(arr, 0, len);
}
}
static void makeHeap(int[] arr) {
for (int i = arr.length - 1; i >= 0; i--) {
bubbleDown(arr, i, arr.length - 1);
}
}
static void bubbleDown(int[] arr, int pos, int len) {
if (pos * 2 + 1 > len) {
return;
}
int cur = arr[pos];
int leftChild = arr[pos * 2 + 1];
int rightChild = (pos * 2 + 2) > len ? Integer.MIN_VALUE : arr[pos * 2 + 2];
int max = Math.max(Math.max(cur, leftChild), rightChild);
if (max == leftChild) {
arr[pos] = leftChild;
arr[pos * 2 + 1] = cur;
bubbleDown(arr, pos * 2 + 1, len);
} else if (max == rightChild) {
arr[pos] = rightChild;
arr[pos * 2 + 2] = cur;
bubbleDown(arr, pos * 2 + 2, len);
}
}
public static PrintWriter out;
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["aabc", "aabcd"]
|
2 seconds
|
["abba", "abcba"]
| null |
Java 8
|
standard input
|
[
"constructive algorithms",
"greedy",
"strings"
] |
f996224809df700265d940b12622016f
|
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
| 1,800 |
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
|
standard output
| |
PASSED
|
54bc4d52068ceec46e6855019ee1fa6d
|
train_000.jsonl
|
1448636400
|
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class CodeForces
{
static InputStreamReader isr = new InputStreamReader(System.in);
static BufferedReader br = new BufferedReader(isr);
// static PrintWriter pt = new PrintWriter(System.out);
public static void main(String[] args) throws IOException
{
// Scanner in = new Scanner(System.in);
String s = br.readLine();
int len = s.length();
int[] letters = new int[26];
for(int i=0 ; i<len ; i++){
letters[s.charAt(i)-'a']++;
}
if(Is_palindrome(letters) == 1){
print_string(letters , len );
return ;
}
for(int i=0 ; i<26 ; i++){
if(letters[i] % 2 == 1){
letters[i]++ ;
for(int j = 25 ; j>= 0 ; j--){
if(letters[j] % 2 == 1){
letters[j] -- ;
break ;
}
}
if(Is_palindrome(letters) == 1){
print_string(letters , len );
return ;
}
}
}
}
public static int Is_palindrome(int[] chars) {
int flag = 0 ;
for(int i=0 ; i<26 ; i++){
if(chars[i]%2 == 1) flag ++;
}
return (flag < 2) ? 1 : 0 ;
}
public static void print_string(int[] chars , int len){
char[] word = new char[len];
int index = 0 ;
for(int i=0 ; i<26 ; i++){
if(chars[i] % 2 == 1){
word[len/2] = (char)('a' + i) ;
chars[i] -- ;
}
while(chars[i] != 0){
word[index] = (char)('a' + i) ;
word[len-1-index] = (char)('a' + i) ;
index ++ ;
chars[i] -= 2 ;
}
}
System.out.println(new String(word));
}
}
|
Java
|
["aabc", "aabcd"]
|
2 seconds
|
["abba", "abcba"]
| null |
Java 8
|
standard input
|
[
"constructive algorithms",
"greedy",
"strings"
] |
f996224809df700265d940b12622016f
|
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
| 1,800 |
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
|
standard output
| |
PASSED
|
d102bca31f095c9b73ae3dc10a483fe9
|
train_000.jsonl
|
1448636400
|
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class C
{
static InputStreamReader isr = new InputStreamReader(System.in);
static BufferedReader br = new BufferedReader(isr);
// static PrintWriter pt = new PrintWriter(System.out);
public static void main(String[] args) throws IOException
{
// Scanner in = new Scanner(System.in);
String s = br.readLine();
int len = s.length();
int[] letters = new int[26];
for(int i=0 ; i<len ; i++){
letters[s.charAt(i)-'a']++;
}
if(Is_palindrome(letters) == 1){
print_string(letters , len );
return ;
}
for(int i=0 ; i<26 ; i++){
if(letters[i] % 2 == 1){
letters[i]++ ;
for(int j = 25 ; j>= 0 ; j--){
if(letters[j] % 2 == 1){
letters[j] -- ;
break ;
}
}
if(Is_palindrome(letters) == 1){
print_string(letters , len );
return ;
}
}
}
}
public static int Is_palindrome(int[] chars) {
int flag = 0 ;
for(int i=0 ; i<26 ; i++){
if(chars[i]%2 == 1) flag ++;
}
return (flag < 2) ? 1 : 0 ;
}
public static void print_string(int[] chars , int len){
char[] word = new char[len];
int index = 0 ;
for(int i=0 ; i<26 ; i++){
if(chars[i] % 2 == 1){
word[len/2] = (char)('a' + i) ;
chars[i] -- ;
}
while(chars[i] != 0){
word[index] = (char)('a' + i) ;
word[len-1-index] = (char)('a' + i) ;
index ++ ;
chars[i] -= 2 ;
}
}
System.out.println(new String(word));
}
}
|
Java
|
["aabc", "aabcd"]
|
2 seconds
|
["abba", "abcba"]
| null |
Java 8
|
standard input
|
[
"constructive algorithms",
"greedy",
"strings"
] |
f996224809df700265d940b12622016f
|
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
| 1,800 |
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
|
standard output
| |
PASSED
|
39af325d32205157e0532a096ab745d8
|
train_000.jsonl
|
1448636400
|
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main
{
public static void main (String[] args) {
/* code */
Scanner scan = new Scanner(System.in);
String s = scan.next();
int arr[] = new int[26];
for(int i=0;i<s.length();i++)
{
arr[s.charAt(i)-'a']++;
}
int i=0, j=25;
while(i<j)
{
while(arr[i]%2==0 && i<j)
{
i++;
}
while(arr[j]%2==0 && j>i)
{
j--;
}
arr[i]++;
arr[j]--;
}
// System.out.println(Arrays.toString(arr));
char ch = 'a';
for(i=0;i<26;i++)
{
if(arr[i]%2!=0)
{
ch = (char)(i+'a');
arr[i]--;
break;
}
}
for(i=0;i<26;i++)
{
int x = arr[i]/2;
while(arr[i]!=x)
{
System.out.print((char)(i+'a'));
arr[i]--;
}
}
if(s.length()%2!=0)
{
System.out.print(ch);
}
for(i=25;i>=0;i--)
{
while(arr[i]--!=0)
{
System.out.print((char)(i+'a'));
}
}
}
}
|
Java
|
["aabc", "aabcd"]
|
2 seconds
|
["abba", "abcba"]
| null |
Java 8
|
standard input
|
[
"constructive algorithms",
"greedy",
"strings"
] |
f996224809df700265d940b12622016f
|
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
| 1,800 |
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
|
standard output
| |
PASSED
|
f9736240f4150f2b302d979e1d6b5bd0
|
train_000.jsonl
|
1448636400
|
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
public class Solution{
public static void main(String[] args) throws IOException {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int tt = 1;
while(tt-->0) {
char[] s = fs.next().toCharArray();
int n = s.length;
StringBuilder ans = new StringBuilder("");
int[] cnt = new int[26];
for(int i=0;i<n;i++) {
cnt[s[i]-'a']++;
}
int nodd = 0;
for(int i=0;i<26;i++) if(cnt[i]%2!=0) nodd++;
char pal = '\u0000';
boolean isodd = false;
if(nodd%2!=0) isodd = true;
int num = 1;
for(int i=0;i<26;i++) {
if(cnt[i]%2==0) add(ans, (char)(i+'a'), cnt[i]/2);
else {
if(num<=nodd/2) {
add(ans, (char)(i+'a'), (cnt[i]+1)/2);
}
else {
add(ans, (char)(i+'a'), cnt[i]/2);
}
if(isodd && num==(nodd+1)/2) pal = (char)(i+'a');
num++;
}
}
out.print(ans.toString());
if(isodd) out.print(pal);
out.println(ans.reverse().toString());
}
out.close();
}
static void add(StringBuilder str, char ch, int t) {
while(t-->0) str.append(ch);
}
static final Random random=new Random();
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n); int temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static class FastScanner{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String next(){
while(!st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
} catch(IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt(){
return Integer.parseInt(next());
}
public int[] readArray(int n){
int[] a = new int[n];
for(int i=0;i<n;i++)
a[i] = nextInt();
return a;
}
public long nextLong() {
return Long.parseLong(next());
}
public char nextChar() {
return next().toCharArray()[0];
}
}
}
|
Java
|
["aabc", "aabcd"]
|
2 seconds
|
["abba", "abcba"]
| null |
Java 8
|
standard input
|
[
"constructive algorithms",
"greedy",
"strings"
] |
f996224809df700265d940b12622016f
|
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
| 1,800 |
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
|
standard output
| |
PASSED
|
9f7a54b6cfc75d3abbee784f47048bac
|
train_000.jsonl
|
1448636400
|
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
|
256 megabytes
|
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.TreeSet;
/**
* Created by tignatchenko on 15.10.2015.
*/
public class Z1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
char[] cs = sc.next().toCharArray();
int[] cnt = new int[200];
int n = cs.length;
int k = 0;
for (int i = 0; i<cs.length; i++) {
cnt[cs[i]]++;
}
for (int i = 0; i<cnt.length; i++) {
while (cnt[i] > 1) {
cs[k] = (char)i;
cs[n-k-1] = (char)i;
cnt[i]-=2;
k++;
}
}
for (int i = 0; i<cnt.length; i++) {
if (cnt[i]==1) {
cs[k] = (char)i;
k++;
}
}
/*for (int i = 0; i<n; i++) {
System.out.print(cs[i]);
}
System.out.println();*/
k = n/2;
char[] half = new char[k];
for (int i = 0; i<k; i++) {
half[i] = cs[i];
}
Arrays.sort(half);
for (int i = 0; i<k; i++) {
cs[i] = half[i];
}
int j = k;
if (n%2==1) {
j++;
}
for (int i = k-1; i>=0; i--) {
cs[j++] = half[i];
}
/*for (int i = 0; i<k; i++) {
char f = cs[i];
char l = cs[n-1-i];
if (f!=l) {
int min = Math.min(f, l);
cs[i] = (char)min;
cs[n-1-i] = (char)min;
}
}*/
for (int i = 0; i<n; i++) {
pw.print(cs[i]);
}
pw.close();
}
}
|
Java
|
["aabc", "aabcd"]
|
2 seconds
|
["abba", "abcba"]
| null |
Java 8
|
standard input
|
[
"constructive algorithms",
"greedy",
"strings"
] |
f996224809df700265d940b12622016f
|
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
| 1,800 |
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
|
standard output
| |
PASSED
|
3611ce8d7eddb3a4aedad88652470a6a
|
train_000.jsonl
|
1448636400
|
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
|
256 megabytes
|
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.List;
public class _v30{
public static void main(String args[]){
PrintWriter out = new PrintWriter(System.out);
Reader in = new Reader();
char ch[] = in.next().toCharArray();
int a[] = new int[26];
for(int i=0;i<ch.length;i++){
a[ch[i]-97]++;
}
List<Integer> lis = new ArrayList<>();
for(int i=0;i<26;i++){
if(a[i]%2 != 0){
lis.add(i);
}
}
int limit = 0;
for(int i=lis.size()-1;i>=limit;i--){
int index = lis.get(i);
//System.out.println(index);
a[index]--;
int top = lis.get(limit);
a[top]++;
limit++;
}
char odd = ' ';
StringBuilder sb = new StringBuilder();
for(int i=0;i<26;i++){
if(a[i]%2 == 1){
odd = (char)(i+97);
a[i]--;
}
for(int j=0;j<a[i]/2;j++){
sb.append((char)(i+97));
}
}
if(odd==' ')
out.println(sb+""+sb.reverse());
else
out.println(sb+""+odd+""+sb.reverse());
out.flush();
out.close();
}
static class Reader {
private InputStream mIs;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public Reader() {
this(System.in);
}
public Reader(InputStream is) {
mIs = is;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = mIs.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String next() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
double nextDouble()
{
return Double.parseDouble(next());
}
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 boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
}
|
Java
|
["aabc", "aabcd"]
|
2 seconds
|
["abba", "abcba"]
| null |
Java 8
|
standard input
|
[
"constructive algorithms",
"greedy",
"strings"
] |
f996224809df700265d940b12622016f
|
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
| 1,800 |
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
|
standard output
| |
PASSED
|
49d23f893899d4e73034923db3fc20cd
|
train_000.jsonl
|
1539511500
|
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
|
512 megabytes
|
import java.util.*;
import java.io.*;
public class Main {
static class Four{
int x , y , r , l ;
public Four(int x , int y , int l , int r) {
this.x = x;
this.y = y;
this.l = l;
this.r = r;
}
}
public static int mod = 1000000007;
public static void solve(InputReader in) {
int n = in.readInt();
int m = in.readInt();
int r = in.readInt() - 1;
int c = in.readInt() - 1;
int L = in.readInt();
int R = in.readInt();
char[][] maze = new char[n][m];
for (int i = 0; i < n; maze[i++] = in.next().toCharArray());
Deque<Four> deque = new ArrayDeque<>();
deque.add(new Four(r, c, 0, 0));
boolean[][] used = new boolean[n][m];
int reachable = 0;
while (!deque.isEmpty()) {
Four four = deque.poll();
if (four.x == -1 || four.x == n || four.y == -1 || four.y == m || four.l > L || four.r > R ||
maze[four.x][four.y] == '*' || used[four.x][four.y]) {
continue;
}
used[four.x][four.y] = true;
reachable++;
deque.addFirst(new Four(four.x - 1, four.y, four.l, four.r));
deque.addFirst(new Four(four.x + 1, four.y, four.l, four.r));
deque.addLast(new Four(four.x, four.y - 1, four.l + 1, four.r));
deque.addLast(new Four(four.x, four.y + 1, four.l, four.r + 1));
}
System.out.println(reachable);
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
int t = 1;
while (t-- > 0)
solve(in);
}
}
class InputReader{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long readLong() {
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 c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
|
Java
|
["4 5\n3 2\n1 2\n.....\n.***.\n...**\n*....", "4 4\n2 2\n0 1\n....\n..*.\n....\n...."]
|
2 seconds
|
["10", "7"]
|
NoteCells, reachable in the corresponding example, are marked with '+'.First example: +++..+***.+++***+++. Second example: .++..+*..++..++.
|
Java 8
|
standard input
|
[
"shortest paths",
"graphs"
] |
cfdbe4bd1c9438de2d871768c546a580
|
The first line contains two integers n, m (1 ≤ n, m ≤ 2000) — the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0 ≤ x, y ≤ 109) — the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles.
| 1,800 |
Print exactly one integer — the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.
|
standard output
| |
PASSED
|
9da0bfe8ac8a6c86cd888d2614f0c430
|
train_000.jsonl
|
1539511500
|
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
|
512 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
/**
* Created by Moi on 14-10-18.
*/
public class D {
static int n, m, r, c, x, y;
static boolean osbtacle[][];
static boolean vis[][];
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(bf.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
st = new StringTokenizer(bf.readLine());
r = Integer.parseInt(st.nextToken());
c = Integer.parseInt(st.nextToken());
st = new StringTokenizer(bf.readLine());
x = Integer.parseInt(st.nextToken());
y = Integer.parseInt(st.nextToken());
osbtacle = new boolean[n][m];
vis = new boolean[n][m];
for (int i = 0; i < n; i++) {
char str[] = bf.readLine().toCharArray();
for (int j = 0; j < m; j++) {
osbtacle[i][j] = (str[j] == '*');
}
}
Queue<Node> queue = new LinkedList<Node>();
queue.add(new Node(r-1,c-1, 0, 0));
while(!queue.isEmpty()) {
// System.out.println(queue.size());
Node n2 = queue.poll();
if (!vis[n2.x][n2.y]) {
// System.out.println(n2.x + " " + n2.y);
vis[n2.x][n2.y] = true;
int xx = n2.x;
while (xx < n && !osbtacle[xx][n2.y]) {
vis[xx][n2.y] = true;
if (n2.y > 0 && n2.ll < x && !osbtacle[xx][n2.y - 1]) {
queue.add(new Node(xx, n2.y - 1, n2.ll + 1, n2.lr));
}
if (n2.y < m - 1 && n2.lr < y && !osbtacle[xx][n2.y + 1]) {
queue.add(new Node(xx, n2.y + 1, n2.ll, n2.lr + 1));
}
xx++;
}
xx = n2.x - 1;
while (xx >= 0 && !osbtacle[xx][n2.y]) {
vis[xx][n2.y] = true;
if (n2.y > 0 && n2.ll < x && !osbtacle[xx][n2.y - 1]) {
queue.add(new Node(xx, n2.y - 1, n2.ll + 1, n2.lr));
}
if (n2.y < m - 1 && n2.lr < y && !osbtacle[xx][n2.y + 1]) {
queue.add(new Node(xx, n2.y + 1, n2.ll, n2.lr + 1));
}
xx--;
}
}
}
int reachable = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (vis[i][j]) {
reachable++;
}
}
}
System.out.println(reachable);
}
static class Node {
int x, y;
int ll, lr;
public Node(int x, int y, int ll, int lr) {
this.x = x;
this.y = y;
this.ll = ll;
this.lr = lr;
}
}
}
|
Java
|
["4 5\n3 2\n1 2\n.....\n.***.\n...**\n*....", "4 4\n2 2\n0 1\n....\n..*.\n....\n...."]
|
2 seconds
|
["10", "7"]
|
NoteCells, reachable in the corresponding example, are marked with '+'.First example: +++..+***.+++***+++. Second example: .++..+*..++..++.
|
Java 8
|
standard input
|
[
"shortest paths",
"graphs"
] |
cfdbe4bd1c9438de2d871768c546a580
|
The first line contains two integers n, m (1 ≤ n, m ≤ 2000) — the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0 ≤ x, y ≤ 109) — the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles.
| 1,800 |
Print exactly one integer — the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.
|
standard output
| |
PASSED
|
e3ed3e816792056d3fbe4060b47edcd5
|
train_000.jsonl
|
1539511500
|
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
|
512 megabytes
|
import java.util.*;
public class ProblemD {
static class Point {
int x = 0;
int y = 0;
int l = 0;
int r = 0;
public Point(int x, int y, int l, int r) {
this.x = x;
this.y = y;
this.l = l;
this.r = r;
}
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int r = sc.nextInt() - 1;
int c = sc.nextInt() - 1;
int ix = sc.nextInt();
int iy = sc.nextInt();
boolean[][] visited = new boolean[n][m];
for(int i=0;i<n;i++) {
String s = sc.next();
for(int j=0;j<s.length();j++) {
if(s.charAt(j) == '*') {
visited[i][j] = true;
}
}
}
PriorityQueue<Point> q = new PriorityQueue<>(new Comparator<Point>() {
@Override
public int compare(Point o1, Point o2) {
return (o2.l + o2.r) - (o1.l + o1.r);
}
});
q.add(new Point(r, c, ix, iy));
visited[r][c] = true;
int count = 0;
while(!q.isEmpty()) {
Point p = q.remove();
count = count + 1;
if(p.x > 0 && !visited[p.x-1][p.y]) {
visited[p.x-1][p.y] = true;
q.add(new Point(p.x-1, p.y, p.l, p.r));
}
if(p.x < n - 1 && !visited[p.x+1][p.y]) {
visited[p.x+1][p.y] = true;
q.add(new Point(p.x + 1, p.y, p.l, p.r));
}
if(p.l > 0 && p.y > 0 && !visited[p.x][p.y-1]) {
visited[p.x][p.y-1] = true;
q.add(new Point(p.x, p.y -1, p.l - 1, p.r));
}
if(p.r > 0 && p.y < m-1 && !visited[p.x][p.y+1]) {
visited[p.x][p.y+1] = true;
q.add(new Point(p.x, p.y + 1, p.l, p.r - 1));
}
}
System.out.println(count);
}
}
|
Java
|
["4 5\n3 2\n1 2\n.....\n.***.\n...**\n*....", "4 4\n2 2\n0 1\n....\n..*.\n....\n...."]
|
2 seconds
|
["10", "7"]
|
NoteCells, reachable in the corresponding example, are marked with '+'.First example: +++..+***.+++***+++. Second example: .++..+*..++..++.
|
Java 8
|
standard input
|
[
"shortest paths",
"graphs"
] |
cfdbe4bd1c9438de2d871768c546a580
|
The first line contains two integers n, m (1 ≤ n, m ≤ 2000) — the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0 ≤ x, y ≤ 109) — the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles.
| 1,800 |
Print exactly one integer — the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.
|
standard output
| |
PASSED
|
0f93fa21c48b249b292d908964cba9bf
|
train_000.jsonl
|
1539511500
|
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
|
512 megabytes
|
//Labyrinth
//iterative bfs
import java.io.*;
import java.util.*;
public class B1063b{
public static int n,m,xi,yi,left,right;
public static char[][] board;
public static boolean[][] used;
public static int[][] movesl,movesr;
public static void main(String[] args)throws IOException{
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
StringTokenizer st = new StringTokenizer(f.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
st = new StringTokenizer(f.readLine());
xi = Integer.parseInt(st.nextToken());
yi = Integer.parseInt(st.nextToken());
st = new StringTokenizer(f.readLine());
left = Integer.parseInt(st.nextToken());
right = Integer.parseInt(st.nextToken());
board = new char[n][m];
String s;
for(int k = 0; k < n; k++){
s = f.readLine();
for(int j = 0; j < m; j++){
board[k][j] = s.charAt(j);
}
}
used = new boolean[n][m];
movesl = new int[n][m];
movesr = new int[n][m];
PriorityQueue<State> q = new PriorityQueue<State>();
q.add(new State(xi-1,yi-1,0,0));
int x,y,l,r;
int answer = 0;
used[xi-1][yi-1] = true;
while(!q.isEmpty()){
State cur = q.poll();
x = cur.x;
y = cur.y;
l = cur.l;
r = cur.r;
answer++;
//System.out.println(x + " " + y);
if(in(x-1,y) && !used[x-1][y] && board[x-1][y] != '*'){
q.add(new State(x-1,y,l,r));
used[x-1][y] = true;
}
if(in(x+1,y) && !used[x+1][y] && board[x+1][y] != '*'){
q.add(new State(x+1,y,l,r));
used[x+1][y] = true;
}
if(in(x,y-1) && !used[x][y-1] && board[x][y-1] != '*' && l < left){
q.add(new State(x,y-1,l+1,r));
used[x][y-1] = true;
}
if(in(x,y+1) && !used[x][y+1] && board[x][y+1] != '*' && r < right){
q.add(new State(x,y+1,l,r+1));
used[x][y+1] = true;
}
}
out.println(answer);
out.close();
}
public static class State implements Comparable<State>{
int x;
int y;
int l;
int r;
public State(int a, int b, int c, int d){
x = a;
y = b;
l = c;
r = d;
}
public int compareTo(State s){
return l+r-s.l-s.r;
}
}
public static boolean in(int a, int b){
return a >= 0 && b >= 0 && a < n && b < m;
}
}
|
Java
|
["4 5\n3 2\n1 2\n.....\n.***.\n...**\n*....", "4 4\n2 2\n0 1\n....\n..*.\n....\n...."]
|
2 seconds
|
["10", "7"]
|
NoteCells, reachable in the corresponding example, are marked with '+'.First example: +++..+***.+++***+++. Second example: .++..+*..++..++.
|
Java 8
|
standard input
|
[
"shortest paths",
"graphs"
] |
cfdbe4bd1c9438de2d871768c546a580
|
The first line contains two integers n, m (1 ≤ n, m ≤ 2000) — the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0 ≤ x, y ≤ 109) — the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles.
| 1,800 |
Print exactly one integer — the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.
|
standard output
| |
PASSED
|
3ef929becd8bab72b28ad4320bc52dcb
|
train_000.jsonl
|
1539511500
|
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
|
512 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.AbstractCollection;
import java.util.Scanner;
import java.util.LinkedList;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author xwchen
*/
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int r = in.nextInt();
int c = in.nextInt();
int x = in.nextInt();
int y = in.nextInt();
char[][] s = new char[n][m];
for (int i = 0; i < n; ++i) {
s[i] = in.next().toCharArray();
}
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, 1, -1};
LinkedList<Integer> q = new LinkedList<Integer>();
q.addLast(r - 1);
q.addLast(c - 1);
q.addLast(x);
q.addLast(y);
int res = 1;
s[r - 1][c - 1] = '+';
while (!q.isEmpty()) {
int cx = q.getFirst();
q.pollFirst();
int cy = q.getFirst();
q.pollFirst();
int cleft = q.getFirst();
q.pollFirst();
int cright = q.getFirst();
q.pollFirst();
//out.println(String.format("%d %d %d %d",cx,cy,cleft,cright));
for (int k = 0; k < 2; ++k) {
int nx = cx + dx[k];
int ny = cy + dy[k];
if (nx >= 0 && nx < n && ny >= 0 && ny < m && s[nx][ny] == '.') {
s[nx][ny] = '+';
res++;
q.addFirst(cright);
q.addFirst(cleft);
q.addFirst(ny);
q.addFirst(nx);
}
}
if (cright > 0) {
int nx = cx;
int ny = cy + 1;
if (nx >= 0 && nx < n && ny >= 0 && ny < m && s[nx][ny] == '.') {
s[nx][ny] = '+';
res++;
q.addLast(nx);
q.addLast(ny);
q.addLast(cleft);
q.addLast(cright - 1);
}
}
if (cleft > 0) {
int nx = cx;
int ny = cy - 1;
if (nx >= 0 && nx < n && ny >= 0 && ny < m && s[nx][ny] == '.') {
s[nx][ny] = '+';
res++;
q.addLast(nx);
q.addLast(ny);
q.addLast(cleft - 1);
q.addLast(cright);
}
}
}
//for(int i=0;i<n;++i){out.println(s[i]);}
out.println(res);
}
}
}
|
Java
|
["4 5\n3 2\n1 2\n.....\n.***.\n...**\n*....", "4 4\n2 2\n0 1\n....\n..*.\n....\n...."]
|
2 seconds
|
["10", "7"]
|
NoteCells, reachable in the corresponding example, are marked with '+'.First example: +++..+***.+++***+++. Second example: .++..+*..++..++.
|
Java 8
|
standard input
|
[
"shortest paths",
"graphs"
] |
cfdbe4bd1c9438de2d871768c546a580
|
The first line contains two integers n, m (1 ≤ n, m ≤ 2000) — the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0 ≤ x, y ≤ 109) — the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles.
| 1,800 |
Print exactly one integer — the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.
|
standard output
| |
PASSED
|
04fbd5defc2c2162ae90e683d8a362b3
|
train_000.jsonl
|
1539511500
|
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
|
512 megabytes
|
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class tt_3 {
static Scanner sc;
static int n;
static int m;
static int r;
static int c;
static int max_l;
static int max_r;
static boolean[][] visitedPoints;
static int[][][] leftRightVals;
public static void main(String[] args){
sc = new Scanner(System.in);
n = getInt();
m = getInt();
r = getInt();
c = getInt();
max_l = getInt();
max_r = getInt();
visitedPoints = new boolean[n+2][m+2];
leftRightVals = new int[n+2][m+2][2];
for(int j=0 ; j<=m+1; j++){
visitedPoints[0][j] = true;
leftRightVals[0][j][0] = leftRightVals[0][j][1] = Integer.MAX_VALUE;
visitedPoints[n+1][j] = true;
leftRightVals[n+1][j][0] = leftRightVals[n+1][j][1] = Integer.MAX_VALUE;
}
for(int i=0; i<=n+1; i++){
visitedPoints[i][0] = true;
leftRightVals[i][0][0] = leftRightVals[i][0][1] = Integer.MAX_VALUE;
visitedPoints[i][m+1] = true;
leftRightVals[i][m+1][0] = leftRightVals[i][m+1][1] = Integer.MAX_VALUE;
}
int blocked = 0;
for(int i=1; i<=n; i++){
char[] chars = getString().toCharArray();
for(int j=1; j<=m; j++){
if(chars[j-1]=='*'){
blocked++;
visitedPoints[i][j] = true;
leftRightVals[i][j][0] = leftRightVals[i][j][1] = Integer.MAX_VALUE;
}
}
}
Node node = new Node(r,c,max_l,max_r);
calc(node, new LinkedList<>());
int res = 0;
for(int i=1; i<=n; i++){
for(int j=1; j<=m; j++){
if(!visitedPoints[i][j]){
res++;
}
}
}
System.out.println((n*m)-res-blocked);
}
static class Node{
int row,column,left,right;
public Node(int r, int c, int l, int rr){
row = r;
column = c;
left = l;
right = rr;
}
}
public static void calc(Node n, Queue<Node> stack){
stack.add(n);
while(!stack.isEmpty()){
Node k = stack.poll();
int row = k.row;
int column = k.column;
int left = k.left;
int right = k.right;
if(visitedPoints[row][column] && leftRightVals[row][column][0]>=left && leftRightVals[row][column][1]>=right) {
continue;
}
visitedPoints[row][column] = true;
leftRightVals[row][column][0] = Math.max(left, leftRightVals[row][column][0]);
leftRightVals[row][column][1] = Math.max(right, leftRightVals[row][column][1]);
stack.add(new Node(row-1, column, left, right));
stack.add(new Node(row+1, column, left, right));
if(left>0){
stack.add(new Node(row, column-1, left-1, right));
}
if(right>0){
stack.add(new Node(row, column+1, left, right-1));
}
}
}
public static int getInt(){
return sc.nextInt();
}
public static String getString(){
return sc.next();
}
public static String nextLine(){
return sc.nextLine();
}
}
|
Java
|
["4 5\n3 2\n1 2\n.....\n.***.\n...**\n*....", "4 4\n2 2\n0 1\n....\n..*.\n....\n...."]
|
2 seconds
|
["10", "7"]
|
NoteCells, reachable in the corresponding example, are marked with '+'.First example: +++..+***.+++***+++. Second example: .++..+*..++..++.
|
Java 8
|
standard input
|
[
"shortest paths",
"graphs"
] |
cfdbe4bd1c9438de2d871768c546a580
|
The first line contains two integers n, m (1 ≤ n, m ≤ 2000) — the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0 ≤ x, y ≤ 109) — the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles.
| 1,800 |
Print exactly one integer — the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.
|
standard output
| |
PASSED
|
90af2f462c7ee25cdd09ac3ea9a6d903
|
train_000.jsonl
|
1539511500
|
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
|
512 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Reader.init(System.in);
new Main();
}
Main() throws IOException {
solve();
}
void solve() throws IOException {
PrintWriter out = new PrintWriter(System.out);
int n = Reader.nextInt();
int m = Reader.nextInt();
int r = Reader.nextInt()-1;
int c = Reader.nextInt()-1;
int x = Reader.nextInt();
int y = Reader.nextInt();
boolean[][] free = new boolean[n][m];
for(int i = 0; i < n; i++){
String xx = Reader.next();
for(int j = 0; j < xx.length(); j++){
if(xx.charAt(j) == '.'){free[i][j] = true;}
}
}
int vis[][] = new int[n][m];
boolean vis2[][] = new boolean[n][m];
for(int i = 0; i < n; i++){Arrays.fill(vis[i], Integer.MAX_VALUE);}
Queue<Node> P = new LinkedList<>();
int ans = 0;
P.add(new Node(r,c,0,0));
while(!P.isEmpty()){
Node S = P.remove();
// if(S.x < 0 || S.x >= n || S.y < 0||S.y >= m|| S.lst > x || S.rst > y){continue;}
if(vis[S.x][S.y] <= S.lst || !free[S.x][S.y]) continue;
vis[S.x][S.y] = S.lst;
if(!vis2[S.x][S.y])ans++;
vis2[S.x][S.y] = true;
if(!(S.y+1>= m || S.rst+1 > y)) P.add(new Node(S.x, S.y+1, S.lst, S.rst+1));
if(!(S.y - 1 < 0 ||S.y-1>= m || S.lst+1 > x)) P.add(new Node(S.x , S.y -1, S.lst + 1, S.rst));
if(!(S.x+1 < 0 || S.x+1 >= n )) P.add(new Node(S.x+1, S.y, S.lst, S.rst));
if(!(S.x -1< 0 || S.x-1 >= n )) P.add(new Node(S.x - 1, S.y, S.lst, S.rst));
}
out.println(ans);
out.close();
}
class Node{
int lst;
int rst;
int x;
int y;
Node(int xi, int yi, int l, int r){
lst = l;
rst = r;
x = xi;
y = yi;
}
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
static void init(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
static String nextToken() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException { return Integer.parseInt( next() ); }
static double nextDouble() throws IOException { return Double.parseDouble( next() ); }
static long nextLong() { return Long.parseLong(nextToken()); }
}
|
Java
|
["4 5\n3 2\n1 2\n.....\n.***.\n...**\n*....", "4 4\n2 2\n0 1\n....\n..*.\n....\n...."]
|
2 seconds
|
["10", "7"]
|
NoteCells, reachable in the corresponding example, are marked with '+'.First example: +++..+***.+++***+++. Second example: .++..+*..++..++.
|
Java 8
|
standard input
|
[
"shortest paths",
"graphs"
] |
cfdbe4bd1c9438de2d871768c546a580
|
The first line contains two integers n, m (1 ≤ n, m ≤ 2000) — the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0 ≤ x, y ≤ 109) — the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles.
| 1,800 |
Print exactly one integer — the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.
|
standard output
| |
PASSED
|
44569d87ec1f2c70c7fac5a816f310e7
|
train_000.jsonl
|
1539511500
|
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
|
512 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
long MOD = (long)1e9 + 7;
public static void main(String[] args) throws IOException {
Reader.init(System.in);
new Main();
}
Main() throws IOException {
solve();
}
void solve() throws IOException {
PrintWriter out = new PrintWriter(System.out);
int n = Reader.nextInt();
int m = Reader.nextInt();
int r = Reader.nextInt()-1;
int c = Reader.nextInt()-1;
int x = Reader.nextInt();
int y = Reader.nextInt();
boolean[][] free = new boolean[n][m];
for(int i = 0; i < n; i++){
String xx = Reader.next();
for(int j = 0; j < xx.length(); j++){
if(xx.charAt(j) == '.'){free[i][j] = true;}
}
}
int vis[][] = new int[n][m];
boolean vis2[][] = new boolean[n][m];
for(int i = 0; i < n; i++){Arrays.fill(vis[i], Integer.MAX_VALUE);}
Queue<Node> P = new LinkedList<>();
int ans = 0;
P.add(new Node(r,c,0,0));
while(!P.isEmpty()){
Node S = P.remove();
if(S.x < 0 || S.x >= n || S.y < 0||S.y >= m|| S.lst > x || S.rst > y){continue;}
if(vis[S.x][S.y] <= S.lst || !free[S.x][S.y]) continue;
vis[S.x][S.y] = S.lst;
if(!vis2[S.x][S.y])ans++;
vis2[S.x][S.y] = true;
P.add(new Node(S.x+1, S.y, S.lst, S.rst));
P.add(new Node(S.x - 1, S.y, S.lst, S.rst));
P.add(new Node(S.x, S.y+1, S.lst, S.rst+1));
P.add(new Node(S.x , S.y -1, S.lst + 1, S.rst));
}
out.println(ans);
out.close();
}
class Node{
int lst;
int rst;
int x;
int y;
Node(int xi, int yi, int l, int r){
lst = l;
rst = r;
x = xi;
y = yi;
}
}
boolean ispal(String x){
for(int i = 0; i < x.length()/2; i++){
if(x.charAt(x.length() - i-1) != x.charAt(i)){return false;}
}
return true;
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
static void init(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
static String nextToken() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException { return Integer.parseInt( next() ); }
static double nextDouble() throws IOException { return Double.parseDouble( next() ); }
static long nextLong() { return Long.parseLong(nextToken()); }
}
|
Java
|
["4 5\n3 2\n1 2\n.....\n.***.\n...**\n*....", "4 4\n2 2\n0 1\n....\n..*.\n....\n...."]
|
2 seconds
|
["10", "7"]
|
NoteCells, reachable in the corresponding example, are marked with '+'.First example: +++..+***.+++***+++. Second example: .++..+*..++..++.
|
Java 8
|
standard input
|
[
"shortest paths",
"graphs"
] |
cfdbe4bd1c9438de2d871768c546a580
|
The first line contains two integers n, m (1 ≤ n, m ≤ 2000) — the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0 ≤ x, y ≤ 109) — the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles.
| 1,800 |
Print exactly one integer — the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.
|
standard output
| |
PASSED
|
498abddb6ac78398fb4204ada2cf8ee7
|
train_000.jsonl
|
1539511500
|
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
|
512 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class Soly
{
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];
}
for(int i = 0; i < n2; i++) {
R[i] = a[mid + 1 + i];
R1[i] = c[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++];
}
else
{
a[k] = R[j];
c[k] = R1[j++];
inversion=inversion+(n1-i);
}
return inversion;
}
static int l;
static int va(char[]a){
Stack<Character>s= new Stack<>();
int op=0,c=0;
for (int p = 0; p < a.length; p++) {
if (a[p]==')'){
if (!s.isEmpty()){
if (s.peek()=='('){
op--;
s.pop();
}
else{
++c;
s.push(')');
}
}
else {
++c;
s.push(')');
}
}
else if(a[p]=='(') {
++op;
if (!s.isEmpty()){
if (s.peek()=='('){
s.push(a[p]);
}
else s.push('(');
}
else s.push('(');
}
}
if (s.isEmpty())return 0;
else {
if (op>0&&c>0)return 50;
if (s.peek()=='('){
//1 opening
l=s.size();
return 1;
}
else {
//2 closing
l=s.size();
return 2;
}
}
}
static public int maxSubArray(int[] nums) {
boolean s= false,s2=false;
int ans2=Integer.MIN_VALUE;
int ans=0,sum=0;
for (int i = 0; i < nums.length; i++) {
if (nums[i]>=0)s=true;
if (nums[i]<0)s2=true;
ans2=Math.max(ans2,nums[i]);
if (sum+nums[i]>0)sum+=nums[i];
else sum=0;
ans=Math.max(ans,sum);
}
if (!s2)return ans;
if (!s)return ans2;
else {
return ans;
}
}
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(),m=in.nextInt();
int r=in.nextInt()-1,c=in.nextInt()-1;
int x=in.nextInt(),y=in.nextInt();
char[][]a= new char[n][m];
for (int i = 0; i < n; i++) a[i]=in.next().toCharArray();
int ans=0;
LinkedList<Triple>queue = new LinkedList<>();
queue.add(new Triple(r,c,x,y));
while (!queue.isEmpty()){
Triple demo=queue.pollFirst();
if (a[demo.r][demo.c]!='.')continue;
++ans;
a[demo.r][demo.c]='+';
if (demo.r+1<n&&a[demo.r+1][demo.c]=='.'){
queue.addFirst(new Triple(demo.r+1,demo.c,demo.x,demo.y));
}
if (demo.r-1>=0&&a[demo.r-1][demo.c]=='.'){
queue.addFirst(new Triple(demo.r-1,demo.c,demo.x,demo.y));
}
if (demo.x>0&&demo.c-1>=0&&a[demo.r][demo.c-1]=='.'){
queue.addLast(new Triple(demo.r,demo.c-1,demo.x-1,demo.y));
}
if (demo.y>0&&demo.c+1<m&&a[demo.r][demo.c+1]=='.'){
queue.addLast(new Triple(demo.r,demo.c+1,demo.x,demo.y-1));
}
}
or.println(ans);
}
}
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 Triple{
int r,c,x,y;
public Triple(int r, int c, int x, int y) {
this.r = r;
this.c = c;
this.x = x;
this.y = y;
}
}
|
Java
|
["4 5\n3 2\n1 2\n.....\n.***.\n...**\n*....", "4 4\n2 2\n0 1\n....\n..*.\n....\n...."]
|
2 seconds
|
["10", "7"]
|
NoteCells, reachable in the corresponding example, are marked with '+'.First example: +++..+***.+++***+++. Second example: .++..+*..++..++.
|
Java 8
|
standard input
|
[
"shortest paths",
"graphs"
] |
cfdbe4bd1c9438de2d871768c546a580
|
The first line contains two integers n, m (1 ≤ n, m ≤ 2000) — the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0 ≤ x, y ≤ 109) — the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles.
| 1,800 |
Print exactly one integer — the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.
|
standard output
| |
PASSED
|
cf09f98ca8762cd318c04849001d75ca
|
train_000.jsonl
|
1539511500
|
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
|
512 megabytes
|
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args)
{
FastReader reader = new FastReader();
PrintWriter writer = new PrintWriter(System.out);
int n = reader.nextInt();
int m = reader.nextInt();
int r = reader.nextInt()-1;
int c = reader.nextInt()-1;
long[][] x = new long[n][m];
long[][] y = new long[n][m];
boolean[][] visit = new boolean[n][m];
x[r][c] = reader.nextLong();
y[r][c] = reader.nextLong();
int[][] lost = new int[n][m];
for (int i=0; i<n; i++)
for (int j=0; j<m; j++)
lost[i][j] = Integer.MAX_VALUE;
String[] grid = new String[n];
for (int i=0; i<n; i++)
grid[i] = reader.nextLine();
PriorityQueue<Node> heap = new PriorityQueue<>();
heap.add(new Node(r, c, 0));
visit[r][c] = true;
lost[r][c] = 0;
int[] ar = {1, 0, -1, 0};
int[] ac = {0, 1, 0, -1};
int count = 0;
while (!heap.isEmpty())
{
Node temp = heap.remove();
int tr = temp.x;
int tc = temp.y;
if (temp.l > lost[tr][tc])
continue;
count++;
for (int i=0; i<4; i++)
{
int nr = tr + ar[i];
int nc = tc + ac[i];
if (nr >= 0 && nr < n && nc >= 0 && nc < m)
if (grid[nr].charAt(nc) != '*')
{
if (ac[i] == 0)
{
x[nr][nc] = x[tr][tc];
y[nr][nc] = y[tr][tc];
if (temp.l < lost[nr][nc])
{
heap.add(new Node(nr, nc, temp.l));
lost[nr][nc] = temp.l;
}
}
else if (ac[i] == -1 && x[tr][tc] > 0)
{
x[nr][nc] = x[tr][tc] - 1;
y[nr][nc] = y[tr][tc];
if (temp.l + 1 < lost[nr][nc])
{
heap.add(new Node(nr, nc, temp.l+1));
lost[nr][nc] = temp.l + 1;
}
}
else if (ac[i] == 1 && y[tr][tc] > 0)
{
x[nr][nc] = x[tr][tc];
y[nr][nc] = y[tr][tc] - 1;
if (temp.l + 1 < lost[nr][nc])
{
heap.add(new Node(nr, nc, temp.l+1));
lost[nr][nc] = temp.l + 1;
}
}
}
}
}
/*for (int i=0; i<n; i++)
{
for (int j=0; j<m; j++)
if (visit[i][j])
writer.print("+");
else
writer.print(".");
writer.println();
}
for (int i=0; i<n; i++)
{
for (int j=0; j<m; j++)
writer.print(x[i][j] + " ");
writer.println();
}
for (int i=0; i<n; i++)
{
for (int j=0; j<m; j++)
writer.print(y[i][j] + " ");
writer.println();
}*/
//writer.println(x[0][1] + " " + y[0][1]);
//wr
writer.print(count);
writer.close();
}
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;
}
}
}
class Node implements Comparable<Node>
{
int x;
int y;
int l;
Node(int a, int b, int c)
{
x = a;
y = b;
l = c;
}
public int compareTo(Node temp)
{
return Integer.compare(this.l, temp.l);
}
}
|
Java
|
["4 5\n3 2\n1 2\n.....\n.***.\n...**\n*....", "4 4\n2 2\n0 1\n....\n..*.\n....\n...."]
|
2 seconds
|
["10", "7"]
|
NoteCells, reachable in the corresponding example, are marked with '+'.First example: +++..+***.+++***+++. Second example: .++..+*..++..++.
|
Java 8
|
standard input
|
[
"shortest paths",
"graphs"
] |
cfdbe4bd1c9438de2d871768c546a580
|
The first line contains two integers n, m (1 ≤ n, m ≤ 2000) — the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0 ≤ x, y ≤ 109) — the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles.
| 1,800 |
Print exactly one integer — the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.
|
standard output
| |
PASSED
|
2bf2557ef16bdad180a6bf42851a5411
|
train_000.jsonl
|
1539511500
|
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
|
512 megabytes
|
//Labyrinth
//iterative bfs
import java.io.*;
import java.util.*;
public class B1063b{
public static int n,m,xi,yi,left,right;
public static char[][] board;
public static boolean[][] used;
public static int[][] movesl,movesr;
public static void main(String[] args)throws IOException{
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
StringTokenizer st = new StringTokenizer(f.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
st = new StringTokenizer(f.readLine());
xi = Integer.parseInt(st.nextToken());
yi = Integer.parseInt(st.nextToken());
st = new StringTokenizer(f.readLine());
left = Integer.parseInt(st.nextToken());
right = Integer.parseInt(st.nextToken());
board = new char[n][m];
String s;
for(int k = 0; k < n; k++){
s = f.readLine();
for(int j = 0; j < m; j++){
board[k][j] = s.charAt(j);
}
}
used = new boolean[n][m];
movesl = new int[n][m];
movesr = new int[n][m];
PriorityQueue<State> q = new PriorityQueue<State>();
q.add(new State(xi-1,yi-1,0,0));
int x,y,l,r;
int answer = 0;
used[xi-1][yi-1] = true;
while(!q.isEmpty()){
State cur = q.poll();
x = cur.x;
y = cur.y;
l = cur.l;
r = cur.r;
answer++;
//System.out.println(x + " " + y);
if(in(x-1,y) && !used[x-1][y] && board[x-1][y] != '*'){
q.add(new State(x-1,y,l,r));
used[x-1][y] = true;
}
if(in(x+1,y) && !used[x+1][y] && board[x+1][y] != '*'){
q.add(new State(x+1,y,l,r));
used[x+1][y] = true;
}
if(in(x,y-1) && !used[x][y-1] && board[x][y-1] != '*' && l < left){
q.add(new State(x,y-1,l+1,r));
used[x][y-1] = true;
}
if(in(x,y+1) && !used[x][y+1] && board[x][y+1] != '*' && r < right){
q.add(new State(x,y+1,l,r+1));
used[x][y+1] = true;
}
}
out.println(answer);
out.close();
}
public static class State implements Comparable<State>{
int x;
int y;
int l;
int r;
public State(int a, int b, int c, int d){
x = a;
y = b;
l = c;
r = d;
}
public int compareTo(State s){
return l+r-s.l-s.r;
}
}
public static boolean in(int a, int b){
return a >= 0 && b >= 0 && a < n && b < m;
}
}
|
Java
|
["4 5\n3 2\n1 2\n.....\n.***.\n...**\n*....", "4 4\n2 2\n0 1\n....\n..*.\n....\n...."]
|
2 seconds
|
["10", "7"]
|
NoteCells, reachable in the corresponding example, are marked with '+'.First example: +++..+***.+++***+++. Second example: .++..+*..++..++.
|
Java 8
|
standard input
|
[
"shortest paths",
"graphs"
] |
cfdbe4bd1c9438de2d871768c546a580
|
The first line contains two integers n, m (1 ≤ n, m ≤ 2000) — the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0 ≤ x, y ≤ 109) — the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles.
| 1,800 |
Print exactly one integer — the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.
|
standard output
| |
PASSED
|
c7efe4d436216c80961f879f329ee58f
|
train_000.jsonl
|
1539511500
|
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
|
512 megabytes
|
/**
* Created by Aminul on 10/14/2018.
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Queue;
public class D_3 {
public static void main(String[] args)throws Exception {
FastReader in = new FastReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
n = in.nextInt(); m = in.nextInt();
r = in.nextInt(); c = in.nextInt();
maxLeft = in.nextInt(); maxRight = in.nextInt();
r--; c--;
mat = new char[n][];
for (int i = 0; i < n; i++) {
mat[i] = in.next(m);
}
int ans = bfs_0_1();
pw.println(ans);
pw.close();
}
static int[] dx = new int[]{0, 1, 0, -1};
static int[] dy = new int[]{1, 0, -1, 0};
static int LEFT = 2, RIGHT = 0, UP = 3, DOWN = 1;
static int n, m, r, c, maxLeft, maxRight;
static char[][] mat;
static boolean isValid(int x, int y, boolean vis[][]) {
return x >= 0 && x < n && y >= 0 && y < m && vis[x][y] == false && mat[x][y] != '*';
}
static boolean v[][];
static int bfs_0_1() {
v = new boolean[n][m];
v[r][c] = true;
ArrayDeque<Node> dq = new ArrayDeque<>();
dq.addFirst(new Node(r, c, 0, 0));
int ans = 0;
while (!dq.isEmpty()) {
Node top = dq.pollFirst();
if(top.left <= maxLeft && top.right <= maxRight) ans++;
else continue;
for(int i = 0; i < 4; i++) {
int x = top.x + dx[i], y = top.y + dy[i];
if(isValid(x, y, v)) {
v[x][y] = true;
if (i == LEFT) dq.addLast(new Node(x, y, top.left + 1, top.right));
else if (i == RIGHT) dq.addLast(new Node(x, y, top.left, top.right + 1));
else dq.addFirst(new Node(x, y, top.left, top.right));
}
}
}
return ans;
}
static class Node {
int x, y, left, right;
Node(int X, int Y, int L, int R) {
x = X; y = Y; left = L; right = R;
}
}
static void debug(Object...obj) {
System.err.println(Arrays.deepToString(obj));
}
static class FastReader {
InputStream is;
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
public FastReader(InputStream is) {
this.is = is;
}
public 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++];
}
public boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b)) ;
return b;
}
public String next() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public String nextLine() {
int c = skip();
StringBuilder sb = new StringBuilder();
while (!isEndOfLine(c)){
sb.appendCodePoint(c);
c = readByte();
}
return sb.toString();
}
public 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 << 3) + (num << 1) + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
public 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 << 3) + (num << 1) + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
public double nextDouble() {
return Double.parseDouble(next());
}
public 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);
}
public char readChar() {
return (char) skip();
}
}
}
|
Java
|
["4 5\n3 2\n1 2\n.....\n.***.\n...**\n*....", "4 4\n2 2\n0 1\n....\n..*.\n....\n...."]
|
2 seconds
|
["10", "7"]
|
NoteCells, reachable in the corresponding example, are marked with '+'.First example: +++..+***.+++***+++. Second example: .++..+*..++..++.
|
Java 8
|
standard input
|
[
"shortest paths",
"graphs"
] |
cfdbe4bd1c9438de2d871768c546a580
|
The first line contains two integers n, m (1 ≤ n, m ≤ 2000) — the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0 ≤ x, y ≤ 109) — the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles.
| 1,800 |
Print exactly one integer — the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.
|
standard output
| |
PASSED
|
3c6e0688fabf1bf665af0033c67e29d8
|
train_000.jsonl
|
1539511500
|
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
|
512 megabytes
|
import java.util.Deque;
import java.util.LinkedList;
import java.util.Scanner;
public class Main {
private static class Position {
public int x , y;
public Position(int x , int y) {
this.x = x;
this.y = y;
}
}
private static String[] input = new String[2010];
private static int[][] leftDist = new int[2010][2010];
private static int[] dx = new int[] {- 1 , 0 , 1 , 0};
private static int[] dy = new int[] {0 , 1 , 0 , - 1};
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i , j , n , m , ans = 0;
n = scan.nextInt();
m = scan.nextInt();
for (i = 0;i < n;i ++) {
for (j = 0;j < m;j ++) {
leftDist[i][j] = - 1;
}
}
int r = scan.nextInt() , c = scan.nextInt();
int x = scan.nextInt() , y = scan.nextInt();
for (i = 0;i < n;i ++) {
input[i] = scan.next();
}
r --;
c --;
leftDist[r][c] = 0;
Deque<Position> queue = new LinkedList<>();
queue.addLast(new Position(r , c));
while (!queue.isEmpty()) {
Position current = queue.pollFirst();
for (i = 0;i < 4;i ++) {
int tx = current.x + dx[i];
int ty = current.y + dy[i];
if (tx >= 0 && tx < n && ty >= 0 && ty < m && input[tx].charAt(ty) == '.') {
int nextDist = leftDist[current.x][current.y];
if (i == 3) {
nextDist ++;
}
if (nextDist < leftDist[tx][ty] || leftDist[tx][ty] < 0) {
leftDist[tx][ty] = nextDist;
if (i < 3) {
queue.addFirst(new Position(tx , ty));
} else {
// left
queue.addLast(new Position(tx , ty));
}
}
}
}
}
for (i = 0;i < n;i ++) {
for (j = 0;j < m;j ++) {
if (leftDist[i][j] >= 0) {
int xOffset = j - c;
int rightDist = xOffset + leftDist[i][j];
if (leftDist[i][j] <= x && rightDist <= y) {
ans ++;
}
}
}
}
System.out.println(ans);
}
}
|
Java
|
["4 5\n3 2\n1 2\n.....\n.***.\n...**\n*....", "4 4\n2 2\n0 1\n....\n..*.\n....\n...."]
|
2 seconds
|
["10", "7"]
|
NoteCells, reachable in the corresponding example, are marked with '+'.First example: +++..+***.+++***+++. Second example: .++..+*..++..++.
|
Java 8
|
standard input
|
[
"shortest paths",
"graphs"
] |
cfdbe4bd1c9438de2d871768c546a580
|
The first line contains two integers n, m (1 ≤ n, m ≤ 2000) — the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0 ≤ x, y ≤ 109) — the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles.
| 1,800 |
Print exactly one integer — the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.
|
standard output
| |
PASSED
|
723c9f88ceabe876397a4f8d7d8a68e0
|
train_000.jsonl
|
1539511500
|
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
|
512 megabytes
|
import java.util.PriorityQueue;
import java.util.Scanner;
public class Main {
private static class Element implements Comparable<Element> {
public int x , y;
public int cnt;
public Element(int x , int y , int cnt) {
this.x = x;
this.y = y;
this.cnt = cnt;
}
@Override
public int compareTo(Element e) {
if (this.cnt < e.cnt) {
return - 1;
} else if (this.cnt > e.cnt) {
return 1;
} else {
return 0;
}
}
}
private static String[] input = new String[2010];
private static int[][] leftCnt = new int[2010][2010];
private static int[] dx = new int[] {- 1 , 0 , 1 , 0};
private static int[] dy = new int[] {0 , 1 , 0 , - 1};
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i , j , n = scan.nextInt() , m = scan.nextInt();
int r = scan.nextInt() , c = scan.nextInt();
int x = scan.nextInt() , y = scan.nextInt();
r --;
c --;
for (i = 0;i < n;i ++) {
input[i] = scan.next();
}
for (i = 0;i < n;i ++) {
for (j = 0;j < m;j ++) {
leftCnt[i][j] = - 1;
}
}
PriorityQueue<Element> queue = new PriorityQueue<>();
queue.add(new Element(r , c , 0));
leftCnt[r][c] = 0;
while (!queue.isEmpty()) {
Element e = queue.poll();
if (leftCnt[e.x][e.y] == e.cnt) {
for (i = 0;i < 4;i ++) {
int tx = e.x + dx[i];
int ty = e.y + dy[i];
int nextCnt = e.cnt;
if (i == 3) {
nextCnt ++;
}
if (tx >= 0 && tx < n && ty >= 0 && ty < m && input[tx].charAt(ty) == '.') {
if (nextCnt < leftCnt[tx][ty] || leftCnt[tx][ty] < 0) {
leftCnt[tx][ty] = nextCnt;
queue.add(new Element(tx , ty , nextCnt));
}
}
}
}
}
int ans = 0;
for (i = 0;i < n;i ++) {
for (j = 0;j < m;j ++) {
if (input[i].charAt(j) == '.') {
int value1 = leftCnt[i][j];
if (value1 >= 0) {
int value2 = j - c + value1;
if (value1 <= x && value2 <= y) {
ans ++;
}
}
}
}
}
System.out.println(ans);
}
}
|
Java
|
["4 5\n3 2\n1 2\n.....\n.***.\n...**\n*....", "4 4\n2 2\n0 1\n....\n..*.\n....\n...."]
|
2 seconds
|
["10", "7"]
|
NoteCells, reachable in the corresponding example, are marked with '+'.First example: +++..+***.+++***+++. Second example: .++..+*..++..++.
|
Java 8
|
standard input
|
[
"shortest paths",
"graphs"
] |
cfdbe4bd1c9438de2d871768c546a580
|
The first line contains two integers n, m (1 ≤ n, m ≤ 2000) — the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0 ≤ x, y ≤ 109) — the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles.
| 1,800 |
Print exactly one integer — the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.
|
standard output
| |
PASSED
|
92ebf89d439bafeb4d407281226cc72b
|
train_000.jsonl
|
1539511500
|
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
|
512 megabytes
|
//package baobab;
import java.io.*;
import java.util.*;
public class D {
public static void main(String[] args) {
Solver solver = new Solver();
}
static class Solver {
IO io;
public Solver() {
this.io = new IO();
try {
solve();
} catch (RuntimeException e) {
if (!e.getMessage().equals("Clean exit")) {
throw e;
}
} finally {
io.close();
}
}
/****************************** START READING HERE ********************************/
int n;
int m;
boolean[][] v;
void solve() {
n = io.nextInt();
m = io.nextInt();
int startY = io.nextInt();
int startX = io.nextInt();
int maxLmoves = io.nextInt();
int maxRmoves = io.nextInt();
v = new boolean[n+2][m+2];
for (int y=0; y<=n+1; y++) v[y][0] = true;
for (int y=0; y<=n+1; y++) v[y][m+1] = true;
for (int x=0; x<=m+1; x++) v[0][x] = true;
for (int x=0; x<=m+1; x++) v[n+1][x] = true;
for (int y=1; y<=n; y++) {
String row = io.next();
for (int x=1; x<=m; x++) {
char c = row.charAt(x-1);
if (c == '*') v[y][x] = true;
}
}
boolean[][] canReach = new boolean[n+2][m+2];
Deque<State> q = new ArrayDeque<>();
q.add(new State(startY, startX, 0, 0, 0));
while (!q.isEmpty()) {
State s = q.pollFirst();
if (v[s.y][s.x]) continue;
v[s.y][s.x] = true;
if (s.left <= maxLmoves && s.right <= maxRmoves) canReach[s.y][s.x] = true;
else continue;
if (!v[s.y+1][s.x]) q.addFirst(new State(s.y+1, s.x, s.steps+1, s.left, s.right));
if (!v[s.y-1][s.x]) q.addFirst(new State(s.y-1, s.x, s.steps+1, s.left, s.right));
if (!v[s.y][s.x+1]) q.addLast(new State(s.y, s.x+1, s.steps+1, s.left, s.right+1));
if (!v[s.y][s.x-1]) q.addLast(new State(s.y, s.x-1, s.steps+1, s.left+1, s.right));
}
long ans = 0;
for (int y=1; y<=n; y++) {
for (int x=1; x<=m; x++) {
if (canReach[y][x]) ans++;
}
}
io.println(ans);
}
class State implements Comparable<State> {
int y;
int x;
int steps;
int left;
int right;
public State(int y, int x, int steps, int left, int right) {
this.y = y;
this.x = x;
this.steps = steps;
this.left = left;
this.right = right;
}
@Override
public int compareTo(State o) {
if (this.steps < o.steps) return -1;
if (o.steps < this.steps) return 1;
int c1 = this.left + this.right;
int c2 = o.left + o.right;
if (c1 < c2) return -1;
if (c2 < c1) return 1;
return 0;
}
}
/************************** UTILITY CODE BELOW THIS LINE **************************/
long MOD = (long)1e9 + 7;
boolean closeToZero(double v) {
// Check if double is close to zero, considering precision issues.
return Math.abs(v) <= 0.0000000001;
}
class DrawGrid {
void draw(boolean[][] d) {
System.out.print(" ");
for (int x=0; x<d[0].length; x++) {
System.out.print(" " + x + " ");
}
System.out.println("");
for (int y=0; y<d.length; y++) {
System.out.print(y + " ");
for (int x=0; x<d[0].length; x++) {
System.out.print((d[y][x] ? "[x]" : "[ ]"));
}
System.out.println("");
}
}
void draw(int[][] d) {
int max = 1;
for (int y=0; y<d.length; y++) {
for (int x=0; x<d[0].length; x++) {
max = Math.max(max, ("" + d[y][x]).length());
}
}
System.out.print(" ");
String format = "%" + (max+2) + "s";
for (int x=0; x<d[0].length; x++) {
System.out.print(String.format(format, x) + " ");
}
format = "%" + (max) + "s";
System.out.println("");
for (int y=0; y<d.length; y++) {
System.out.print(y + " ");
for (int x=0; x<d[0].length; x++) {
System.out.print(" [" + String.format(format, (d[y][x])) + "]");
}
System.out.println("");
}
}
}
class IDval implements Comparable<IDval> {
int id;
long val;
public IDval(int id, long val) {
this.val = val;
this.id = id;
}
@Override
public int compareTo(IDval o) {
if (this.val < o.val) return -1;
if (this.val > o.val) return 1;
return this.id - o.id;
}
}
private class ElementCounter {
private HashMap<Long, Integer> elements;
public ElementCounter() {
elements = new HashMap<>();
}
public void add(long element) {
int count = 1;
Integer prev = elements.get(element);
if (prev != null) count += prev;
elements.put(element, count);
}
public void remove(long element) {
int count = elements.remove(element);
count--;
if (count > 0) elements.put(element, count);
}
public int get(long element) {
Integer val = elements.get(element);
if (val == null) return 0;
return val;
}
public int size() {
return elements.size();
}
}
class StringCounter {
HashMap<String, Integer> elements;
public StringCounter() {
elements = new HashMap<>();
}
public void add(String identifier) {
int count = 1;
Integer prev = elements.get(identifier);
if (prev != null) count += prev;
elements.put(identifier, count);
}
public void remove(String identifier) {
int count = elements.remove(identifier);
count--;
if (count > 0) elements.put(identifier, count);
}
public long get(String identifier) {
Integer val = elements.get(identifier);
if (val == null) return 0;
return val;
}
public int size() {
return elements.size();
}
}
class DisjointSet {
/** Union Find / Disjoint Set data structure. */
int[] size;
int[] parent;
int componentCount;
public DisjointSet(int n) {
componentCount = n;
size = new int[n];
parent = new int[n];
for (int i=0; i<n; i++) parent[i] = i;
for (int i=0; i<n; i++) size[i] = 1;
}
public void join(int a, int b) {
/* Find roots */
int rootA = parent[a];
int rootB = parent[b];
while (rootA != parent[rootA]) rootA = parent[rootA];
while (rootB != parent[rootB]) rootB = parent[rootB];
if (rootA == rootB) {
/* Already in the same set */
return;
}
/* Merge smaller set into larger set. */
if (size[rootA] > size[rootB]) {
size[rootA] += size[rootB];
parent[rootB] = rootA;
} else {
size[rootB] += size[rootA];
parent[rootA] = rootB;
}
componentCount--;
}
}
class Trie {
int N;
int Z;
int nextFreeId;
int[][] pointers;
boolean[] end;
/** maxLenSum = maximum possible sum of length of words */
public Trie(int maxLenSum, int alphabetSize) {
this.N = maxLenSum;
this.Z = alphabetSize;
this.nextFreeId = 1;
pointers = new int[N+1][alphabetSize];
end = new boolean[N+1];
}
public void addWord(String word) {
int curr = 0;
for (int j=0; j<word.length(); j++) {
int c = word.charAt(j) - 'a';
int next = pointers[curr][c];
if (next == 0) {
next = nextFreeId++;
pointers[curr][c] = next;
}
curr = next;
}
end[curr] = true;
}
public boolean hasWord(String word) {
int curr = 0;
for (int j=0; j<word.length(); j++) {
int c = word.charAt(j) - 'a';
int next = pointers[curr][c];
if (next == 0) return false;
curr = next;
}
return end[curr];
}
}
private static class Prob {
/** For heavy calculations on probabilities, this class
* provides more accuracy & efficiency than doubles.
* Math explained: https://en.wikipedia.org/wiki/Log_probability
* Quick start:
* - Instantiate probabilities, eg. Prob a = new Prob(0.75)
* - add(), multiply() return new objects, can perform on nulls & NaNs.
* - get() returns probability as a readable double */
/** Logarithmized probability. Note: 0% represented by logP NaN. */
private double logP;
/** Construct instance with real probability. */
public Prob(double real) {
if (real > 0) this.logP = Math.log(real);
else this.logP = Double.NaN;
}
/** Construct instance with already logarithmized value. */
static boolean dontLogAgain = true;
public Prob(double logP, boolean anyBooleanHereToChooseThisConstructor) {
this.logP = logP;
}
/** Returns real probability as a double. */
public double get() {
return Math.exp(logP);
}
@Override
public String toString() {
return ""+get();
}
/***************** STATIC METHODS BELOW ********************/
/** Note: returns NaN only when a && b are both NaN/null. */
public static Prob add(Prob a, Prob b) {
if (nullOrNaN(a) && nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain);
if (nullOrNaN(a)) return copy(b);
if (nullOrNaN(b)) return copy(a);
double x = Math.max(a.logP, b.logP);
double y = Math.min(a.logP, b.logP);
double sum = x + Math.log(1 + Math.exp(y - x));
return new Prob(sum, dontLogAgain);
}
/** Note: multiplying by null or NaN produces NaN (repping 0% real prob). */
public static Prob multiply(Prob a, Prob b) {
if (nullOrNaN(a) || nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain);
return new Prob(a.logP + b.logP, dontLogAgain);
}
/** Returns true if p is null or NaN. */
private static boolean nullOrNaN(Prob p) {
return (p == null || Double.isNaN(p.logP));
}
/** Returns a new instance with the same value as original. */
private static Prob copy(Prob original) {
return new Prob(original.logP, dontLogAgain);
}
}
class Binary implements Comparable<Binary> {
/**
* Use example: Binary b = new Binary(Long.toBinaryString(53249834L));
*
* When manipulating small binary strings, instantiate new Binary(string)
* When just reading large binary strings, instantiate new Binary(string,true)
* get(int i) returns a character '1' or '0', not an int.
*/
private boolean[] d;
private int first; // Starting from left, the first (most remarkable) '1'
public int length;
public Binary(String binaryString) {
this(binaryString, false);
}
public Binary(String binaryString, boolean initWithMinArraySize) {
length = binaryString.length();
int size = Math.max(2*length, 1);
first = length/4;
if (initWithMinArraySize) {
first = 0;
size = Math.max(length, 1);
}
d = new boolean[size];
for (int i=0; i<length; i++) {
if (binaryString.charAt(i) == '1') d[i+first] = true;
}
}
public void addFirst(char c) {
if (first-1 < 0) doubleArraySize();
first--;
d[first] = (c == '1' ? true : false);
length++;
}
public void addLast(char c) {
if (first+length >= d.length) doubleArraySize();
d[first+length] = (c == '1' ? true : false);
length++;
}
private void doubleArraySize() {
boolean[] bigArray = new boolean[(d.length+1) * 2];
int newFirst = bigArray.length / 4;
for (int i=0; i<length; i++) {
bigArray[i + newFirst] = d[i + first];
}
first = newFirst;
d = bigArray;
}
public boolean flip(int i) {
boolean value = (this.d[first+i] ? false : true);
this.d[first+i] = value;
return value;
}
public void set(int i, char c) {
boolean value = (c == '1' ? true : false);
this.d[first+i] = value;
}
public char get(int i) {
return (this.d[first+i] ? '1' : '0');
}
@Override
public int compareTo(Binary o) {
if (this.length != o.length) return this.length - o.length;
int len = this.length;
for (int i=0; i<len; i++) {
int diff = this.get(i) - o.get(i);
if (diff != 0) return diff;
}
return 0;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i=0; i<length; i++) {
sb.append(d[i+first] ? '1' : '0');
}
return sb.toString();
}
}
/************************** Range queries **************************/
class FenwickMin {
long n;
long[] original;
long[] bottomUp;
long[] topDown;
public FenwickMin(int n) {
this.n = n;
original = new long[n+2];
bottomUp = new long[n+2];
topDown = new long[n+2];
}
public void set(int modifiedNode, long value) {
long replaced = original[modifiedNode];
original[modifiedNode] = value;
// Update left tree
int i = modifiedNode;
long v = value;
while (i <= n) {
if (v > bottomUp[i]) {
if (replaced == bottomUp[i]) {
v = Math.min(v, original[i]);
for (int r=1 ;; r++) {
int x = (i&-i)>>>r;
if (x == 0) break;
int child = i-x;
v = Math.min(v, bottomUp[child]);
}
} else break;
}
if (v == bottomUp[i]) break;
bottomUp[i] = v;
i += (i&-i);
}
// Update right tree
i = modifiedNode;
v = value;
while (i > 0) {
if (v > topDown[i]) {
if (replaced == topDown[i]) {
v = Math.min(v, original[i]);
for (int r=1 ;; r++) {
int x = (i&-i)>>>r;
if (x == 0) break;
int child = i+x;
if (child > n+1) break;
v = Math.min(v, topDown[child]);
}
} else break;
}
if (v == topDown[i]) break;
topDown[i] = v;
i -= (i&-i);
}
}
public long getMin(int a, int b) {
long min = original[a];
int prev = a;
int curr = prev + (prev&-prev); // parent right hand side
while (curr <= b) {
min = Math.min(min, topDown[prev]); // value from the other tree
prev = curr;
curr = prev + (prev&-prev);;
}
min = Math.min(min, original[prev]);
prev = b;
curr = prev - (prev&-prev); // parent left hand side
while (curr >= a) {
min = Math.min(min,bottomUp[prev]); // value from the other tree
prev = curr;
curr = prev - (prev&-prev);
}
return min;
}
}
class FenwickSum {
public long[] d;
public FenwickSum(int n) {
d=new long[n+1];
}
/** a[0] must be unused. */
public FenwickSum(long[] a) {
d=new long[a.length];
for (int i=1; i<a.length; i++) {
modify(i, a[i]);
}
}
/** Do not modify i=0. */
void modify(int i, long v) {
while (i<d.length) {
d[i] += v;
// Move to next uplink on the RIGHT side of i
i += (i&-i);
}
}
/** Returns sum from a to b, *BOTH* inclusive. */
long getSum(int a, int b) {
return getSum(b) - getSum(a-1);
}
private long getSum(int i) {
long sum = 0;
while (i>0) {
sum += d[i];
// Move to next uplink on the LEFT side of i
i -= (i&-i);
}
return sum;
}
}
class SegmentTree {
/* Provides log(n) operations for:
* - Range query (sum, min or max)
* - Range update ("+8 to all values between indexes 4 and 94")
*/
int N;
long[] lazy;
long[] sum;
long[] min;
long[] max;
boolean supportSum;
boolean supportMin;
boolean supportMax;
public SegmentTree(int n) {
this(n, true, true, true);
}
public SegmentTree(int n, boolean supportSum, boolean supportMin, boolean supportMax) {
for (N=2; N<n;) N*=2;
this.lazy = new long[2*N];
this.supportSum = supportSum;
this.supportMin = supportMin;
this.supportMax = supportMax;
if (this.supportSum) this.sum = new long[2*N];
if (this.supportMin) this.min = new long[2*N];
if (this.supportMax) this.max = new long[2*N];
}
void modifyRange(long x, int a, int b) {
modifyRec(a, b, 1, 0, N-1, x);
}
void setRange() {
//TODO
}
long getSum(int a, int b) {
return querySum(a, b, 1, 0, N-1);
}
long getMin(int a, int b) {
return queryMin(a, b, 1, 0, N-1);
}
long getMax(int a, int b) {
return queryMax(a, b, 1, 0, N-1);
}
private long querySum(int wantedLeft, int wantedRight, int i, int actualLeft, int actualRight) {
if (wantedLeft > actualRight || wantedRight < actualLeft) {
return 0;
}
if (wantedLeft == actualLeft && wantedRight == actualRight) {
int count = wantedRight - wantedLeft + 1;
return sum[i] + count * lazy[i];
}
if (lazy[i] != 0) propagate(i, actualLeft, actualRight);
int d = (actualRight - actualLeft + 1) / 2;
long left = querySum(wantedLeft, min(actualLeft+d-1, wantedRight), 2*i, actualLeft, actualLeft+d-1);
long right = querySum(max(actualLeft+d, wantedLeft), wantedRight, 2*i+1, actualLeft+d, actualRight);
return left + right;
}
private long queryMin(int wantedLeft, int wantedRight, int i, int actualLeft, int actualRight) {
if (wantedLeft > actualRight || wantedRight < actualLeft) {
return 0;
}
if (wantedLeft == actualLeft && wantedRight == actualRight) {
return min[i] + lazy[i];
}
if (lazy[i] != 0) propagate(i, actualLeft, actualRight);
int d = (actualRight - actualLeft + 1) / 2;
long left = queryMin(wantedLeft, min(actualLeft+d-1, wantedRight), 2*i, actualLeft, actualLeft+d-1);
long right = queryMin(max(actualLeft+d, wantedLeft), wantedRight, 2*i+1, actualLeft+d, actualRight);
return min(left, right);
}
private long queryMax(int wantedLeft, int wantedRight, int i, int actualLeft, int actualRight) {
if (wantedLeft > actualRight || wantedRight < actualLeft) {
return 0;
}
if (wantedLeft == actualLeft && wantedRight == actualRight) {
return max[i] + lazy[i];
}
if (lazy[i] != 0) propagate(i, actualLeft, actualRight);
int d = (actualRight - actualLeft + 1) / 2;
long left = queryMax(wantedLeft, min(actualLeft+d-1, wantedRight), 2*i, actualLeft, actualLeft+d-1);
long right = queryMax(max(actualLeft+d, wantedLeft), wantedRight, 2*i+1, actualLeft+d, actualRight);
return max(left, right);
}
private void modifyRec(int wantedLeft, int wantedRight, int i, int actualLeft, int actualRight, long value) {
if (wantedLeft > actualRight || wantedRight < actualLeft) {
return;
}
if (wantedLeft == actualLeft && wantedRight == actualRight) {
lazy[i] += value;
return;
}
if (lazy[i] != 0) propagate(i, actualLeft, actualRight);
int d = (actualRight - actualLeft + 1) / 2;
modifyRec(wantedLeft, min(actualLeft+d-1, wantedRight), 2*i, actualLeft, actualLeft+d-1, value);
modifyRec(max(actualLeft+d, wantedLeft), wantedRight, 2*i+1, actualLeft+d, actualRight, value);
if (supportSum) sum[i] += value * (min(actualRight, wantedRight) - max(actualLeft, wantedLeft) + 1);
if (supportMin) min[i] = min(min[2*i] + lazy[2*i], min[2*i+1] + lazy[2*i+1]);
if (supportMax) max[i] = max(max[2*i] + lazy[2*i], max[2*i+1] + lazy[2*i+1]);
}
private void propagate(int i, int actualLeft, int actualRight) {
lazy[2*i] += lazy[i];
lazy[2*i+1] += lazy[i];
if (supportSum) sum[i] += lazy[i] * (actualRight - actualLeft + 1);
if (supportMin) min[i] += lazy[i];
if (supportMax) max[i] += lazy[i];
lazy[i] = 0;
}
}
/***************************** Graphs *****************************/
List<Integer>[] toGraph(IO io, int n) {
List<Integer>[] g = new ArrayList[n+1];
for (int i=1; i<=n; i++) g[i] = new ArrayList<>();
for (int i=1; i<=n-1; i++) {
int a = io.nextInt();
int b = io.nextInt();
g[a].add(b);
g[b].add(a);
}
return g;
}
class Graph {
HashMap<Long, List<Long>> edges;
public Graph() {
edges = new HashMap<>();
}
List<Long> getSetNeighbors(Long node) {
List<Long> neighbors = edges.get(node);
if (neighbors == null) {
neighbors = new ArrayList<>();
edges.put(node, neighbors);
}
return neighbors;
}
void addBiEdge(Long a, Long b) {
addEdge(a, b);
addEdge(b, a);
}
void addEdge(Long from, Long to) {
getSetNeighbors(to); // make sure all have initialized lists
List<Long> neighbors = getSetNeighbors(from);
neighbors.add(to);
}
// topoSort variables
int UNTOUCHED = 0;
int FINISHED = 2;
int INPROGRESS = 1;
HashMap<Long, Integer> vis;
List<Long> topoAns;
List<Long> failDueToCycle = new ArrayList<Long>() {{ add(-1L); }};
List<Long> topoSort() {
topoAns = new ArrayList<>();
vis = new HashMap<>();
for (Long a : edges.keySet()) {
if (!topoDFS(a)) return failDueToCycle;
}
Collections.reverse(topoAns);
return topoAns;
}
boolean topoDFS(long curr) {
Integer status = vis.get(curr);
if (status == null) status = UNTOUCHED;
if (status == FINISHED) return true;
if (status == INPROGRESS) {
return false;
}
vis.put(curr, INPROGRESS);
for (long next : edges.get(curr)) {
if (!topoDFS(next)) return false;
}
vis.put(curr, FINISHED);
topoAns.add(curr);
return true;
}
}
public class StronglyConnectedComponents {
/** Kosaraju's algorithm */
ArrayList<Integer>[] forw;
ArrayList<Integer>[] bacw;
/** Use: getCount(2, new int[] {1,2}, new int[] {2,1}) */
public int getCount(int n, int[] mista, int[] minne) {
forw = new ArrayList[n+1];
bacw = new ArrayList[n+1];
for (int i=1; i<=n; i++) {
forw[i] = new ArrayList<Integer>();
bacw[i] = new ArrayList<Integer>();
}
for (int i=0; i<mista.length; i++) {
int a = mista[i];
int b = minne[i];
forw[a].add(b);
bacw[b].add(a);
}
int count = 0;
List<Integer> list = new ArrayList<Integer>();
boolean[] visited = new boolean[n+1];
for (int i=1; i<=n; i++) {
dfsForward(i, visited, list);
}
visited = new boolean[n+1];
for (int i=n-1; i>=0; i--) {
int node = list.get(i);
if (visited[node]) continue;
count++;
dfsBackward(node, visited);
}
return count;
}
public void dfsForward(int i, boolean[] visited, List<Integer> list) {
if (visited[i]) return;
visited[i] = true;
for (int neighbor : forw[i]) {
dfsForward(neighbor, visited, list);
}
list.add(i);
}
public void dfsBackward(int i, boolean[] visited) {
if (visited[i]) return;
visited[i] = true;
for (int neighbor : bacw[i]) {
dfsBackward(neighbor, visited);
}
}
}
class LCAFinder {
/* O(n log n) Initialize: new LCAFinder(graph)
* O(log n) Queries: find(a,b) returns lowest common ancestor for nodes a and b */
int[] nodes;
int[] depths;
int[] entries;
int pointer;
FenwickMin fenwick;
public LCAFinder(List<Integer>[] graph) {
this.nodes = new int[(int)10e6];
this.depths = new int[(int)10e6];
this.entries = new int[graph.length];
this.pointer = 1;
boolean[] visited = new boolean[graph.length+1];
dfs(1, 0, graph, visited);
fenwick = new FenwickMin(pointer-1);
for (int i=1; i<pointer; i++) {
fenwick.set(i, depths[i] * 1000000L + i);
}
}
private void dfs(int node, int depth, List<Integer>[] graph, boolean[] visited) {
visited[node] = true;
entries[node] = pointer;
nodes[pointer] = node;
depths[pointer] = depth;
pointer++;
for (int neighbor : graph[node]) {
if (visited[neighbor]) continue;
dfs(neighbor, depth+1, graph, visited);
nodes[pointer] = node;
depths[pointer] = depth;
pointer++;
}
}
public int find(int a, int b) {
int left = entries[a];
int right = entries[b];
if (left > right) {
int temp = left;
left = right;
right = temp;
}
long mixedBag = fenwick.getMin(left, right);
int index = (int) (mixedBag % 1000000L);
return nodes[index];
}
}
/**************************** Geometry ****************************/
class Point {
int y;
int x;
public Point(int y, int x) {
this.y = y;
this.x = x;
}
}
boolean segmentsIntersect(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) {
// Returns true if segment 1-2 intersects segment 3-4
if (x1 == x2 && x3 == x4) {
// Both segments are vertical
if (x1 != x3) return false;
if (min(y1,y2) < min(y3,y4)) {
return max(y1,y2) >= min(y3,y4);
} else {
return max(y3,y4) >= min(y1,y2);
}
}
if (x1 == x2) {
// Only segment 1-2 is vertical. Does segment 3-4 cross it? y = a*x + b
double a34 = (y4-y3)/(x4-x3);
double b34 = y3 - a34*x3;
double y = a34 * x1 + b34;
return y >= min(y1,y2) && y <= max(y1,y2) && x1 >= min(x3,x4) && x1 <= max(x3,x4);
}
if (x3 == x4) {
// Only segment 3-4 is vertical. Does segment 1-2 cross it? y = a*x + b
double a12 = (y2-y1)/(x2-x1);
double b12 = y1 - a12*x1;
double y = a12 * x3 + b12;
return y >= min(y3,y4) && y <= max(y3,y4) && x3 >= min(x1,x2) && x3 <= max(x1,x2);
}
double a12 = (y2-y1)/(x2-x1);
double b12 = y1 - a12*x1;
double a34 = (y4-y3)/(x4-x3);
double b34 = y3 - a34*x3;
if (closeToZero(a12 - a34)) {
// Parallel lines
return closeToZero(b12 - b34);
}
// Non parallel non vertical lines intersect at x. Is x part of both segments?
double x = -(b12-b34)/(a12-a34);
return x >= min(x1,x2) && x <= max(x1,x2) && x >= min(x3,x4) && x <= max(x3,x4);
}
boolean pointInsideRectangle(Point p, List<Point> r, boolean countBorderAsInside) {
Point a = r.get(0);
Point b = r.get(1);
Point c = r.get(2);
Point d = r.get(3);
double apd = areaOfTriangle(a, p, d);
double dpc = areaOfTriangle(d, p, c);
double cpb = areaOfTriangle(c, p, b);
double pba = areaOfTriangle(p, b, a);
double sumOfAreas = apd + dpc + cpb + pba;
if (closeToZero(sumOfAreas - areaOfRectangle(r))) {
if (closeToZero(apd) || closeToZero(dpc) || closeToZero(cpb) || closeToZero(pba)) {
return countBorderAsInside;
}
return true;
}
return false;
}
double areaOfTriangle(Point a, Point b, Point c) {
return 0.5 * Math.abs((a.x-c.x)*(b.y-a.y)-(a.x-b.x)*(c.y-a.y));
}
double areaOfRectangle(List<Point> r) {
double side1xDiff = r.get(0).x - r.get(1).x;
double side1yDiff = r.get(0).y - r.get(1).y;
double side2xDiff = r.get(1).x - r.get(2).x;
double side2yDiff = r.get(1).y - r.get(2).y;
double side1 = Math.sqrt(side1xDiff * side1xDiff + side1yDiff * side1yDiff);
double side2 = Math.sqrt(side2xDiff * side2xDiff + side2yDiff * side2yDiff);
return side1 * side2;
}
boolean pointsOnSameLine(double x1, double y1, double x2, double y2, double x3, double y3) {
double areaTimes2 = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2);
return (closeToZero(areaTimes2));
}
class PointToLineSegmentDistanceCalculator {
// Just call this
double minDistFromPointToLineSegment(double point_x, double point_y, double x1, double y1, double x2, double y2) {
return Math.sqrt(distToSegmentSquared(point_x, point_y, x1, y1, x2, y2));
}
private double distToSegmentSquared(double point_x, double point_y, double x1, double y1, double x2, double y2) {
double l2 = dist2(x1,y1,x2,y2);
if (l2 == 0) return dist2(point_x, point_y, x1, y1);
double t = ((point_x - x1) * (x2 - x1) + (point_y - y1) * (y2 - y1)) / l2;
if (t < 0) return dist2(point_x, point_y, x1, y1);
if (t > 1) return dist2(point_x, point_y, x2, y2);
double com_x = x1 + t * (x2 - x1);
double com_y = y1 + t * (y2 - y1);
return dist2(point_x, point_y, com_x, com_y);
}
private double dist2(double x1, double y1, double x2, double y2) {
return Math.pow((x1 - x2), 2) + Math.pow((y1 - y2), 2);
}
}
/****************************** Math ******************************/
long pow(long base, int exp) {
if (exp == 0) return 1L;
long x = pow(base, exp/2);
long ans = x * x;
if (exp % 2 != 0) ans *= base;
return ans;
}
long gcd(long... v) {
/** Chained calls to Euclidean algorithm. */
if (v.length == 1) return v[0];
long ans = gcd(v[1], v[0]);
for (int i=2; i<v.length; i++) {
ans = gcd(ans, v[i]);
}
return ans;
}
long gcd(long a, long b) {
/** Euclidean algorithm. */
if (b == 0) return a;
return gcd(b, a%b);
}
int[] generatePrimesUpTo(int last) {
/* Sieve of Eratosthenes. Practically O(n). Values of 0 indicate primes. */
int[] div = new int[last+1];
for (int x=2; x<=last; x++) {
if (div[x] > 0) continue;
for (int u=2*x; u<=last; u+=x) {
div[u] = x;
}
}
return div;
}
long lcm(long a, long b) {
/** Least common multiple */
return a * b / gcd(a,b);
}
class BaseConverter {
/* Palauttaa luvun esityksen kannassa base */
public String convert(Long number, int base) {
return Long.toString(number, base);
}
/* Palauttaa luvun esityksen kannassa baseTo, kun annetaan luku Stringinä kannassa baseFrom */
public String convert(String number, int baseFrom, int baseTo) {
return Long.toString(Long.parseLong(number, baseFrom), baseTo);
}
/* Tulkitsee kannassa base esitetyn luvun longiksi (kannassa 10) */
public long longify(String number, int baseFrom) {
return Long.parseLong(number, baseFrom);
}
}
class BinomialCoefficients {
/** Total number of K sized unique combinations from pool of size N (unordered)
N! / ( K! (N - K)! ) */
/** For simple queries where output fits in long. */
public long biCo(long n, long k) {
long r = 1;
if (k > n) return 0;
for (long d = 1; d <= k; d++) {
r *= n--;
r /= d;
}
return r;
}
/** For multiple queries with same n, different k. */
public long[] precalcBinomialCoefficientsK(int n, int maxK) {
long v[] = new long[maxK+1];
v[0] = 1; // nC0 == 1
for (int i=1; i<=n; i++) {
for (int j=Math.min(i,maxK); j>0; j--) {
v[j] = v[j] + v[j-1]; // Pascal's triangle
}
}
return v;
}
/** When output needs % MOD. */
public long[] precalcBinomialCoefficientsK(int n, int k, long M) {
long v[] = new long[k+1];
v[0] = 1; // nC0 == 1
for (int i=1; i<=n; i++) {
for (int j=Math.min(i,k); j>0; j--) {
v[j] = v[j] + v[j-1]; // Pascal's triangle
v[j] %= M;
}
}
return v;
}
}
/**************************** Strings ****************************/
class Zalgo {
public int pisinEsiintyma(String haku, String kohde) {
char[] s = new char[haku.length() + 1 + kohde.length()];
for (int i=0; i<haku.length(); i++) {
s[i] = haku.charAt(i);
}
int j = haku.length();
s[j++] = '#';
for (int i=0; i<kohde.length(); i++) {
s[j++] = kohde.charAt(i);
}
int[] z = toZarray(s);
int max = 0;
for (int i=haku.length(); i<z.length; i++) {
max = Math.max(max, z[i]);
}
return max;
}
public int[] toZarray(char[] s) {
int n = s.length;
int[] z = new int[n];
int a = 0, b = 0;
for (int i = 1; i < n; i++) {
if (i > b) {
for (int j = i; j < n && s[j - i] == s[j]; j++) z[i]++;
}
else {
z[i] = z[i - a];
if (i + z[i - a] > b) {
for (int j = b + 1; j < n && s[j - i] == s[j]; j++) z[i]++;
a = i;
b = i + z[i] - 1;
}
}
}
return z;
}
public List<Integer> getStartIndexesWhereWordIsFound(String haku, String kohde) {
// this is alternative use case
char[] s = new char[haku.length() + 1 + kohde.length()];
for (int i=0; i<haku.length(); i++) {
s[i] = haku.charAt(i);
}
int j = haku.length();
s[j++] = '#';
for (int i=0; i<kohde.length(); i++) {
s[j++] = kohde.charAt(i);
}
int[] z = toZarray(s);
List<Integer> indexes = new ArrayList<>();
for (int i=haku.length(); i<z.length; i++) {
if (z[i] < haku.length()) continue;
indexes.add(i);
}
return indexes;
}
}
class StringHasher {
class HashedString {
long[] hashes;
long[] modifiers;
public HashedString(long[] hashes, long[] modifiers) {
this.hashes = hashes;
this.modifiers = modifiers;
}
}
long P;
long M;
public StringHasher() {
initializePandM();
}
HashedString hashString(String s) {
int n = s.length();
long[] hashes = new long[n];
long[] modifiers = new long[n];
hashes[0] = s.charAt(0);
modifiers[0] = 1;
for (int i=1; i<n; i++) {
hashes[i] = (hashes[i-1] * P + s.charAt(i)) % M;
modifiers[i] = (modifiers[i-1] * P) % M;
}
return new HashedString(hashes, modifiers);
}
/**
* Indices are inclusive.
*/
long getHash(HashedString hashedString, int startIndex, int endIndex) {
long[] hashes = hashedString.hashes;
long[] modifiers = hashedString.modifiers;
long result = hashes[endIndex];
if (startIndex > 0) result -= (hashes[startIndex-1] * modifiers[endIndex-startIndex+1]) % M;
if (result < 0) result += M;
return result;
}
// Less interesting methods below
/**
* Efficient for 2 input parameter strings in particular.
*/
HashedString[] hashString(String first, String second) {
HashedString[] array = new HashedString[2];
int n = first.length();
long[] modifiers = new long[n];
modifiers[0] = 1;
long[] firstHashes = new long[n];
firstHashes[0] = first.charAt(0);
array[0] = new HashedString(firstHashes, modifiers);
long[] secondHashes = new long[n];
secondHashes[0] = second.charAt(0);
array[1] = new HashedString(secondHashes, modifiers);
for (int i=1; i<n; i++) {
modifiers[i] = (modifiers[i-1] * P) % M;
firstHashes[i] = (firstHashes[i-1] * P + first.charAt(i)) % M;
secondHashes[i] = (secondHashes[i-1] * P + second.charAt(i)) % M;
}
return array;
}
/**
* Efficient for 3+ strings
* More efficient than multiple hashString calls IF strings are same length.
*/
HashedString[] hashString(String... strings) {
HashedString[] array = new HashedString[strings.length];
int n = strings[0].length();
long[] modifiers = new long[n];
modifiers[0] = 1;
for (int j=0; j<strings.length; j++) {
// if all strings are not same length, defer work to another method
if (strings[j].length() != n) {
for (int i=0; i<n; i++) {
array[i] = hashString(strings[i]);
}
return array;
}
// otherwise initialize stuff
long[] hashes = new long[n];
hashes[0] = strings[j].charAt(0);
array[j] = new HashedString(hashes, modifiers);
}
for (int i=1; i<n; i++) {
modifiers[i] = (modifiers[i-1] * P) % M;
for (int j=0; j<strings.length; j++) {
String s = strings[j];
long[] hashes = array[j].hashes;
hashes[i] = (hashes[i-1] * P + s.charAt(i)) % M;
}
}
return array;
}
void initializePandM() {
ArrayList<Long> modOptions = new ArrayList<>(20);
modOptions.add(353873237L);
modOptions.add(353875897L);
modOptions.add(353878703L);
modOptions.add(353882671L);
modOptions.add(353885303L);
modOptions.add(353888377L);
modOptions.add(353893457L);
P = modOptions.get(new Random().nextInt(modOptions.size()));
modOptions.clear();
modOptions.add(452940277L);
modOptions.add(452947687L);
modOptions.add(464478431L);
modOptions.add(468098221L);
modOptions.add(470374601L);
modOptions.add(472879717L);
modOptions.add(472881973L);
M = modOptions.get(new Random().nextInt(modOptions.size()));
}
}
int editDistance(String a, String b) {
a = "#"+a;
b = "#"+b;
int n = a.length();
int m = b.length();
int[][] dp = new int[n+1][m+1];
for (int y=0; y<=n; y++) {
for (int x=0; x<=m; x++) {
if (y == 0) dp[y][x] = x;
else if (x == 0) dp[y][x] = y;
else {
int e1 = dp[y-1][x] + 1;
int e2 = dp[y][x-1] + 1;
int e3 = dp[y-1][x-1] + (a.charAt(y-1) != b.charAt(x-1) ? 1 : 0);
dp[y][x] = min(e1, e2, e3);
}
}
}
return dp[n][m];
}
/*************************** Technical ***************************/
private class IO extends PrintWriter {
private InputStreamReader r;
private static final int BUFSIZE = 1 << 15;
private char[] buf;
private int bufc;
private int bufi;
private StringBuilder sb;
public IO() {
super(new BufferedOutputStream(System.out));
r = new InputStreamReader(System.in);
buf = new char[BUFSIZE];
bufc = 0;
bufi = 0;
sb = new StringBuilder();
}
/** Print, flush, return nextInt. */
private int queryInt(String s) {
io.println(s);
io.flush();
return nextInt();
}
/** Print, flush, return nextLong. */
private long queryLong(String s) {
io.println(s);
io.flush();
return nextLong();
}
/** Print, flush, return next word. */
private String queryNext(String s) {
io.println(s);
io.flush();
return next();
}
private void fillBuf() throws IOException {
bufi = 0;
bufc = 0;
while(bufc == 0) {
bufc = r.read(buf, 0, BUFSIZE);
if(bufc == -1) {
bufc = 0;
return;
}
}
}
private boolean pumpBuf() throws IOException {
if(bufi == bufc) {
fillBuf();
}
return bufc != 0;
}
private boolean isDelimiter(char c) {
return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
}
private void eatDelimiters() throws IOException {
while(true) {
if(bufi == bufc) {
fillBuf();
if(bufc == 0) throw new RuntimeException("IO: Out of input.");
}
if(!isDelimiter(buf[bufi])) break;
++bufi;
}
}
public String next() {
try {
sb.setLength(0);
eatDelimiters();
int start = bufi;
while(true) {
if(bufi == bufc) {
sb.append(buf, start, bufi - start);
fillBuf();
start = 0;
if(bufc == 0) break;
}
if(isDelimiter(buf[bufi])) break;
++bufi;
}
sb.append(buf, start, bufi - start);
return sb.toString();
} catch(IOException e) {
throw new RuntimeException("IO.next: Caught IOException.");
}
}
public int nextInt() {
try {
int ret = 0;
eatDelimiters();
boolean positive = true;
if(buf[bufi] == '-') {
++bufi;
if(!pumpBuf()) throw new RuntimeException("IO.nextInt: Invalid int.");
positive = false;
}
boolean first = true;
while(true) {
if(!pumpBuf()) break;
if(isDelimiter(buf[bufi])) {
if(first) throw new RuntimeException("IO.nextInt: Invalid int.");
break;
}
first = false;
if(buf[bufi] >= '0' && buf[bufi] <= '9') {
if(ret < -214748364) throw new RuntimeException("IO.nextInt: Invalid int.");
ret *= 10;
ret -= (int)(buf[bufi] - '0');
if(ret > 0) throw new RuntimeException("IO.nextInt: Invalid int.");
} else {
throw new RuntimeException("IO.nextInt: Invalid int.");
}
++bufi;
}
if(positive) {
if(ret == -2147483648) throw new RuntimeException("IO.nextInt: Invalid int.");
ret = -ret;
}
return ret;
} catch(IOException e) {
throw new RuntimeException("IO.nextInt: Caught IOException.");
}
}
public long nextLong() {
try {
long ret = 0;
eatDelimiters();
boolean positive = true;
if(buf[bufi] == '-') {
++bufi;
if(!pumpBuf()) throw new RuntimeException("IO.nextLong: Invalid long.");
positive = false;
}
boolean first = true;
while(true) {
if(!pumpBuf()) break;
if(isDelimiter(buf[bufi])) {
if(first) throw new RuntimeException("IO.nextLong: Invalid long.");
break;
}
first = false;
if(buf[bufi] >= '0' && buf[bufi] <= '9') {
if(ret < -922337203685477580L) throw new RuntimeException("IO.nextLong: Invalid long.");
ret *= 10;
ret -= (long)(buf[bufi] - '0');
if(ret > 0) throw new RuntimeException("IO.nextLong: Invalid long.");
} else {
throw new RuntimeException("IO.nextLong: Invalid long.");
}
++bufi;
}
if(positive) {
if(ret == -9223372036854775808L) throw new RuntimeException("IO.nextLong: Invalid long.");
ret = -ret;
}
return ret;
} catch(IOException e) {
throw new RuntimeException("IO.nextLong: Caught IOException.");
}
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
void print(Object output) {
io.println(output);
}
void done(Object output) {
print(output);
done();
}
void done() {
io.close();
throw new RuntimeException("Clean exit");
}
long min(long... v) {
long ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.min(ans, v[i]);
}
return ans;
}
double min(double... v) {
double ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.min(ans, v[i]);
}
return ans;
}
int min(int... v) {
int ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.min(ans, v[i]);
}
return ans;
}
long max(long... v) {
long ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.max(ans, v[i]);
}
return ans;
}
double max(double... v) {
double ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.max(ans, v[i]);
}
return ans;
}
int max(int... v) {
int ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.max(ans, v[i]);
}
return ans;
}
}
}
|
Java
|
["4 5\n3 2\n1 2\n.....\n.***.\n...**\n*....", "4 4\n2 2\n0 1\n....\n..*.\n....\n...."]
|
2 seconds
|
["10", "7"]
|
NoteCells, reachable in the corresponding example, are marked with '+'.First example: +++..+***.+++***+++. Second example: .++..+*..++..++.
|
Java 8
|
standard input
|
[
"shortest paths",
"graphs"
] |
cfdbe4bd1c9438de2d871768c546a580
|
The first line contains two integers n, m (1 ≤ n, m ≤ 2000) — the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0 ≤ x, y ≤ 109) — the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles.
| 1,800 |
Print exactly one integer — the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.
|
standard output
| |
PASSED
|
b41e756ecbe0b68434df957ca92fc687
|
train_000.jsonl
|
1539511500
|
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
|
512 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
ConsoleIO io = new ConsoleIO(new InputStreamReader(System.in), new PrintWriter(System.out));
// String fileName = "C-small-attempt0";
// ConsoleIO io = new ConsoleIO(new FileReader("D:\\Dropbox\\code\\practice\\jb\\src\\" + fileName + ".in"), new PrintWriter(new File("D:\\Dropbox\\code\\practice\\jb\\src\\" + fileName + ".out")));
new Main(io).solve();
// new Main(io).solveLocal();
io.close();
}
ConsoleIO io;
Main(ConsoleIO io) {
this.io = io;
}
ConsoleIO opt;
Main(ConsoleIO io, ConsoleIO opt) {
this.io = io;
this.opt = opt;
}
List<List<Integer>> gr = new ArrayList<>();
long MOD = 1_000_000_007;
class State{
public State(int r, int c, int rl, int rr){
row = r;
col = c;
remLeft = rl;
remRight = rr;
}
public int row;
public int col;
public int remLeft;
public int remRight;
}
int[] dr = {-1,0,1,0};
int[] dc = {0,-1,0,1};
int[] dleft = {0,-1,0,0};
int[] dright = {0,0,0,-1};
public void solve() {
int[] l = io.readIntArray();
int n = l[0], m = l[1];
l = io.readIntArray();
int sr = l[0], sc = l[1];
l = io.readIntArray();
int maxLeft = l[0], maxRight = l[1];
PriorityQueue<State> queue = new PriorityQueue<>((a, b) -> -Integer.compare(a.remLeft+a.remRight, b.remLeft + b.remRight));
boolean[][] visit = new boolean[n][m];
char[][] map = new char[n][];
for(int i = 0;i<n;i++){
map[i] = io.readLine().toCharArray();
}
int res = 1;
queue.add(new State(sr-1,sc-1, maxLeft, maxRight));
visit[sr-1][sc-1] = true;
while(queue.size() > 0){
State cur = queue.remove();
for(int e = 0;e <4;e++){
int r = cur.row+dr[e];
int c = cur.col+dc[e];
int left = cur.remLeft+dleft[e];
int right = cur.remRight+dright[e];
if(left>=0 && right>=0 && r>=0 && r<n && c>=0 && c<m && !visit[r][c] && map[r][c] == '.'){
queue.add(new State(r,c,left,right));
visit[r][c] = true;
res++;
}
}
}
io.writeLine(res+"");
}
}
class ConsoleIO {
BufferedReader br;
PrintWriter out;
public ConsoleIO(Reader reader, PrintWriter writer){br = new BufferedReader(reader);out = writer;}
public void flush(){this.out.flush();}
public void close(){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 void writeIntArray(int[] a, int k, String separator) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < k; i++) {
if (i > 0) sb.append(separator);
sb.append(a[i]);
}
this.writeLine(sb.toString());
}
public int read(char[] buf, int len){try {return br.read(buf,0,len);}catch (Exception ex){ return -1; }}
public String readLine() {try {return br.readLine();}catch (Exception ex){ return "";}}
public long[] readLongArray() {
String[]n=this.readLine().trim().split("\\s+");long[]r=new long[n.length];
for(int i=0;i<n.length;i++)r[i]=Long.parseLong(n[i]);
return r;
}
public int[] readIntArray() {
String[]n=this.readLine().trim().split("\\s+");int[]r=new int[n.length];
for(int i=0;i<n.length;i++)r[i]=Integer.parseInt(n[i]);
return r;
}
public int[] readIntArray(int n) {
int[] res = new int[n];
char[] all = this.readLine().toCharArray();
int cur = 0;boolean have = false;
int k = 0;
boolean neg = false;
for(int i = 0;i<all.length;i++){
if(all[i]>='0' && all[i]<='9'){
cur = cur*10+all[i]-'0';
have = true;
}else if(all[i]=='-') {
neg = true;
}
else if(have){
res[k++] = neg?-cur:cur;
cur = 0;
have = false;
neg = false;
}
}
if(have)res[k++] = neg?-cur:cur;
return res;
}
public int ri() {
try {
int r = 0;
boolean start = false;
boolean neg = false;
while (true) {
int c = br.read();
if (c >= '0' && c <= '9') {
r = r * 10 + c - '0';
start = true;
} else if (!start && c == '-') {
start = true;
neg = true;
} else if (start || c == -1) return neg ? -r : r;
}
} catch (Exception ex) {
return -1;
}
}
public long readLong() {
try {
long r = 0;
boolean start = false;
boolean neg = false;
while (true) {
int c = br.read();
if (c >= '0' && c <= '9') {
r = r * 10 + c - '0';
start = true;
} else if (!start && c == '-') {
start = true;
neg = true;
} else if (start || c == -1) return neg ? -r : r;
}
} catch (Exception ex) {
return -1;
}
}
public String readWord() {
try {
boolean start = false;
StringBuilder sb = new StringBuilder();
while (true) {
int c = br.read();
if (c!= ' ' && c!= '\r' && c!='\n' && c!='\t') {
sb.append((char)c);
start = true;
} else if (start || c == -1) return sb.toString();
}
} catch (Exception ex) {
return "";
}
}
public char readSymbol() {
try {
while (true) {
int c = br.read();
if (c != ' ' && c != '\r' && c != '\n' && c != '\t') {
return (char) c;
}
}
} catch (Exception ex) {
return 0;
}
}
//public char readChar(){try {return (char)br.read();}catch (Exception ex){ return 0; }}
}
class Pair {
public Pair(int a, int b) {this.a = a;this.b = b;}
public int a;
public int b;
}
class PairLL {
public PairLL(long a, long b) {this.a = a;this.b = b;}
public long a;
public long b;
}
class Triple {
public Triple(int a, int b, int c) {this.a = a;this.b = b;this.c = c;}
public int a;
public int b;
public int c;
}
|
Java
|
["4 5\n3 2\n1 2\n.....\n.***.\n...**\n*....", "4 4\n2 2\n0 1\n....\n..*.\n....\n...."]
|
2 seconds
|
["10", "7"]
|
NoteCells, reachable in the corresponding example, are marked with '+'.First example: +++..+***.+++***+++. Second example: .++..+*..++..++.
|
Java 8
|
standard input
|
[
"shortest paths",
"graphs"
] |
cfdbe4bd1c9438de2d871768c546a580
|
The first line contains two integers n, m (1 ≤ n, m ≤ 2000) — the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0 ≤ x, y ≤ 109) — the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles.
| 1,800 |
Print exactly one integer — the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.
|
standard output
| |
PASSED
|
b5d853252126d0d47d16c8ae971b3d12
|
train_000.jsonl
|
1539511500
|
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
|
512 megabytes
|
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.StringTokenizer;
public class Labyrinth implements Closeable {
private InputReader in = new InputReader(System.in);
private PrintWriter out = new PrintWriter(System.out);
public void solve() {
n = in.ni();
m = in.ni();
int r = in.ni() - 1, c = in.ni() - 1;
int left = in.ni(), right = in.ni();
grid = new char[n][m];
for (int i = 0; i < n; i++) {
grid[i] = in.next().toCharArray();
}
visited = new boolean[n][m];
bfs(r, c, left, right);
int result = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (visited[i][j]) {
result++;
}
}
}
out.println(result);
}
private int n, m;
private char[][] grid;
private boolean[][] visited;
private void bfs(int row, int col, int left, int right) {
ArrayDeque<State> queue = new ArrayDeque<>();
queue.add(new State(row, col, left, right));
while (!queue.isEmpty()) {
State top = queue.pollFirst();
if (visited[top.row][top.col]) continue;
int max = top.row;
for (int i = top.row; i < n; i++) {
if (grid[i][top.col] == '.') {
visited[i][top.col] = true;
max = i;
} else break;
}
int min = top.row;
for (int i = top.row; i >= 0; i--) {
if (grid[i][top.col] == '.') {
visited[i][top.col] = true;
min = i;
} else break;
}
for (int r = min; r <= max; r++) {
if (top.left > 0) {
int c = top.col - 1;
if (c >= 0 && grid[r][c] == '.') {
queue.add(new State(r, c, top.left - 1, top.right));
}
}
if (top.right > 0) {
int c = top.col + 1;
if (c < m && grid[r][c] == '.') {
queue.add(new State(r, c, top.left, top.right - 1));
}
}
}
}
}
private class State {
private int row, col, left, right;
private State(int row, int col, int left, int right) {
this.row = row;
this.col = col;
this.left = left;
this.right = right;
}
}
@Override
public void close() throws IOException {
in.close();
out.close();
}
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 ni() {
return Integer.parseInt(next());
}
public long nl() {
return Long.parseLong(next());
}
public void close() throws IOException {
reader.close();
}
}
public static void main(String[] args) throws IOException {
try (Labyrinth instance = new Labyrinth()) {
instance.solve();
}
}
}
|
Java
|
["4 5\n3 2\n1 2\n.....\n.***.\n...**\n*....", "4 4\n2 2\n0 1\n....\n..*.\n....\n...."]
|
2 seconds
|
["10", "7"]
|
NoteCells, reachable in the corresponding example, are marked with '+'.First example: +++..+***.+++***+++. Second example: .++..+*..++..++.
|
Java 8
|
standard input
|
[
"shortest paths",
"graphs"
] |
cfdbe4bd1c9438de2d871768c546a580
|
The first line contains two integers n, m (1 ≤ n, m ≤ 2000) — the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0 ≤ x, y ≤ 109) — the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles.
| 1,800 |
Print exactly one integer — the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.
|
standard output
| |
PASSED
|
4e28a34ba643c3aa73892b4c51df9e62
|
train_000.jsonl
|
1539511500
|
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
|
512 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.AbstractCollection;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.util.LinkedList;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author bacali
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
DLabyrinth solver = new DLabyrinth();
solver.solve(1, in, out);
out.close();
}
static class DLabyrinth {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int r = in.nextInt() - 1;
int c = in.nextInt() - 1;
int x = in.nextInt();
int y = in.nextInt();
char[][] tab = new char[n][];
for (int i = 0; i < n; i++) {
tab[i] = in.next().toCharArray();
}
LinkedList<DLabyrinth.obj> q = new LinkedList<>();
q.addLast(new DLabyrinth.obj(r, c, x, y));
int count = 0;
while (!q.isEmpty()) {
DLabyrinth.obj o = q.pollFirst();
if (tab[o.i][o.j] != '.') continue;
count++;
tab[o.i][o.j] = '+';
if (o.i - 1 >= 0 && tab[o.i - 1][o.j] == '.') {
q.addFirst(new DLabyrinth.obj(o.i - 1, o.j, o.x, o.y));
}
if (o.i + 1 < n && tab[o.i + 1][o.j] == '.') {
q.addFirst(new DLabyrinth.obj(o.i + 1, o.j, o.x, o.y));
}
if (o.x > 0 && o.j - 1 >= 0 && tab[o.i][o.j - 1] == '.') {
q.addLast(new DLabyrinth.obj(o.i, o.j - 1, o.x - 1, o.y));
}
if (o.y > 0 && o.j + 1 < m && tab[o.i][o.j + 1] == '.') {
q.addLast(new DLabyrinth.obj(o.i, o.j + 1, o.x, o.y - 1));
}
}
out.println(count);
}
static class obj {
int i;
int j;
int x;
int y;
public obj(int i, int j, int x, int y) {
this.i = i;
this.j = j;
this.x = x;
this.y = y;
}
public String toString() {
return "obj{" +
"i=" + i +
", j=" + j +
", x=" + x +
", y=" + y +
'}';
}
}
}
static class FastScanner {
private BufferedReader br;
private StringTokenizer st;
public FastScanner(InputStream inputStream) {
br = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
Java
|
["4 5\n3 2\n1 2\n.....\n.***.\n...**\n*....", "4 4\n2 2\n0 1\n....\n..*.\n....\n...."]
|
2 seconds
|
["10", "7"]
|
NoteCells, reachable in the corresponding example, are marked with '+'.First example: +++..+***.+++***+++. Second example: .++..+*..++..++.
|
Java 8
|
standard input
|
[
"shortest paths",
"graphs"
] |
cfdbe4bd1c9438de2d871768c546a580
|
The first line contains two integers n, m (1 ≤ n, m ≤ 2000) — the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0 ≤ x, y ≤ 109) — the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles.
| 1,800 |
Print exactly one integer — the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.
|
standard output
| |
PASSED
|
0977c712cfa049c19c61c61447731c38
|
train_000.jsonl
|
1539511500
|
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
|
512 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.AbstractCollection;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author dhairya
*/
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);
D solver = new D();
solver.solve(1, in, out);
out.close();
}
static class D {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int tr = in.nextInt();
int tc = in.nextInt();
int r = in.nextInt() - 1;
int c = in.nextInt() - 1;
int nl = in.nextInt();
int nr = in.nextInt();
String a[] = new String[tr];
Cust arr[][] = new Cust[tr][tc];
for (int i = 0; i < tr; i++) {
a[i] = in.next();
}
LinkedList<Cust> l = new LinkedList<>();
Cust curr = new Cust(r, c, nl, nr, false);
l.add(curr);
int visited[][] = new int[tr][tc];
for (int i = 0; i < tr; i++) {
for (int j = 0; j < tc; j++) {
arr[i][j] = new Cust(i, j, 0, 0, false);
if (a[i].charAt(j) == '*') {
visited[i][j] = -1;
arr[i][j].obst = true;
}
}
}
visited[r][c] = 1;
arr[r][c].nl = nl;
arr[r][c].nr = nr;
while (!l.isEmpty()) {
Cust p = l.pollFirst();
int ci = p.i;
int cj = p.j;
int cl = p.nl;
int cr = p.nr;
if (ci - 1 >= 0) {
if ((visited[ci - 1][cj] == 0 || arr[ci - 1][cj].nl < cl || arr[ci - 1][cj].nr < cr) && (cl >= 0 && cr >= 0 && visited[ci - 1][cj] != -1)) {
Cust np = new Cust(ci - 1, cj, cl, cr, false);
visited[ci - 1][cj] = 1;
arr[ci - 1][cj].nl = cl;
arr[ci - 1][cj].nr = cr;
l.add(np);
}
}
if (ci + 1 < tr) {
if ((visited[ci + 1][cj] == 0 || arr[ci + 1][cj].nl < cl || arr[ci + 1][cj].nr < cr) && (cl >= 0 && cr >= 0 && visited[ci + 1][cj] != -1)) {
Cust np = new Cust(ci + 1, cj, cl, cr, false);
visited[ci + 1][cj] = 1;
arr[ci + 1][cj].nl = cl;
arr[ci + 1][cj].nr = cr;
l.add(np);
}
}
if (cj - 1 >= 0) {
if ((visited[ci][cj - 1] == 0 || arr[ci][cj - 1].nl < (cl - 1) || arr[ci][cj - 1].nr < cr) && (cl - 1 >= 0 && cr >= 0 && visited[ci][cj - 1] != -1)) {
Cust np = new Cust(ci, cj - 1, cl - 1, cr, false);
visited[ci][cj - 1] = 1;
arr[ci][cj - 1].nl = cl - 1;
arr[ci][cj - 1].nr = cr;
l.add(np);
}
}
if (cj + 1 < tc) {
if ((visited[ci][cj + 1] == 0 || arr[ci][cj + 1].nl < cl || arr[ci][cj + 1].nr < (cr - 1)) && (cl >= 0 && cr - 1 >= 0 && visited[ci][cj + 1] != -1)) {
Cust np = new Cust(ci, cj + 1, cl, cr - 1, false);
visited[ci][cj + 1] = 1;
arr[ci][cj + 1].nl = cl;
arr[ci][cj + 1].nr = cr - 1;
l.add(np);
}
}
}
int tot = 0;
for (int i = 0; i < tr; i++) {
for (int j = 0; j < tc; j++) {
if (visited[i][j] == 1) {
tot++;
}
}
}
out.println(tot);
}
}
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 close() {
writer.close();
}
public void println(int i) {
writer.println(i);
}
}
static class Cust {
int i;
int j;
boolean obst;
int nl;
int nr;
Cust(int i, int j, int nl, int nr, boolean obst) {
this.i = i;
this.j = j;
this.nl = nl;
this.nr = nr;
this.obst = obst;
}
}
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);
}
}
}
|
Java
|
["4 5\n3 2\n1 2\n.....\n.***.\n...**\n*....", "4 4\n2 2\n0 1\n....\n..*.\n....\n...."]
|
2 seconds
|
["10", "7"]
|
NoteCells, reachable in the corresponding example, are marked with '+'.First example: +++..+***.+++***+++. Second example: .++..+*..++..++.
|
Java 8
|
standard input
|
[
"shortest paths",
"graphs"
] |
cfdbe4bd1c9438de2d871768c546a580
|
The first line contains two integers n, m (1 ≤ n, m ≤ 2000) — the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0 ≤ x, y ≤ 109) — the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles.
| 1,800 |
Print exactly one integer — the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.
|
standard output
| |
PASSED
|
8c8ea106d493a6ada40e5518cf668ef4
|
train_000.jsonl
|
1539511500
|
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
|
512 megabytes
|
import java.io.BufferedInputStream;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static int [] dx={1,0,-1,0};
static int [] dy={0,1,0,-1};
static int n,m,x,y;
static String[] map =new String[2005];
static int[][] vis =new int[2005][2005];
public static int bfs(int x1,int y1)
{
Comparator<node> cmp;///可以new一个重载器;
cmp = new Comparator<node>()
{
public int compare(node e1,node e2)
{
return (e1.ls+e1.rs) - (e2.ls+e2.rs);///重载优先级使其变为大根堆
}
};
Queue<node> q=new PriorityQueue<node>(cmp);
node a = new node(x1,y1,0,0);
q.offer(a);
int ans=1;
vis[x1][y1]=1;
while(q.size()!=0)
{
a=q.poll();
//System.out.println(a);
for(int i=0;i<4;i++)
{
node b=null;
if(i==1)
{
b=new node(a.x+dx[i],a.y+dy[i],a.ls,a.rs+1);
}
else if(i==3)
b=new node(a.x+dx[i],a.y+dy[i],a.ls+1,a.rs);
else
b=new node(a.x+dx[i],a.y+dy[i],a.ls,a.rs);
if(b.x>=0&&b.x<n&&b.y>=0&&b.y<m&&map[b.x].charAt(b.y)!='*'&&b.ls<=x&&b.rs<=y&&vis[b.x][b.y]==0)
{
ans++;
q.offer(b);
vis[b.x][b.y]=1;
}
}
}
return ans;
}
public static void main(String[] args) {
//Scanner in = new Scanner (new BufferedInputStream(System.in));
Scanner in = new Scanner(new BufferedInputStream(System.in));
n=in.nextInt();
m=in.nextInt();
int r=in.nextInt();
int c=in.nextInt();
r--;
c--;
x=in.nextInt();
y=in.nextInt();
in.nextLine();
for(int i=0;i<n;i++)
{
map[i]=new String();
map[i]=in.next();
}
int ans=bfs(r,c);
System.out.println(ans);
}
}
class node
{
int x,y,ls,rs;
public node(int x, int y, int ls, int rs) {
super();
this.x = x;
this.y = y;
this.ls = ls;
this.rs = rs;
}
}
|
Java
|
["4 5\n3 2\n1 2\n.....\n.***.\n...**\n*....", "4 4\n2 2\n0 1\n....\n..*.\n....\n...."]
|
2 seconds
|
["10", "7"]
|
NoteCells, reachable in the corresponding example, are marked with '+'.First example: +++..+***.+++***+++. Second example: .++..+*..++..++.
|
Java 8
|
standard input
|
[
"shortest paths",
"graphs"
] |
cfdbe4bd1c9438de2d871768c546a580
|
The first line contains two integers n, m (1 ≤ n, m ≤ 2000) — the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0 ≤ x, y ≤ 109) — the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles.
| 1,800 |
Print exactly one integer — the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.
|
standard output
| |
PASSED
|
67ceb4157bae310ec2b7aa4dc87bb185
|
train_000.jsonl
|
1539511500
|
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
|
512 megabytes
|
// TO LOVE IS TO KNOW WHAT'S YOUR WORTH. //
// Author :- Saurabh//
//BIT MESRA, RANCHI//
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class labyrinth {
static long ans=0; static int ar[][];static data vis[][];static int r,c,left,right;
static void Bolo_Jai_Mata_Di() {
n = ni();
m = ni();
r = ni();
c = ni();
left = ni();
right = ni();
tsc(); // starting time of execution
ar = new int[n + 2][m + 2];
for (int i = 1; i <= n; i++) {
char ch[] = ns().toCharArray();
for (int j = 0; j < m; j++) {
if (ch[j] == '.') ar[i][j + 1] = 1;
else ar[i][j + 1] = 2;
}
}
vis = new data[n + 2][m + 2];
for(int i=0;i<=n+1;i++){
for(int j=0;j<=m+1;j++)
vis[i][j]=new data();
}
Queue<data> q = new LinkedList<>();
q.add(new data(r, c, 0, 0));int temp=0;
while (!q.isEmpty()) {
//pl(q);
data d = q.poll();
//if(d.x==6 && d.y==9)temp++;
if (ar[d.x][d.y] != 1 || d.r > right || d.l > left) continue;
if(vis[d.x][d.y].x==1 && vis[d.x][d.y].l<=d.l && vis[d.x][d.y].r<=d.r)continue;
if(vis[d.x][d.y].x!=1)ans++;
vis[d.x][d.y].x = 1;vis[d.x][d.y].l=d.l;vis[d.x][d.y].r=d.r;
q.add(new data(d.x + 1, d.y, d.r, d.l));
q.add(new data(d.x - 1, d.y, d.r, d.l));
q.add(new data(d.x, d.y + 1, d.r + 1, d.l));
q.add(new data(d.x, d.y - 1, d.r, d.l + 1));
}
pl(ans);
//pl(temp);
// for (int i = 1; i <= n; i++) {
// for (int j = 1; j <= m; j++) p(vis[i][j].x);
// pl();
// }
// pl();
//
// for (int i = 1; i <= n; i++) {
// for (int j = 1; j <= m; j++) p(ar[i][j]);
// pl();
// }
// pl();
tec(); //ending time of execution
//pwt(); //prints the time taken to execute the program
flush();
}
static class data{
int x,y,l,r;
data(int x, int y, int r, int l){
this.l=l;this.r=r;this.x=x;this.y=y;
}
data(){
x=0;y=-1;l=r=Integer.MAX_VALUE;
}
public String toString(){
return "("+x+","+y+")";
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//THE DON'T CARE ZONE BEGINS HERE...//
static Calendar ts, te; //For time calculation
static int mod9 = 1000000007;
static int n, m, k, t, mod = 998244353;
static Lelo input = new Lelo(System.in);
static PrintWriter pw = new PrintWriter(System.out, true);
public static void main(String[] args) { //threading has been used to increase the stack size.
new Thread(null, null, "BlackRise", 1 << 25) //the last parameter is stack size desired.,
{
public void run() {
try {
Bolo_Jai_Mata_Di();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}.start();
}
static class Lelo { //Lelo class for fast input
private InputStream ayega;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public Lelo(InputStream ayega) {
this.ayega = ayega;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = ayega.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
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);
}
}
// functions to take input//
static int ni() {
return input.nextInt();
}
static long nl() {
return input.nextLong();
}
static double nd() {
return input.nextDouble();
}
static String ns() {
return input.readString();
}
//functions to give output
static void pl() {
pw.println();
}
static void p(Object o) {
pw.print(o + " ");
}
static void pws(Object o) {
pw.print(o + "");
}
static void pl(Object o) {
pw.println(o);
}
static void tsc() //calculates the starting time of execution
{
ts = Calendar.getInstance();
ts.setTime(new Date());
}
static void tec() //calculates the ending time of execution
{
te = Calendar.getInstance();
te.setTime(new Date());
}
static void pwt() //prints the time taken for execution
{
pw.printf("\nExecution time was :- %f s\n", (te.getTimeInMillis() - ts.getTimeInMillis()) / 1000.00);
}
static void flush() {
pw.flush();
pw.close();
}
static void sort(int ar[], int n) {
for (int i = 0; i < n; i++) {
int ran = (int) (Math.random() * n);
int temp = ar[i];
ar[i] = ar[ran];
ar[ran] = temp;
}
Arrays.sort(ar);
}
static void sort(long ar[], int n) {
for (int i = 0; i < n; i++) {
int ran = (int) (Math.random() * n);
long temp = ar[i];
ar[i] = ar[ran];
ar[ran] = temp;
}
Arrays.sort(ar);
}
static void sort(char ar[], int n) {
for (int i = 0; i < n; i++) {
int ran = (int) (Math.random() * n);
char temp = ar[i];
ar[i] = ar[ran];
ar[ran] = temp;
}
Arrays.sort(ar);
}
}
|
Java
|
["4 5\n3 2\n1 2\n.....\n.***.\n...**\n*....", "4 4\n2 2\n0 1\n....\n..*.\n....\n...."]
|
2 seconds
|
["10", "7"]
|
NoteCells, reachable in the corresponding example, are marked with '+'.First example: +++..+***.+++***+++. Second example: .++..+*..++..++.
|
Java 8
|
standard input
|
[
"shortest paths",
"graphs"
] |
cfdbe4bd1c9438de2d871768c546a580
|
The first line contains two integers n, m (1 ≤ n, m ≤ 2000) — the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0 ≤ x, y ≤ 109) — the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles.
| 1,800 |
Print exactly one integer — the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.
|
standard output
| |
PASSED
|
121d9656acd47c7290f68f2203ef9b0c
|
train_000.jsonl
|
1539511500
|
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
|
512 megabytes
|
/**
* BaZ :D
*/
import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class Main
{
static MyScanner scan;
static PrintWriter pw;
public static void main(String[] args) {
new Thread(null,null,"BaZ",1<<25)
{
public void run()
{
try
{
solve();
}
catch(Exception e)
{
e.printStackTrace();
System.exit(1);
}
}
}.start();
}
static void solve() throws IOException
{
scan = new MyScanner();
pw = new PrintWriter(System.out,true);
StringBuilder sb = new StringBuilder();
int n = ni(),m = ni();
char c[][] = new char[n][m];
int sx = ni()-1, sy = ni()-1;
int x = ni(), y = ni();
for(int i=0;i<n;++i) {
c[i] = ne().toCharArray();
}
int minleft[][] = new int[n][m];
for(int i=0;i<n;++i) {
Arrays.fill(minleft[i], -1);
}
PriorityQueue<Tuple> pq = new PriorityQueue<>();
boolean vis[][] = new boolean[n][m];
pq.add(new Tuple(sx,sy,0));
minleft[sx][sy] = 0;
int dx[] = {-1,1,0,0};
int dy[] = {0,0,1,-1};
while(!pq.isEmpty()) {
Tuple curr = pq.poll();
if(vis[curr.x][curr.y]) {
continue;
}
vis[curr.x][curr.y] = true;
for(int i=0;i<4;++i) {
int nx = curr.x + dx[i];
int ny = curr.y + dy[i];
int yahase = curr.dis;
if(i==3) {
yahase++;
}
if(nx>=0 && nx<n && ny>=0 && ny<m && c[nx][ny]=='.' && (minleft[nx][ny]==-1 || minleft[nx][ny]>yahase)) {
minleft[nx][ny] = yahase;
pq.add(new Tuple(nx, ny, minleft[nx][ny]));
}
}
}
int ans = 0;
for(int i=0;i<n;++i) {
for(int j=0;j<m;++j) {
if(minleft[i][j]==-1) {
continue;
}
int min_req = min(x, y+(sy-j));
if(minleft[i][j]<=min_req) {
++ans;
}
}
}
//pa("minleft", minleft);
pl(ans);
pw.flush();
pw.close();
}
static class Tuple implements Comparable<Tuple> {
int x,y,dis;
public Tuple(int x, int y, int dis) {
this.x = x;
this.y = y;
this.dis = dis;
}
public int compareTo(Tuple other) {
return this.dis - other.dis;
}
}
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()
{
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
|
["4 5\n3 2\n1 2\n.....\n.***.\n...**\n*....", "4 4\n2 2\n0 1\n....\n..*.\n....\n...."]
|
2 seconds
|
["10", "7"]
|
NoteCells, reachable in the corresponding example, are marked with '+'.First example: +++..+***.+++***+++. Second example: .++..+*..++..++.
|
Java 8
|
standard input
|
[
"shortest paths",
"graphs"
] |
cfdbe4bd1c9438de2d871768c546a580
|
The first line contains two integers n, m (1 ≤ n, m ≤ 2000) — the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0 ≤ x, y ≤ 109) — the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles.
| 1,800 |
Print exactly one integer — the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.
|
standard output
| |
PASSED
|
a02cc10c10eea5844bc5164f1f2ad1fc
|
train_000.jsonl
|
1539511500
|
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
|
512 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.ArrayDeque;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author prakharjain
*/
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);
_1064D solver = new _1064D();
solver.solve(1, in, out);
out.close();
}
static class _1064D {
int inf = 400000000;
int[][] dis;
char dot = '.';
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int r = in.nextInt();
int c = in.nextInt();
int x = in.nextInt();
int y = in.nextInt();
String[] mat = new String[n];
for (int i = 0; i < n; i++) {
mat[i] = in.next();
}
r--;
c--;
dis = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
dis[i][j] = inf;
}
}
bfs(r, c, mat, n, m);
int ans = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (mat[i].charAt(j) == dot) {
int mindis = Math.abs(j - c);
if (dis[i][j] == inf)
continue;
int adis = dis[i][j];
if (j <= c) {
int minx = c - j;
int miny = 0;
if (adis > mindis) {
minx += (adis - mindis) / 2;
miny += (adis - mindis) / 2;
}
if (minx <= x && miny <= y) {
//out.println(i + " " + j);
ans++;
}
} else {
int miny = j - c;
int minx = 0;
if (adis > mindis) {
minx += (adis - mindis) / 2;
miny += (adis - mindis) / 2;
}
if (minx <= x && miny <= y) {
//out.println(i + " " + j);
ans++;
}
}
}
}
}
out.println(ans);
}
void bfs(int sr, int sc, String[] mat, int n, int m) {
ArrayDeque<coord> dq = new ArrayDeque<>();
dq.addLast(new coord(sr, sc));
int[][] vis = new int[n][m];
vis[sr][sc] = 2;
dis[sr][sc] = 0;
while (dq.size() > 0) {
coord pc = dq.removeFirst();
int r = pc.x;
int c = pc.y;
if (vis[r][c] > 2)
continue;
if (r > 0 && mat[r - 1].charAt(c) == dot && vis[r - 1][c] < 2) {
vis[r - 1][c] = 2;
dis[r - 1][c] = dis[r][c];
dq.addFirst(new coord(r - 1, c));
}
if (r < n - 1 && mat[r + 1].charAt(c) == dot && vis[r + 1][c] < 2) {
vis[r + 1][c] = 2;
dis[r + 1][c] = dis[r][c];
dq.addFirst(new coord(r + 1, c));
}
if (c > 0 && mat[r].charAt(c - 1) == dot && vis[r][c - 1] == 0) {
vis[r][c - 1] = 1;
dis[r][c - 1] = dis[r][c] + 1;
dq.addLast(new coord(r, c - 1));
}
if (c < m - 1 && mat[r].charAt(c + 1) == dot && vis[r][c + 1] == 0) {
vis[r][c + 1] = 1;
dis[r][c + 1] = dis[r][c] + 1;
dq.addLast(new coord(r, c + 1));
}
vis[r][c] = 3;
}
}
class coord {
int x;
int y;
public coord(int x, int y) {
this.x = x;
this.y = y;
}
}
}
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 close() {
writer.close();
}
public void println(int i) {
writer.println(i);
}
}
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 static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
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 String next() {
return nextString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
Java
|
["4 5\n3 2\n1 2\n.....\n.***.\n...**\n*....", "4 4\n2 2\n0 1\n....\n..*.\n....\n...."]
|
2 seconds
|
["10", "7"]
|
NoteCells, reachable in the corresponding example, are marked with '+'.First example: +++..+***.+++***+++. Second example: .++..+*..++..++.
|
Java 8
|
standard input
|
[
"shortest paths",
"graphs"
] |
cfdbe4bd1c9438de2d871768c546a580
|
The first line contains two integers n, m (1 ≤ n, m ≤ 2000) — the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0 ≤ x, y ≤ 109) — the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles.
| 1,800 |
Print exactly one integer — the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.
|
standard output
| |
PASSED
|
bd584f2735f40e6d4b944ff880d9b002
|
train_000.jsonl
|
1539511500
|
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
|
512 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.ArrayDeque;
import java.util.Deque;
import java.util.InputMismatchException;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskX solver = new TaskX();
solver.solve(1, in, out);
out.close();
}
static class TaskX {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt(), m = in.nextInt();
int r = in.nextInt()-1, c = in.nextInt()-1;
int L = in.nextInt(), R = in.nextInt();
char[][] s = new char[n][m];
for (int i = 0; i < n; i++) {
s[i] = in.nextString().toCharArray();
}
int[] mh4 = { 0, -1, 1, 0 };
int[] mw4 = { -1, 0, 0, 1 };
boolean[][] used = new boolean[n][m];
Deque<P> q = new ArrayDeque<>();
q.add(new P(r, c, L, R));
used[r][c] = true;
while (!q.isEmpty()) {
P p = q.pollFirst();
int nr = p.r, nc = p.c;
for (int i = 0; i < 4; i++) {
int mr = nr + mh4[i];
int mc = nc + mw4[i];
if (mr < 0 || mc < 0 || mr >= n || mc >= m) continue;
if (used[mr][mc] || s[mr][mc] == '*') continue;
if (i == 0 && p.ml > 0) {
used[mr][mc] = true;
q.addLast(new P(mr, mc, p.ml-1, p.mr));
}
if (i == 1) {
used[mr][mc] = true;
q.addFirst(new P(mr, mc, p.ml, p.mr));
}
if (i == 2) {
used[mr][mc] = true;
q.addFirst(new P(mr, mc, p.ml, p.mr));
}
if (i == 3 && p.mr > 0) {
used[mr][mc] = true;
q.addLast(new P(mr, mc, p.ml, p.mr-1));
}
}
}
long ans = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (used[i][j]) ans++;
}
}
out.println(ans);
}
}
static class P {
int r, c, ml, mr;
public P(int r, int c, int ml, int mr) {
super();
this.r = r;
this.c = c;
this.ml = ml;
this.mr = mr;
}
@Override
public String toString() {
return "P [r=" + r + ", c=" + c + ", ml=" + ml + ", mr=" + mr + "]";
}
}
static class InputReader {
BufferedReader in;
StringTokenizer tok;
public String nextString() {
while (!tok.hasMoreTokens()) {
try {
tok = new StringTokenizer(in.readLine(), " ");
} catch (IOException e) {
throw new InputMismatchException();
}
}
return tok.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextString());
}
public long nextLong() {
return Long.parseLong(nextString());
}
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = nextInt();
}
return res;
}
public int[] nextIntArrayDec(int n) {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = nextInt() - 1;
}
return res;
}
public int[] nextIntArray1Index(int n) {
int[] res = new int[n + 1];
for (int i = 0; i < n; i++) {
res[i + 1] = nextInt();
}
return res;
}
public long[] nextLongArray(int n) {
long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = nextLong();
}
return res;
}
public long[] nextLongArrayDec(int n) {
long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = nextLong() - 1;
}
return res;
}
public long[] nextLongArray1Index(int n) {
long[] res = new long[n + 1];
for (int i = 0; i < n; i++) {
res[i + 1] = nextLong();
}
return res;
}
public double[] nextDoubleArray(int n) {
double[] res = new double[n];
for (int i = 0; i < n; i++) {
res[i] = nextDouble();
}
return res;
}
public InputReader(InputStream inputStream) {
in = new BufferedReader(new InputStreamReader(inputStream));
tok = new StringTokenizer("");
}
}
}
|
Java
|
["4 5\n3 2\n1 2\n.....\n.***.\n...**\n*....", "4 4\n2 2\n0 1\n....\n..*.\n....\n...."]
|
2 seconds
|
["10", "7"]
|
NoteCells, reachable in the corresponding example, are marked with '+'.First example: +++..+***.+++***+++. Second example: .++..+*..++..++.
|
Java 8
|
standard input
|
[
"shortest paths",
"graphs"
] |
cfdbe4bd1c9438de2d871768c546a580
|
The first line contains two integers n, m (1 ≤ n, m ≤ 2000) — the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0 ≤ x, y ≤ 109) — the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles.
| 1,800 |
Print exactly one integer — the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.
|
standard output
| |
PASSED
|
de53bd5498e8ae5e743742c24f660163
|
train_000.jsonl
|
1539511500
|
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
|
512 megabytes
|
import java.util.*;
import java.io.*;
public class Labyrinth {
static BufferedReader br;
static StringTokenizer tokenizer;
static int[] xOff = {0,0,-1,1};
static int[] yOff = {1,-1,0,0};
static int[] lOff = {0,0,-1,0};
static int[] rOff = {0,0,0,-1};
public static void main(String[] args) throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
int n,m,x,y,l,r;
n = nextInt(); m = nextInt();
boolean[][] passable = new boolean[n][m];
int ans = 0;
x = nextInt(); y = nextInt();
l = nextInt(); r = nextInt();
for(int i = 0; i < n; i++) {
char[] t = next().toCharArray();
for(int k = 0; k < m; k++)
passable[i][k] = (t[k] == '.');
}
PriorityQueue<State> max = new PriorityQueue<State>();
State start = new State(x - 1,y - 1,l,r);
max.add(start);
// System.out.println(max);
while(!max.isEmpty()) {
// System.out.println(ans);
State t = max.poll();
// System.out.println(t);
if(!passable[t.x][t.y] )
continue;
ans++;
passable[t.x][t.y]= false;
for(int i = 0; i < 4; i++) {
if(t.x + yOff[i] >= 0 && t.x + yOff[i] < n && t.y + xOff[i] >= 0 && t.y + xOff[i] < m &&
passable[t.x + yOff[i]][t.y + xOff[i]] && t.l + lOff[i] >= 0 && t.r + rOff[i] >= 0) {
max.add(new State(t.x + yOff[i], t.y + xOff[i],t.l + lOff[i], t.r + rOff[i]));
}
}
// System.out.println(max);
}
System.out.println(ans);
// for(boolean[] e: passable)
// System.out.println(Arrays.toString(e));
}
public static String next() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
String line = br.readLine();
if (line == null)
throw new IOException();
tokenizer = new StringTokenizer(line);
}
return tokenizer.nextToken();
}
public static int nextInt() throws IOException {
return Integer.parseInt(next());
}
}
class State implements Comparable<State> {
int x, y, l, r;
@Override
public int compareTo(State o) {
return o.r - r;
}
public State(int x, int y, int l, int r) {
super();
this.x = x;
this.y = y;
this.l = l;
this.r = r;
}
// public String toString() {
// return x + " " + y + " " + l + " " + r;
// }
}
|
Java
|
["4 5\n3 2\n1 2\n.....\n.***.\n...**\n*....", "4 4\n2 2\n0 1\n....\n..*.\n....\n...."]
|
2 seconds
|
["10", "7"]
|
NoteCells, reachable in the corresponding example, are marked with '+'.First example: +++..+***.+++***+++. Second example: .++..+*..++..++.
|
Java 8
|
standard input
|
[
"shortest paths",
"graphs"
] |
cfdbe4bd1c9438de2d871768c546a580
|
The first line contains two integers n, m (1 ≤ n, m ≤ 2000) — the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0 ≤ x, y ≤ 109) — the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles.
| 1,800 |
Print exactly one integer — the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.
|
standard output
| |
PASSED
|
a0d7400dfaec0fbf1f71a0e90ba30e1d
|
train_000.jsonl
|
1539511500
|
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
|
512 megabytes
|
//package CodeForces.Round516_div2;
import javafx.util.Pair;
import java.util.LinkedList;
import java.util.Scanner;
/**
* @Author: tianchengjiang
* @Date:2018/10/17
*/
public class problemD {
public static Scanner sc = new Scanner(System.in);
public static Integer n;
public static Integer m;
public static Character[][] map;
public static boolean vis[][];
public static Integer startx;
public static Integer starty;
public static Integer maxmleft;
public static Integer maxmright;
public static Integer[] dirx = new Integer[]{1,-1,0,0};
public static Integer[] diry = new Integer[]{0,0,1,-1};
public static void main(String[] args) {
while(sc.hasNext()){
init();
LinkedList<Pair<Pair<Integer,Integer>,Pair<Integer,Integer>>> list = new LinkedList();
list.offer(new Pair<>(new Pair<>(startx,starty),new Pair<>(0,0)));
int count = 0;
while(list.size() > 0){
Pair<Pair<Integer,Integer>,Pair<Integer,Integer>> top = list.pop();
int x = top.getKey().getKey();
int y = top.getKey().getValue();
int left = top.getValue().getKey();
int right = top.getValue().getValue();
if(left>maxmleft || right>maxmright || vis[x][y]!=false){
continue;
}
vis[x][y]=true;
count ++;
for(int i=0;i<4;i++){
int nextx = x + dirx[i];
int nexty = y + diry[i];
if(nextx>n || nextx<1 || nexty >m || nexty<1 || map[nextx][nexty]=='*') continue;
if(i==0 || i==1){
list.addFirst(new Pair<>(new Pair<>(nextx,nexty),new Pair<>(left,right)));
}else if(i==2){
list.addLast(new Pair<>(new Pair<>(nextx,nexty),new Pair<>(left,right+1)));
}else if(i==3){
list.addLast(new Pair<>(new Pair<>(nextx,nexty),new Pair<>(left+1,right)));
}
}
}
System.out.println(count);
}
}
public static void init(){
n = sc.nextInt();
m = sc.nextInt();
startx = sc.nextInt();
starty = sc.nextInt();
maxmleft = sc.nextInt();
maxmright = sc.nextInt();
map = new Character[n+1][m+1];
vis = new boolean[n+1][m+1];
for(int i=1;i<=n;i++){
String str = sc.next();
for(int j=1;j<=m;j++){
map[i][j] = str.charAt(j-1);
vis[i][j] = false;
}
}
}
}
|
Java
|
["4 5\n3 2\n1 2\n.....\n.***.\n...**\n*....", "4 4\n2 2\n0 1\n....\n..*.\n....\n...."]
|
2 seconds
|
["10", "7"]
|
NoteCells, reachable in the corresponding example, are marked with '+'.First example: +++..+***.+++***+++. Second example: .++..+*..++..++.
|
Java 8
|
standard input
|
[
"shortest paths",
"graphs"
] |
cfdbe4bd1c9438de2d871768c546a580
|
The first line contains two integers n, m (1 ≤ n, m ≤ 2000) — the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0 ≤ x, y ≤ 109) — the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles.
| 1,800 |
Print exactly one integer — the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.
|
standard output
| |
PASSED
|
e91e795c55d91c86376c5feb1ab03fe3
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
/**
* 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);
TaskD solver = new TaskD();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
int[] t = new int[n];
Set<Integer> types = new HashSet<>();
for (int i = 0; i < t.length; i++) {
t[i] = in.nextInt();
types.add(t[i]);
}
if (types.size() == 1) {
out.println(1);
for (int i = 0; i < n; i++) {
out.print(1 + " ");
}
out.println();
return;
}
if (n % 2 == 0) {
out.println(2);
for (int i = 0; i < n; i++) {
out.print(i % 2 + 1 + " ");
}
out.println();
return;
}
int id = -1;
for (int i = 1; i < n; i++) {
if (t[i - 1] == t[i]) {
id = i;
break;
}
}
if (id != -1 || t[0] == t[n - 1]) {
out.println(2);
int prev = 0;
for (int i = 0; i < n; i++) {
if (i == id) {
out.print(prev + 1 + " ");
} else {
prev = 1 - prev;
out.print(prev + 1 + " ");
}
}
out.println();
} else {
out.println(3);
for (int i = 0; i < n - 1; i++) {
out.print(i % 2 + 1 + " ");
}
out.println(3);
}
}
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
ff1535f905ccf4ba4070df6e9c11906d
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class CF1328D {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int q = Integer.parseInt(br.readLine());
for (int i = 0; i < q; i++) {
int n = Integer.parseInt(br.readLine());
int [] types = new int[n+1];
StringTokenizer s = new StringTokenizer(br.readLine());
for (int j = 1; j <= n; j++) {
types[j] = Integer.parseInt(s.nextToken());
}
int [] res = new int[n+1];
res[1] = 1;
boolean hasTwoInRow = false;
int numDistinctColors = 1;
for (int j = 2; j <= n; j++) {
if (types[j] == types[j-1]) {
res[j] = res[j-1];
hasTwoInRow = true;
}
else {
res[j] = (res[j-1] == 1 ? 2 : 1);
numDistinctColors = 2;
}
}
if (res[n] == res[1] && types[n] != types[1]) {
res[n] = 3;
numDistinctColors = 3;
}
if (numDistinctColors == 3 && hasTwoInRow) {
boolean hasModifiedTwoInRow = false;
for (int j = 2; j <= n; j++) {
if (types[j] == types[j-1]) {
if (!hasModifiedTwoInRow) {
res[j] = (res[j-1] == 1 ? 2 : 1);
hasModifiedTwoInRow = true;
}
else {
res[j] = res[j-1];
}
}
else {
res[j] = (res[j-1] == 1 ? 2 : 1);
}
}
numDistinctColors = 2;
}
System.out.println(numDistinctColors);
for (int j = 1; j <= n; j++) {
System.out.print(res[j]+" ");
}
System.out.println();
}
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
6d78a305c756938efa2b2e661a19b55a
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
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 unknown
*/
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);
DCarousel solver = new DCarousel();
solver.solve(1, in, out);
out.close();
}
static class DCarousel {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int ntc = in.nextInt();
while ((ntc--) > 0) {
int n = in.nextInt();
int[] arr = new int[n + 2];
HashSet<Integer> hs = new HashSet<>();
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
hs.add(arr[i]);
}
arr[n] = arr[0];
arr[n + 1] = arr[1];
int[] colors = new int[n + 2];
boolean pairFound = false;
if (n % 2 == 0 || hs.size() == 1) {
for (int i = 0; i < n; i++) {
if (i % 2 == 0 || hs.size() == 1) {
colors[i] = 1;
} else {
colors[i] = 2;
}
}
} else {
int color = 0;
for (int i = 0; i <= n; i++) {
if (arr[i] == arr[i + 1] && !pairFound) {
pairFound = true;
colors[i] = 1 + color;
} else {
colors[i] = 1 + color;
color ^= 1;
}
}
if (!pairFound) {
colors[0] = 3;
} else {
colors[0] = colors[n];
}
}
if (hs.size() == 1) {
out.println(1);
} else if (pairFound || n % 2 == 0) {
out.println(2);
} else {
out.println(3);
}
for (int i = 0; i < n; i++) {
out.print(colors[i] + " ");
}
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 boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; ++i) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println() {
writer.println();
}
public void close() {
writer.close();
}
public void println(long i) {
writer.println(i);
}
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
3cb532da3f4858ff2c938b39d1c414b4
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Solve8 {
public static void main(String[] args) throws IOException {
PrintWriter pw = new PrintWriter(System.out);
new Solve8().solve(pw);
pw.flush();
pw.close();
}
public void solve(PrintWriter pw) throws IOException {
FastReader sc = new FastReader();
int t = sc.nextInt();
l:
while (t-- > 0) {
n = sc.nextInt();
a = new int[n];
boolean f = false;
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
if (i > 0 && a[i] != a[i - 1]) {
f = true;
}
}
if (!f) {
pw.println(1);
for (int j = 0; j < n; j++) {
pw.print(1 + (j + 1 == n ? "\n" : " "));
}
continue l;
}
b = new int[n];
for (int i = 1; i <= 2; i++) {
b[0] = i;
if (dfs(1)) {
pw.println(2);
for (int j = 0; j < n; j++) {
pw.print(b[j] + (j + 1 == n ? "\n" : " "));
}
continue l;
}
}
pw.println(3);
for (int i = 0; i < n; i++) {
if (i % 2 == 0) {
b[i] = 1;
} else {
b[i] = 2;
}
}
b[n - 1] = 3;
for (int j = 0; j < n; j++) {
pw.print(b[j] + (j + 1 == n ? "\n" : " "));
}
}
}
int n;
int[] a, b;
public boolean dfs(int i) {
if (i == n) {
if (a[0] != a[n - 1]) {
return b[0] != b[n - 1];
}
return true;
}
for (int j = 1; j <= 2; j++) {
if (a[i] != a[i - 1] && b[i - 1] == j) {
continue;
}
b[i] = j;
if (dfs(i + 1)) {
return true;
}
}
return false;
}
public long[] input(int n, FastReader sc) {
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextLong();
}
return a;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
}
}
public String next() {
if (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
}
return null;
}
public boolean hasNext() throws IOException {
if (st != null && st.hasMoreTokens()) {
return true;
}
String s = br.readLine();
if (s == null || s.isEmpty()) {
return false;
}
st = new StringTokenizer(s);
return true;
}
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
01e96e5791fccd3163350d98ef6399a2
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Solve8 {
public static void main(String[] args) throws IOException {
PrintWriter pw = new PrintWriter(System.out);
new Solve8().solve(pw);
pw.flush();
pw.close();
}
public void solve(PrintWriter pw) throws IOException {
FastReader sc = new FastReader();
int t = sc.nextInt();
l:
while (t-- > 0) {
n = sc.nextInt();
a = new int[n];
boolean f = false;
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
if (i > 0 && a[i] != a[i - 1]) {
f = true;
}
}
if (!f) {
pw.println(1);
for (int j = 0; j < n; j++) {
pw.print(1 + (j + 1 == n ? "\n" : " "));
}
continue l;
}
b = new int[n];
_2dDP(n, 3);
for (int i = 1; i <= 2; i++) {
b[0] = i;
if (dp(1, i) == 1) {
pw.println(2);
for (int j = 0; j < n; j++) {
pw.print(b[j] + (j + 1 == n ? "\n" : " "));
}
continue l;
}
}
pw.println(3);
for (int i = 0; i < n; i++) {
if (i % 2 == 0) {
b[i] = 1;
} else {
b[i] = 2;
}
}
b[n - 1] = 3;
for (int j = 0; j < n; j++) {
pw.print(b[j] + (j + 1 == n ? "\n" : " "));
}
}
}
int n;
int[] a, b;
long[][] dp;
public long dp(int i, int prev) {
if (i == n) {
if (a[0] != a[n - 1]) {
return b[0] != b[n - 1] ? 1 : 0;
}
return 1;
}
if (dp[i][prev] != -1) {
return dp[i][prev];
}
for (int j = 1; j <= 2; j++) {
if (a[i] != a[i - 1] && b[i - 1] == j) {
continue;
}
b[i] = j;
if (dp(i + 1, j) == 1) {
return dp[i][prev] = 1;
}
}
return dp[i][prev] = 0;
}
public void _2dDP(int n, int m) {
dp = new long[n][m];
for (long[] row : dp) {
Arrays.fill(row, -1);
}
}
public boolean dfs(int i) {
if (i == n) {
if (a[0] != a[n - 1]) {
return b[0] != b[n - 1];
}
return true;
}
for (int j = 1; j <= 2; j++) {
if (a[i] != a[i - 1] && b[i - 1] == j) {
continue;
}
b[i] = j;
if (dfs(i + 1)) {
return true;
}
}
return false;
}
public long[] input(int n, FastReader sc) {
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextLong();
}
return a;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
}
}
public String next() {
if (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
}
return null;
}
public boolean hasNext() throws IOException {
if (st != null && st.hasMoreTokens()) {
return true;
}
String s = br.readLine();
if (s == null || s.isEmpty()) {
return false;
}
st = new StringTokenizer(s);
return true;
}
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
8e6649f8353cf0e959097301f9fa954c
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import java.util.*;
public class D {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
StringBuilder sb = new StringBuilder();
for (int r = 0; r < t; r++) {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
int[] ans = new int[n];
boolean is1 = true;
int isDouble = -1;
for (int i = 1; i < n; i++) {
if (a[i] != a[i - 1]) {
is1 = false;
} else {
isDouble = i;
}
}
if (!is1) {
for (int i = 0; i < n; i += 2) {
ans[i] = 1;
}
for (int i = 1; i < n; i += 2) {
ans[i] = 2;
}
if(n%2==0) {
sb.append("2\n");
}else {
if(isDouble!=-1) {
sb.append("2\n");
for(int i=isDouble;i<n;i++) {
ans[i]=3-ans[i];
}
}else {
if(a[n-1]!=a[0]) {
sb.append("3\n");
ans[n-1]=3;
}else
sb.append("2\n");
}
}
} else {
sb.append("1\n");
for(int i=0;i<n;i++) {
ans[i]=1;
}
}
for(int i=0;i<n;i++) {
sb.append(ans[i]+" ");
}
sb.append("\n");
}
System.out.print(sb);
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
db6fc76489bff6d908d49cb99dc2ccd7
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import javafx.util.Pair;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class D {
public static void solve(int testCase, Reader in, PrintWriter out){
int n = in.nextInt();
int []ar = new int[n];
for(int i = 0;i<n;i++) {
ar[i] = in.nextInt();
}
int [] ans = new int[n];
int mx = 1;
ans[0] = 1;
for(int i = 1;i<n;i++) {
if(i==n-1) {
if(ar[i] == ar[i-1] ) {
ans[i] = ans[i-1];
if(ar[i] != ar[0]) {
if(ans[i]==ans[0]) {
ans[i] = 2;
mx = 2;
}
}
continue;
}
if(ar[0] == ar[i]) {
ans[i] = ans[0];
if(ar[i] != ar[i-1] && ans[i] == ans[i-1]) {
ans[i]++;
mx = 2;
}
continue;
}
if(ans[0] == ans[n-2] ) {
ans[i] = 2;
mx = 2;
} else {
ans[i] = 3;
mx = 3;
}
} else {
if(ar[i]==ar[i-1]) {
ans[i] = ans[i-1];
} else {
if(ans[i-1]==1) {
ans[i] = 2;
mx = 2;
} else {
ans[i] = 1;
}
}
}
}
if(mx==3) {
int ind = -1;
for (int i = n - 2; i >= 1; i--) {
if (ar[i] == ar[i - 1]) {
ind = i;
if (ans[i] == 1) {
ans[i] = 2;
} else {
ans[i] = 1;
}
break;
}
}
if (ind != -1) {
for (int i = ind + 1; i < n - 1; i++) {
if (ans[i] == 1) {
ans[i] = 2;
} else {
ans[i] = 1;
}
}
ans[n-1] = 2;
mx = 2;
}
}
out.println(mx);
for(int i = 0;i<n;i++) {
if(i>0) out.print(" ");
out.print(ans[i]);
}
out.println();
out.flush();
}
public static void main(String... args) {
Reader in = new Reader();
PrintWriter out = new PrintWriter(System.out);
int testCase = in.nextInt();
for(int i = 1;i<=testCase;i++) {
solve(i, in, out);
}
out.close();
}
static class Reader {
private StringTokenizer tokenizer;
private BufferedReader reader;
public Reader() {
tokenizer = null;
try {
reader = new BufferedReader(new InputStreamReader(System.in)); // for file IO, replace this with new FileReader ("in.txt")
} catch (Exception e) {
e.printStackTrace();
}
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return tokenizer.nextToken();
}
public int nextInt() { return Integer.parseInt(this.next()); }
public long nextLong() { return Long.parseLong(this.next()); }
public double nextDouble() { return Double.parseDouble(this.next()); }
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
2ab80aa023b7b772d2813d815b466639
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import java.math.*;
import java.io.*;
import java.util.*;
import java.awt.*;
public class Main implements Runnable {
@Override
public void run() {
try {
new Solver().solve();
System.exit(0);
} catch (Exception | Error e) {
e.printStackTrace();
System.exit(1);
}
}
public static void main(String[] args) {
//new Thread(null, new Main(), "Solver", 1l << 25).start();
new Main().run();
}
}
class Solver {
final Helper hp;
final int MAXN = 1000_006;
final long MOD = (long) 1e9 + 7;
final Timer timer;
final TimerTask task;
Solver() {
hp = new Helper(MOD, MAXN);
hp.initIO(System.in, System.out);
timer = new Timer();
task = new TimerTask() {
@Override
public void run() {
try {
hp.flush();
System.exit(0);
} catch (Exception e) {
}
}
};
//timer.schedule(task, 4700);
}
void solve() throws Exception {
int i, j, k;
boolean testCases = true;
int tc = testCases ? hp.nextInt() : 1;
for (int tce = 1; tce <= tc; tce++) {
N = hp.nextInt();
A = hp.getIntArray(N);
int[] ans = new int[N];
if (hp.max(A) == hp.min(A)) {
Arrays.fill(ans, 1);
} else {
for (i = 0; i < N; ++i) ans[i] = i % 3 + 1;
if (ans[0] == ans[N - 1]) ans[N - 1] = 2;
C = new int[N];
Arrays.fill(C, -7);
C[0] = 1;
mem = new int[3][N];
if (fill(1)) ans = C.clone();
}
hp.println(hp.max(ans));
hp.println(hp.joinElements(ans));
}
timer.cancel();
hp.flush();
}
int N;
int[] A, C;
int[][] mem;
boolean fill(int idx) {
if (idx >= N) return true;
int leftCol = C[idx - 1];
if (mem[leftCol][idx] > 0) return mem[leftCol][idx] == 1;
if (canPut(idx, 1)) {
C[idx] = 1;
if (fill(idx + 1)) {
mem[leftCol][idx] = 1;
return true;
}
}
if (canPut(idx, 2)) {
C[idx] = 2;
if (fill(idx + 1)) {
mem[leftCol][idx] = 1;
return true;
}
}
C[idx] = -7;
mem[leftCol][idx] = 2;
return false;
}
boolean canPut(int idx, int col) {
int left = (idx - 1 + N) % N, right = (idx + 1) % N;
if (A[left] != A[idx] && C[left] == col) return false;
if (A[right] != A[idx] && C[right] == col) return false;
return true;
}
}
class Helper {
final long MOD;
final int MAXN;
final Random rnd;
public Helper(long mod, int maxn) {
MOD = mod;
MAXN = maxn;
rnd = new Random();
}
public static int[] sieve;
public static ArrayList<Integer> primes;
public void setSieve() {
primes = new ArrayList<>();
sieve = new int[MAXN];
int i, j;
for (i = 2; i < MAXN; ++i)
if (sieve[i] == 0) {
primes.add(i);
for (j = i; j < MAXN; j += i) {
sieve[j] = i;
}
}
}
public static long[] factorial;
public void setFactorial() {
factorial = new long[MAXN];
factorial[0] = 1;
for (int i = 1; i < MAXN; ++i) factorial[i] = factorial[i - 1] * i % MOD;
}
public long getFactorial(int n) {
if (factorial == null) setFactorial();
return factorial[n];
}
public long ncr(int n, int r) {
if (r > n) return 0;
if (factorial == null) setFactorial();
long numerator = factorial[n];
long denominator = factorial[r] * factorial[n - r] % MOD;
return numerator * pow(denominator, MOD - 2, MOD) % MOD;
}
public long[] getLongArray(int size) throws Exception {
long[] ar = new long[size];
for (int i = 0; i < size; ++i) ar[i] = nextLong();
return ar;
}
public int[] getIntArray(int size) throws Exception {
int[] ar = new int[size];
for (int i = 0; i < size; ++i) ar[i] = nextInt();
return ar;
}
public String[] getStringArray(int size) throws Exception {
String[] ar = new String[size];
for (int i = 0; i < size; ++i) ar[i] = next();
return ar;
}
public String joinElements(long... ar) {
StringBuilder sb = new StringBuilder();
for (long itr : ar) sb.append(itr).append(" ");
return sb.toString().trim();
}
public String joinElements(int... ar) {
StringBuilder sb = new StringBuilder();
for (int itr : ar) sb.append(itr).append(" ");
return sb.toString().trim();
}
public String joinElements(String... ar) {
StringBuilder sb = new StringBuilder();
for (String itr : ar) sb.append(itr).append(" ");
return sb.toString().trim();
}
public String joinElements(Object... ar) {
StringBuilder sb = new StringBuilder();
for (Object itr : ar) sb.append(itr).append(" ");
return sb.toString().trim();
}
public long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
public int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
public long max(long... ar) {
long ret = ar[0];
for (long itr : ar) ret = Math.max(ret, itr);
return ret;
}
public int max(int... ar) {
int ret = ar[0];
for (int itr : ar) ret = Math.max(ret, itr);
return ret;
}
public long min(long... ar) {
long ret = ar[0];
for (long itr : ar) ret = Math.min(ret, itr);
return ret;
}
public int min(int... ar) {
int ret = ar[0];
for (int itr : ar) ret = Math.min(ret, itr);
return ret;
}
public long sum(long... ar) {
long sum = 0;
for (long itr : ar) sum += itr;
return sum;
}
public long sum(int... ar) {
long sum = 0;
for (int itr : ar) sum += itr;
return sum;
}
public void shuffle(int[] ar) {
int r;
for (int i = 0; i < ar.length; ++i) {
r = rnd.nextInt(ar.length);
if (r != i) {
ar[i] ^= ar[r];
ar[r] ^= ar[i];
ar[i] ^= ar[r];
}
}
}
public void shuffle(long[] ar) {
int r;
for (int i = 0; i < ar.length; ++i) {
r = rnd.nextInt(ar.length);
if (r != i) {
ar[i] ^= ar[r];
ar[r] ^= ar[i];
ar[i] ^= ar[r];
}
}
}
public void reverse(int[] ar) {
int r;
for (int i = 0; i < ar.length; ++i) {
r = ar.length - 1 - i;
if (r > i) {
ar[i] ^= ar[r];
ar[r] ^= ar[i];
ar[i] ^= ar[r];
}
}
}
public void reverse(long[] ar) {
int r;
for (int i = 0; i < ar.length; ++i) {
r = ar.length - 1 - i;
if (r > i) {
ar[i] ^= ar[r];
ar[r] ^= ar[i];
ar[i] ^= ar[r];
}
}
}
public long pow(long base, long exp, long MOD) {
base %= MOD;
long ret = 1;
while (exp > 0) {
if ((exp & 1) == 1) ret = ret * base % MOD;
base = base * base % MOD;
exp >>= 1;
}
return ret;
}
static final int BUFSIZE = 1 << 20;
static byte[] buf;
static int index, total;
static InputStream in;
static BufferedWriter bw;
public void initIO(InputStream is, OutputStream os) {
try {
in = is;
bw = new BufferedWriter(new OutputStreamWriter(os));
buf = new byte[BUFSIZE];
} catch (Exception e) {
}
}
public void initIO(String inputFile, String outputFile) {
try {
in = new FileInputStream(inputFile);
bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outputFile)));
buf = new byte[BUFSIZE];
} catch (Exception e) {
}
}
private int scan() throws Exception {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0)
return -1;
}
return buf[index++];
}
public String next() throws Exception {
int c;
for (c = scan(); c <= 32; c = scan()) ;
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan())
sb.append((char) c);
return sb.toString();
}
public int nextInt() throws Exception {
int c, val = 0;
for (c = scan(); c <= 32; c = scan()) ;
boolean neg = c == '-';
if (c == '-' || c == '+')
c = scan();
for (; c >= '0' && c <= '9'; c = scan())
val = (val << 3) + (val << 1) + (c & 15);
return neg ? -val : val;
}
public long nextLong() throws Exception {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan()) ;
boolean neg = c == '-';
if (c == '-' || c == '+')
c = scan();
for (; c >= '0' && c <= '9'; c = scan())
val = (val << 3) + (val << 1) + (c & 15);
return neg ? -val : val;
}
public void print(Object a) throws Exception {
bw.write(a.toString());
}
public void printsp(Object a) throws Exception {
print(a);
print(" ");
}
public void println() throws Exception {
bw.write("\n");
}
public void println(Object a) throws Exception {
print(a);
println();
}
public void flush() throws Exception {
bw.flush();
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
b316e6f0c010c0e2e1ea274f47b923f1
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class Cf131 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 Cf131(),"Main",1<<27).start();
}
static class Pair
{
int z;
int o;
Pair(int z,int o)
{
this.z=z;
this.o=o;
}
}
static class Edge implements Comparable<Edge>
{
int end, wght;
public Edge(int end, int wght)
{
this.end = end;
this.wght = wght;
}
public int compareTo(Edge edge)
{
return this.wght - edge.wght;
}
}
public void run()
{
InputReader sc = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int t= sc.nextInt();
while(t-->0){
int n= sc.nextInt();
Integer[] a = new Integer[n];
int unitype = 0;
HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
for(int i=0;i<n;i++){
a[i] = sc.nextInt();
int x = hm.getOrDefault(a[i],0);
if(x==0)unitype++;
hm.put(a[i],x+1);
}
if(unitype>1){
if(n%2==0){
w.println("2 ");
for(int i=0;i<n;i++){
if(i%2==0)w.print("1 ");
else w.print("2 ");
}
}
else{
// w.println("f");
// w.println(a[n-1]+" "+a[0]);
if((a[n-1]-a[0])==0){
// w.println("f");
w.println("2");
for(int i=0;i<n;i++){
if(i!=n-1){
if(i%2==0)w.print("1 ");
else w.print("2 ");
}
else{
w.print("1 ");
}
}
}
else if((a[n-1]-a[n-2])==0){
w.println("2 ");
for(int i=0;i<n;i++){
if(i!=n-1){
if(i%2==0)w.print("1 ");
else w.print("2 ");
}
else{
w.print("2 ");
}
}
}
else{
int p = -1;
for(int i=0;i<n;i++){
if((a[i]-a[(i+1)%n])==0){p=i;break;}
}
if(p==-1){
w.println("3 ");
for(int i=0;i<n;i++){
if(i!=n-1){
if(i%2==0)w.print("1 ");
else w.print("2 ");
}
else{
w.print("3 ");
}
}
}
else{
// w.println("s"+p);
w.println("2");
for(int i=0;i<n;i++){
if(i<=p){
if(i%2==0)
w.print("1 ");
else
w.print("2 ");
}
else{
if(i%2==0)
w.print("2 ");
else
w.print("1 ");
}
}
}
}
}
}
else{
w.println("1 ");
for(int i=0;i<n;i++)w.print("1 ");
}
w.println();
}
w.flush();
w.close();
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
46c6efd2504ee506ba223fa14ee593ec
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class CF1328D extends PrintWriter {
CF1328D() { super(System.out); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1328D o = new CF1328D(); o.main(); o.flush();
}
void main() {
int q = sc.nextInt();
while (q-- > 0) {
int n = sc.nextInt();
int[] aa = new int[n];
for (int i = 0; i < n; i++)
aa[i] = sc.nextInt();
boolean same = true;
for (int i = 1; i < n; i++)
if (aa[i] != aa[0]) {
same = false;
break;
}
if (same) {
println(1);
for (int i = 0; i < n; i++)
print(1 + " ");
println();
continue;
}
if (n % 2 == 0 || aa[0] == aa[n - 1]) {
println(2);
for (int i = 0; i < n; i++)
print(i % 2 + 1 + " ");
println();
} else {
int i_ = -1;
for (int i = 0; i + 1 < n; i++)
if (aa[i] == aa[i + 1]) {
i_ = i;
break;
}
if (i_ == -1) {
println(3);
for (int i = 0; i + 1 < n; i++)
print(i % 2 + 1 + " ");
println(3);
} else {
println(2);
int a = 1;
for (int i = 0; i < n; i++) {
print(a + " ");
if (i != i_)
a = 3 - a;
}
println();
}
}
}
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
ad7cff586eae61ce30fa6cc94c58bfd9
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Unstoppable solver = new Unstoppable();
int t=in.nextInt();
while(t-->0)
solver.solve(in, out);
out.close();
}
static class Unstoppable {
public void solve(InputReader in, PrintWriter out) {
int n=in.nextInt();
int flag=0;
int tlag=0,temp=0;
int a[]=new int[n];
int b[]=new int[n]; b[0]=0;
int c[]=new int[n]; c[0]=0;
for(int i=0;i<n;i++) a[i]=in.nextInt();
for(int i=1;i<n;i++)
{
if(a[i]==a[i-1]) b[i]=b[i-1];
else{ flag=1; b[i]=1-b[i-1]; }
}
if(n>2&&a[0]!=a[n-1]&&b[0]==b[n-1]){ if(b[n-1]==b[n-2]) b[n-1]=1-b[n-2]; else{ b[n-1]=2; flag++; } }
for(int i=1;i<n;i++)
{
if(a[i]==a[i-1]){ if(temp==0) { temp=1; tlag=1; c[i]=1-c[i-1]; } else c[i]=c[i-1]; }
else{ tlag=1; c[i]=1-c[i-1]; }
}
if(n>2&&a[0]!=a[n-1]&&c[0]==c[n-1]){ if(c[n-1]==c[n-2]) c[n-1]=1-c[n-2]; else{ c[n-1]=2; tlag++; } }
if(flag<tlag){
out.println(flag+1);
for(int i=0;i<n;i++) out.print((b[i]+1)+" "); out.println("");
}
else {
out.println(tlag+1);
for(int i=0;i<n;i++) out.print((c[i]+1)+" "); out.println("");
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong(){
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
b80d4144b7ff74f8460be3f3fc4e5d2e
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import java.io.*;
import java.text.*;
import java.util.*;
import java.math.*;
public class D {
public void run() throws Exception {
FastScanner f = new FastScanner();
int t = f.nextInt();
while(t-->0) {
int n = f.nextInt();
int[] animals = new int[n];
int[] colors = new int[n];
for(int i = 0; i < animals.length; i++) {
animals[i] = f.nextInt();
}
int numColors = 1;
int c = 1;
int extra = 0;
colors[0] = c;
for(int i = 1; i < animals.length; i++) {
if(animals[i-1] != animals[i])
c = 3-c;
else
extra++;
colors[i] = c;
numColors = Math.max(numColors, c);
}
if(animals[0] != animals[n-1] && colors[0] == colors[n-1]) {
if(animals[n-1] != animals[n-2]) {
if(extra>0) {
boolean flip = false;
for(int i = 1; i < animals.length; i++) {
if(animals[i] == animals[i-1]) {
flip = true;
}
if(flip) colors[i] = 3-colors[i];
}
} else {
colors[n-1] = 3;
numColors = 3;
}
} else {
colors[n-1] = 3-c;
}
}
System.out.println(numColors);
for(int i = 0; i < n; i++)
System.out.print(colors[i] + " ");
System.out.println();
}
}
static class FastScanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastScanner() {
reader = new BufferedReader(new InputStreamReader(System.in), 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 double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public static void main(String[] args) throws Exception {
new D().run();
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
5cae924c1988663af45ea5b71dc9f041
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class gym{
static int[][][]memo;
static int n;
static int dp(int i,int start,int prev) {
if(i>=n)return 0;
if(memo[i][start][prev]!=-1)return memo[i][start][prev];
if(i==n-1) {
for(int c=1;c<=3;c++) {
if(in[i]!=in[i-1] && c==prev)continue;
if(in[i]!=in[0] && c==start)continue;
return memo[i][start][prev]=c;
}
}
int ans=4;
for(int c=1;c<=3;c++) {
if(in[i]!=in[i-1] && c==prev)continue;
ans=Math.min(ans, Math.max(c, dp(i+1,start,c)));
}
return memo[i][start][prev]=ans;
}
static int[]ans;
static void trace(int i,int start,int prev) {
if(i>=n)return;
int min=dp(i,start,prev);
if(i==n-1) {
for(int c=1;c<=3;c++) {
if(in[i]!=in[i-1] && c==prev)continue;
if(in[i]!=in[0] && c==start)continue;
ans[i]=c;
return;
}
}
for(int c=1;c<=3;c++) {
if(in[i]!=in[i-1] && c==prev)continue;
if(min==Math.max(c, dp(i+1,start,c))) {
ans[i]=c;
trace(i+1,start,c);
return;
}
}
}
static int[]in;
public static void main(String[] args) throws Exception{
MScanner sc=new MScanner(System.in);
PrintWriter pw=new PrintWriter(System.out);
int tc=sc.nextInt();
while(tc-->0) {
n=sc.nextInt();
in=sc.intArr(n);
ans=new int[n];
memo=new int[n][4][4];
for(int[][]i:memo) {
for(int []j:i) {
Arrays.fill(j, -1);
}
}
int min=4;int col=-1;
for(int c=1;c<=3;c++) {
int cur=Math.max(c,dp(1,c,c));
if(cur<min) {
min=cur;col=c;
}
}
ans[0]=col;
trace(1,col,col);
pw.println(min);
for(int i:ans)pw.print(i+" ");
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 int[] intArr(int n) throws IOException {
int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public long[] longArr(int n) throws IOException {
long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public int[] intSortedArr(int n) throws IOException {
int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
shuffle(in);
Arrays.sort(in);
return in;
}
public long[] longSortedArr(int n) throws IOException {
long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
shuffle(in);
Arrays.sort(in);
return in;
}
static void shuffle(int[]in) {
for(int i=0;i<in.length;i++) {
int idx=(int)(Math.random()*in.length);
int tmp=in[i];
in[i]=in[idx];
in[idx]=tmp;
}
}
static void shuffle(long[]in) {
for(int i=0;i<in.length;i++) {
int idx=(int)(Math.random()*in.length);
long tmp=in[i];
in[i]=in[idx];
in[idx]=tmp;
}
}
public Integer[] IntegerArr(int n) throws IOException {
Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public Long[] LongArr(int n) throws IOException {
Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
static void addX(int[]in,int x) {
for(int i=0;i<in.length;i++)in[i]+=x;
}
static void addX(long[]in,int x) {
for(int i=0;i<in.length;i++)in[i]+=x;
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
8728f2656e62fbba5e1e89986fed345a
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
DCarousel solver = new DCarousel();
solver.solve(1, in, out);
out.close();
}
static class DCarousel {
public void solve(int testNumber, Scanner sc, PrintWriter pw) {
int q = sc.nextInt();
loop:
while (q-- > 0) {
int n = sc.nextInt();
int[] arr = new int[n];
int idx = -1;
boolean one = true;
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
if (i > 0) {
if (arr[i] == arr[i - 1])
idx = i;
else
one = false;
}
}
int[] ans = new int[n];
if (one) {
pw.println(1);
for (int i = 0; i < n; i++)
pw.print(1 + " ");
continue loop;
}
int c = 1;
for (int i = 0; i < n; i++) {
ans[i] = c;
c = 3 - c;
}
if (ans[0] == ans[n - 1] && arr[0] != arr[n - 1]) {
if (idx == -1) {
ans[n - 1] = 3;
pw.println(3);
} else {
c = ans[idx];
for (int i = idx; i < n; i++) {
c = 3 - c;
ans[i] = c;
}
pw.println(2);
}
} else
pw.println(2);
for (int x : ans)
pw.print(x + " ");
pw.println();
}
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
92e5b68392af1ee822e8a37d2a8d309d
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import java.util.*;
public final class Carousel {
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();
int[] animal = new int[n];
for (int j = 0; j < n; j++) {
animal[j] = sc.nextInt();
}
int[] ans = new int[n];
ans[0] = 0;
int count = 1;
for (int j = 1; j < n; j++) {
if(animal[j - 1] != animal[j]) {
ans[j] = ans[j - 1] == 0 ? 1 : 0;
if(ans[j] == 1)
count = 2;
}
else
ans[j] = ans[j - 1];
}
if(animal[n - 1] != animal[0] && ans[n - 1] == ans[0]) {
int repeatIndex = -1;
for (int j = 0; j < n - 1 && repeatIndex == -1; j++) {
if(animal[j] == animal[j + 1])
repeatIndex = j;
}
if(repeatIndex != -1) {
for (int j = 0; j <= repeatIndex; j++) {
ans[j] = ans[j] == 0 ? 1 : 0;
}
}
else {
ans[n - 1] = 2;
count = 3;
}
}
System.out.println(count);
for (int j = 0; j < n ; j++) {
System.out.print((ans[j] + 1) + " ");
}
System.out.println();
}
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
4374029fb19f61f706e0141607d4474b
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class P4 implements Runnable
{
public static void main(String args[]) throws Exception
{
new Thread(null, new P4(),"P4",1<<27).start();
}
public void run()
{
InputReader sc = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int t=sc.nextInt();
while(t-->0){
int n=sc.nextInt();
int[] a=new int[n];
boolean flag=true;
a[0]=sc.nextInt();
for (int i=1;i<n;++i) {
a[i]=sc.nextInt();
if (a[i]!=a[i-1]) {
flag=false;
}
}
if (flag) {
w.println("1");
for (int i=0;i<n;++i) {
w.print("1 ");
}
}
else{
if (n%2==1 && a[0]!=a[n-1]) {
int mi=-1;
for (int i=1;i<n;++i) {
if (a[i]==a[i-1]) {
flag=true;
mi=i;
break;
}
}
if (flag) {
w.println("2");
for (int i=0;i<mi;++i) {
if (i%2==0) {
w.print("1 ");
}
else{w.print("2 ");}
}
if(mi%2==0){
w.print("2 ");
}
else{
w.print("1 ");
}
for (int i=mi+1;i<n;++i) {
if (i%2==1) {
w.print("1 ");
}
else{w.print("2 ");}
}
}
else{
w.println("3");
for (int i=0;i<n-1;++i) {
if (i%2==0) {
w.print("1 ");
}
else{w.print("2 ");}
}
w.print("3");
}
}
else{
w.println(2);
for (int i=0;i<n;++i) {
if (i%2==0) {
w.print("1 ");
}
else{
w.print("2 ");
}
}
}
}
w.println("");
System.out.flush();
}
w.close();
}
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
// if modulo is required set value accordingly
public static long[][] matrixMultiply2dL(long t[][],long m[][])
{
long res[][]= new long[t.length][m[0].length];
for(int i=0;i<t.length;i++)
{
for(int j=0;j<m[0].length;j++)
{
res[i][j]=0;
for(int k=0;k<t[0].length;k++)
{
res[i][j]+=t[i][k]+m[k][j];
}
}
}
return res;
}
static void Seive(){
int temp=1000001;
boolean[] flag=new boolean[temp];
Arrays.fill(flag,true);
flag[0]=false;
flag[1]=false;
for (int i=2;i<=Math.sqrt(temp);++i) {
if (flag[i]) {
for (int j=2;i*j<temp;++j) {
flag[i*j]=false;
}
}
}
}
static long combination(long n,long r)
{
long ans=1;
for(long i=0;i<r;i++)
{
ans=(ans*(n-i))/(i+1);
}
return ans;
}
// **just change the name of class from Main to reuquired**
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
2a4734bf6a36574313d8325c05176b03
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import java.util.Scanner;
public class Carousel {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int cases = scanner.nextInt();
for (int c = 1; c <= cases; c++) {
solve();
}
}
private static void solve() {
int n = scanner.nextInt();
int[] types = new int[n];
int[] colors = new int[n];
int currentColor = 0;
int max = 1;
for (int i = 0; i < n; i++) {
int current = scanner.nextInt();
types[i] = current;
if (i > 0 && current != types[i - 1]) {
currentColor = (currentColor + 1) % 2;
}
max = Math.max(max, currentColor + 1);
colors[i] = currentColor;
}
if (colors[n - 1] == colors[0] && types[n - 1] != types[0]) {
int index = n;
for (int i = n - 1; i > 0 && index == n; i--) {
if (colors[i] == colors[i - 1]) {
index = i;
}
}
for (int i = index; i < n; i++) {
colors[i] = (colors[i] + 1) % 2;
}
if (index == n) {
colors[n - 1] = 2;
max = 3;
}
}
System.out.println(max);
for (int c : colors) {
System.out.print((c + 1) + " ");
}
System.out.println();
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
19f45d24fd99310be48b0a36a24e49fa
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
/**
* @author egaeus
* @mail [email protected]
* @veredict
* @url
* @category
* @date
**/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static java.lang.Integer.parseInt;
public class CFD {
static int arr[];
public static void main(String args[]) throws Throwable {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int T = parseInt(in.readLine());
StringBuilder sb = new StringBuilder();
for (int t = 0; t < T; t++) {
int N = parseInt(in.readLine());
arr = new int[N];
StringTokenizer st = new StringTokenizer(in.readLine());
mem = new int[N][3][3][];
TreeSet<Integer> set = new TreeSet<>();
int[] result = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = parseInt(st.nextToken());
set.add(arr[i]);
}
if (set.size() == 1) {
Arrays.fill(result, 1);
sb.append("1").append("\n");
} else {
sb.append(f(1, 0, 0) + 1).append("\n");
result[0] = 1;
int p = 1, c = 0, max = 0;
for (; p < arr.length; p++) {
if (mem[p][c][max][1] != -1) {
c = mem[p][c][max][1];
max = Math.max(max, c);
}
result[p] = c + 1;
}
}
sb.append(IntStream.of(result).mapToObj(a -> a + "").collect(Collectors.joining(" "))).append("\n");
}
System.out.print(new String(sb));
}
static int[][][][] mem;
static int f(int p, int c, int max) {
if (p == arr.length) {
if (arr[0] != arr[arr.length - 1] && c == 0)
return Integer.MAX_VALUE;
return max;
}
if (mem[p][c][max] != null)
return mem[p][c][max][0];
int min = Integer.MAX_VALUE, mov = 0;
if (arr[p - 1] == arr[p]) {
min = f(p + 1, c, max);
mov = -1;
}
for (int i = 0; i < 3; i++)
if (c != i && min > f(p + 1, i, Math.max(i, max))) {
mov = i;
min = f(p + 1, i, Math.max(i, max));
}
mem[p][c][max] = new int[]{min, mov};
return min;
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
97fe3415ee15edfd5a8094ae1272bafd
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import java.util.Scanner;
public class carousel {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int q = sc.nextInt();
StringBuilder finAns = new StringBuilder();
while (--q >= 0) {
StringBuilder ans = new StringBuilder();
int n = sc.nextInt(), t[] = new int[n], flag = 0;
for (int i = 0; i < n; i++) {
t[i] = sc.nextInt();
if (t[i] != t[0])
flag = 1;
}
if (flag == 0) {
ans.append("1\n");
for (int i = 0; i < n; i++)
ans.append("1 ");
} else {
if (n % 2 == 0) {
ans.append("2\n");
for (int i = 0; i < n / 2; i++)
ans.append("1 2 ");
} else {
flag = 0;
if (t[0] == t[n - 1]) {
ans.append("2\n");
ans.append("1 ");
for (int i = 1; i < n - 1; i++) {
ans.append((i % 2) + 1 + " ");
}
flag = 1;
ans.append(1);
} else {
for (int i = 0; i < n - 1; i++) {
if (t[i] == t[i + 1]) {
for (int j = 0; j <= i; j++)
ans.append(((j % 2) + 1) + " ");
for (int j = (i + 1); j < n; j++)
ans.append((((j - 1) % 2) + 1) + " ");
ans.insert(0, "2\n");
flag = 1;
break;
}
}
}
if (flag == 0) {
ans.append("3\n");
for (int i = 0; i < n - 1; i++) {
ans.append(((i % 2) + 1) + " ");
}
ans.append("3");
}
}
}
finAns.append(ans + "\n");
}
sc.close();
System.out.print(finAns);
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
986c71d00781a470aa3cec05cca33368
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import java.util.*;
public class Carousel{
public static void main(String[] args){
Scanner sc= new Scanner(System.in);
int t= sc.nextInt();
while(t-->0){
int n= sc.nextInt();
int[] type= new int[n];
for(int i=0;i<n;i++){
type[i]= sc.nextInt();
}
boolean same= true;
int[] group= null;
for(int i=1;i<n;i++){
if(type[i]==type[i-1]){
group= new int[2];
group[0]=i-1;
group[1]=i;
}
else{
same=false;
}
}
if(same){
System.out.println("1");
for(int i=0;i<n;i++){
System.out.print("1 ");
}
System.out.println();
continue;
}
if(n%2==0){
System.out.println("2");
for(int i=0;i<n/2;i++){
System.out.print("1 2 ");
}
System.out.println();
continue;
}
int count=-1;
if(group==null){
if(type[n-1]==type[0]) count=2;
else count=3;
System.out.println(count);
for(int i=0;i<(n-1)/2;i++){
System.out.print("1 2 ");
}
if(count==3) System.out.print("3");
else System.out.print("1");
System.out.println();
}
else{
System.out.println(2);
int cur=2;
for(int i=0;i<=group[0];i++){
cur= ((cur-1)^1)+1;
System.out.print(cur+" ");
}
for(int i=group[1];i<n;i++){
System.out.print(cur+" ");
cur= ((cur-1)^1)+1;
}
System.out.println();
}
}
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
3cd5a01fddd21193f8dcb8a0db802b7a
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import java.util.*;
import java.lang.*;
import java.io.*;
import java.text.*;
/* Name of the class has to be "Main" only if the class is public*/
public class D
{
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;
}
}
static class Node {
long pp;
long a, b;
Node(long x, long y) {
a = x;
b = y;
pp = a * b;
}
}
static class Comp implements Comparator<Node> {
public int compare(Node o1, Node o2) {
if (o1.pp > o2.pp) {
return 1;
} else {
return -1;
}
}
}
static int gcd(int x, int y)
{
if(y==0) return x;
else return gcd(y,x%y);
}
public static void main(String[] args) {
FastReader sc=new FastReader();
PrintWriter out=new PrintWriter(System.out);
//your code starts here
int t = sc.nextInt();
while (t-- > 0) {
int N = sc.nextInt(), flag = 1;
int arr[] = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = sc.nextInt();
if (i != 0) {
if (arr[i] != arr[0])
flag = 0;
}
}
if (flag == 1) {
out.println(1);
for (int i = 0; i < N; i++) out.print(1 + " ");
out.println();
continue;
}
if (N%2==0) {
out.println(2);
for (int i = 0; i < N; i++){
if(i%2==0)
out.print(1 + " ");
else
out.print(2 + " ");
}
out.println();
continue;
}
int index=-1;
for(int i =0;i<N;i++){
if(arr[i]==arr[(i+1 )%N]){
index=i;
break;
}
}
if(index==-1){
out.println(3);
for (int i = 0; i < N-1; i++){
if(i%2==0)
out.print(1 + " ");
else
out.print(2 + " ");
}
out.println(3);
}
else
{
out.println(2);
int a[]=new int[N]; int j=0;
for(int i =0;i<N;i++) {
if (i == index + 1)
continue;
if (j % 2 == 0)
a[i] = 1;
else
a[i] = 2;
if(i==index){
a[(i+1)%N]=a[i];
}
j++;
}
for (int i = 0; i < N; i++)
out.print(a[i] + " ");
out.println();
}
}
out.close();
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
a148674e7bccdd88e76b38086767bede
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class HelloWorld{
public static void main(String []args)throws IOException{
BufferedReader re = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
int t = Integer.parseInt(re.readLine());
while(t-->0){
int n = Integer.parseInt(re.readLine()), a[] = new int[n];
StringTokenizer tk = new StringTokenizer(re.readLine());
for(int i=0; i<n; i++)
a[i] = Integer.parseInt(tk.nextToken());
boolean res = true;
for(int i=1; i<n; i++)
if(a[i] != a[0]) res = false;
if(res){
pw.println(+1);
for(int i=0; i<n; i++)
pw.print(+1+" ");
pw.println();
}
else{
if(n%2 == 0){
pw.println(+2);
for(int i=0; i<n; i+=2)
pw.print(+1+" "+2+" ");
pw.println();
}
else{
int pos = -1;
for(int i=0; i<n; i++){
if(a[i] == a[(i+1)%n])
pos = i;
}
if(pos != -1){
int r[] = new int[n];
r[pos] = 1;
r[(pos+1)%n] = 1;
for(int i=(pos+2)%n, j=0; j<n-2; i=(i+1)%n, j++){
if(j%2 == 0) r[i] = 2;
else r[i] = 1;
}
pw.println(+2);
for(int z : r)
pw.print(+z+" ");
pw.println();
}
else{
pw.println(+3);
for(int i=0; i<n-1; i++){
if(i%2 == 0) pw.print(+1+" ");
else pw.print(+2+" ");
}
pw.println(+3);
}
}
}
}
pw.flush();
pw.close();
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
d6a941b2affd28165dc989347cc85720
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf1328d {
public static void main(String[] args) throws IOException {
int t = ri();
while(t --> 0) {
int n = ri(), c[] = ria(n), ans[] = new int[n];
boolean all = true;
for(int i = 1; i < n; ++i) {
if(c[i] != c[i - 1]) {
all = false;
break;
}
}
if(all) {
for(int i = 0; i < n; ++i) {
ans[i] = 1;
}
prln(1);
prln(ans);
} else if(c[0] == c[n - 1] || n % 2 == 0) {
for(int i = 0; i < n; ++i) {
ans[i] = 2 - (i % 2);
}
prln(2);
prln(ans);
} else {
boolean same = false;
ans[0] = 1;
for(int i = 1; i < n; ++i) {
if(c[i] != c[i - 1] || same) {
ans[i] = 1 + ans[i - 1] % 2;
} else {
same = true;
ans[i] = ans[i - 1];
}
}
if(!same) {
ans[n - 1] = 3;
prln(3);
prln(ans);
} else {
prln(2);
prln(ans);
}
}
}
close();
}
static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));
static StringTokenizer input;
static Random rand = new Random();
// references
// IBIG = 1e9 + 7
// IRAND ~= 3e8
// IMAX ~= 2e10
// LMAX ~= 9e18
// constants
static final int IBIG = 1000000007;
static final int IRAND = 327859546;
static final int IMAX = 2147483647;
static final int IMIN = -2147483648;
static final long LMAX = 9223372036854775807L;
static final long LMIN = -9223372036854775808L;
// util
static int minof(int a, int b, int c) {return min(a, min(b, c));}
static int minof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));}
static int minstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));}
static long minof(long a, long b, long c) {return min(a, min(b, c));}
static long minof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));}
static long minstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));}
static int maxof(int a, int b, int c) {return max(a, max(b, c));}
static int maxof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));}
static int maxstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));}
static long maxof(long a, long b, long c) {return max(a, max(b, c));}
static long maxof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));}
static long maxstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));}
static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static int floori(double d) {return (int)d;}
static int ceili(double d) {return (int)ceil(d);}
static long floorl(double d) {return (long)d;}
static long ceill(double d) {return (long)ceil(d);}
static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(double[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void sort(int[] a) {shuffle(a); Arrays.sort(a);}
static void sort(long[] a) {shuffle(a); Arrays.sort(a);}
static void sort(double[] a) {shuffle(a); Arrays.sort(a);}
static void qsort(int[] a) {Arrays.sort(a);}
static void qsort(long[] a) {Arrays.sort(a);}
static void qsort(double[] a) {Arrays.sort(a);}
static <T> void shuffle(T[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); T swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static int randInt(int min, int max) {return rand.nextInt(max - min + 1) + min;}
// input
static void r() throws IOException {input = new StringTokenizer(__in.readLine());}
static int ri() throws IOException {return Integer.parseInt(__in.readLine());}
static long rl() throws IOException {return Long.parseLong(__in.readLine());}
static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;}
static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;}
static char[] rcha() throws IOException {return __in.readLine().toCharArray();}
static String rline() throws IOException {return __in.readLine();}
static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());}
static int ni() {return Integer.parseInt(input.nextToken());}
static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());}
static long nl() {return Long.parseLong(input.nextToken());}
// output
static void pr(int i) {__out.print(i);}
static void prln(int i) {__out.println(i);}
static void pr(long l) {__out.print(l);}
static void prln(long l) {__out.println(l);}
static void pr(double d) {__out.print(d);}
static void prln(double d) {__out.println(d);}
static void pr(char c) {__out.print(c);}
static void prln(char c) {__out.println(c);}
static void pr(char[] s) {__out.print(new String(s));}
static void prln(char[] s) {__out.println(new String(s));}
static void pr(String s) {__out.print(s);}
static void prln(String s) {__out.println(s);}
static void pr(Object o) {__out.print(o);}
static void prln(Object o) {__out.println(o);}
static void prln() {__out.println();}
static void pryes() {__out.println("yes");}
static void pry() {__out.println("Yes");}
static void prY() {__out.println("YES");}
static void prno() {__out.println("no");}
static void prn() {__out.println("No");}
static void prN() {__out.println("NO");}
static void pryesno(boolean b) {__out.println(b ? "yes" : "no");};
static void pryn(boolean b) {__out.println(b ? "Yes" : "No");}
static void prYN(boolean b) {__out.println(b ? "YES" : "NO");}
static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); __out.println(iter.next());}
static void h() {__out.println("hlfd");}
static void flush() {__out.flush();}
static void close() {__out.close();}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
9be6f752513d2fd2cecb7cc67a8a904c
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author LUCIANO.
*/
import java.util.*;
public class Solve {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner in = new Scanner(System.in);
int q = in.nextInt();
for(int tt = 0; tt < q; tt++) {
int n = in.nextInt();
int[] t = new int[n];
int[] ans = new int[n];
int color = 1;
for(int i = 0; i < n; i++) t[i] = in.nextInt();
if(solve(t, ans, true) <= solve(t, ans, false)) {
color = solve(t, ans, true);
}else {
color = solve(t, ans, false);
}
System.out.println(color);
for(int i = 0; i < n; i++) {
if(i > 0) System.out.print(" ");
System.out.print(ans[i]);
}
System.out.print("\n");
}
}
public static int solve(int[] t, int[] ans, boolean yn) {
int n = t.length;
ans[0] = 1;
boolean flag = yn;
int color = 1;
for(int i = 1; i < n; i++) {
if(i < n - 1) {
if(t[i] == t[i - 1]) {
if(flag == true) {
color = 2;
ans[i] = (ans[i - 1] == 1) ? 2 : 1;
flag = false;
}else {
ans[i] = ans[i - 1];
}
}else {
color = 2;
ans[i] = (ans[i - 1] == 1) ? 2 : 1;
}
}else {
if(ans[i - 1] == ans[0]) {
if((t[i] == t[i - 1]) && (t[i] == t[0])) ans[i] = ans[i - 1];
else {
color = 2;
ans[i] = (ans[i - 1] == 1) ? 2 : 1;
}
}else {
if(t[i] == t[i - 1]) ans[i] = ans[i - 1];
else if(t[i] == t[0]) ans[i] = ans[0];
else {
color = 3;
ans[i] = 3;
}
}
}
}
return color;
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
48fb939fd939d1ee077e111c4d0e066a
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class A {
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
int t = Integer.parseInt(br.readLine());
while (t-- > 0) {
int n = Integer.parseInt(br.readLine());
int[] x = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
solve(x, n);
}
}
private static void solve(int[] x, int n) {
StringBuilder sb = new StringBuilder();
if (count(x[0], x, n) == n) {
sb.append(1).append("\n").append("1 ".repeat(n));
System.out.println(sb);
return;
}
if (n % 2 == 0) {
sb.append(2).append("\n").append("1 2 ".repeat(n/2));
System.out.println(sb);
return;
}
int s = getRepeatIndex(x, n);
int a = 0;
if (s != -1) {
sb.append("2\n");
for (int i = 0; i < n; i++) {
sb.append(a+1).append(" ");
if (i != s)
a ^= 1;
}
System.out.println(sb);
return;
}
sb.append("3\n").append("1 2 ".repeat(n/2)).append("3");
System.out.println(sb);
}
private static int getRepeatIndex(int[] x, int n) {
for (int i = 0; i < n; i++) {
if (x[i] == x[(i + 1) % n])
return i;
}
return -1;
}
private static int count(int x, int[] arr, int end) {
int count = 0;
for (int i = 0; i < end; i++)
if (arr[i] == x)
count++;
return count;
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
fb3b7bfa4d8f3dcd70b8f69f3bb11fc9
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
//package com.company;
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int t =input.nextInt();
for(int j =0;j<t;j++)
{
int n =input.nextInt();
int[] arr=new int[n];
for(int i =0;i<n;i++){
arr[i]=input.nextInt();
}int flag=0;
int spec=0;
int s=0;
for (int i =0;i<n-1;i++){
if(arr[i]!=arr[i+1]){
flag=1;
}else{
s=1;
spec=i;
}
}if(arr[n-1]==arr[0]){
s=1;
spec=n-1;
}
if(flag==0) {
System.out.println(1);
for (int i = 0; i < n; i++) {
System.out.print(1 + " ");
}
}
if (flag == 1) {
if(s==0&&n%2==1){
System.out.println(3);
}else{
System.out.println(2);
} if(n%2==0){
for(int i =0;i<n;i++){
if(i%2==0){
System.out.print(1+" ");
}else{
System.out.print(2+" ");
}
}
}else{
int q=0;
if (s==0){
for(int i=0;i<n;i++){
if(i!=n-1){
if(i%2==0){
System.out.print(1+" ");
}else{
System.out.print(2+" ");
}
}else{
System.out.print(3);
}
}
}if (s==1){
for (int i =0;i<n;i++){
if (q==0){
if(i%2==0){
System.out.print(1+" ");
}else{
System.out.print(2+" ");
}
}if (q==1){
if(i%2==1){
System.out.print(1+" ");
}else{
System.out.print(2+" ");
}
} if(i==spec){
q=1;
}
}
}
}
}
System.out.println("");
}
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
593edb8285d3c3bd6e93633effdf6aad
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import javax.print.DocFlavor;
import java.awt.*;
import java.io.*;
import java.math.*;
import java.util.*;
public class Codeforce {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
Solver solver = new Solver();
solver.solve(in,out);
out.close();
}
static class Solver{
public void solve(InputReader in, OutputWriter out){
int t = in.nextInt();
for(int i=0;i<t;i++){
int n = in.nextInt();
int arr[] = nextAInt(n, in);
int change =0;
boolean flip = false;
if(arr[0]!=arr[n-1]) change++;
else flip =true;
for(int j=1;j<n;j++){
if(arr[j]!=arr[j-1]) change++;
else flip=true;
}
if(change==0){
out.printf("1\n");
for(int j=0;j<n;j++){
out.printf("1 ");
}
out.printf("\n");
}
else if(change%2==0){
out.printf("2\n");
boolean one = true;
out.printf("1 ");
for(int j=1;j<n;j++){
if(arr[j]!=arr[j-1]){
one=!one;
}
if(one){
out.printf("1 ");
}
else{
out.printf("2 ");
}
}
out.printf("\n");
}
else if(flip==true){
out.printf("2\n");
boolean one = true;
out.printf("1 ");
for(int j=1;j<n;j++){
if(arr[j]!=arr[j-1]){
one=!one;
}
else if(flip){
one=!one;
flip=false;
}
if(one){
out.printf("1 ");
}
else{
out.printf("2 ");
}
}
out.printf("\n");
}
else{
out.printf("3\n");
boolean one = true;
out.printf("1 ");
for(int j=1;j<n-1;j++){
if(arr[j]!=arr[j-1]){
one=!one;
}
if(one){
out.printf("1 ");
}
else{
out.printf("2 ");
}
}
out.printf("3\n");
}
}
}
private int bfs(){
ArrayList<Integer> queue = new ArrayList<>();
//queue.add(i);
while (!queue.isEmpty()){
int cur = queue.remove(0);
//visited[cur] = true;
for(int j=0;j<0;j++){
}
}
return 0;
}
private int[] nextAInt(int n, InputReader in){
int arr[] = new int[n];
for(int i=0;i<n;i++){
arr[i]= in.nextInt();
}
return arr;
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1 << 16];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (this.numChars == -1) {
throw new InputMismatchException();
} else {
if (this.curChar >= this.numChars) {
this.curChar = 0;
try {
this.numChars = this.stream.read(this.buf);
} catch (IOException var2) {
throw new InputMismatchException();
}
if (this.numChars <= 0) {
return -1;
}
}
return this.buf[this.curChar++];
}
}
public int nextInt() {
int c;
for (c = this.read(); isSpaceChar(c); c = this.read()) {
;
}
byte sgn = 1;
if (c == 45) {
sgn = -1;
c = this.read();
}
int res = 0;
while (c >= 48 && c <= 57) {
res *= 10;
res += c - 48;
c = this.read();
if (isSpaceChar(c)) {
return res * sgn;
}
}
throw new InputMismatchException();
}
public String next() {
int c;
while (isSpaceChar(c = this.read())) {
;
}
StringBuilder result = new StringBuilder();
result.appendCodePoint(c);
while (!isSpaceChar(c = this.read())) {
result.appendCodePoint(c);
}
return result.toString();
}
public static boolean isSpaceChar(int c) {
return c == 32 || c == 10 || c == 13 || c == 9 || c == -1;
}
}
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 printf(String format, Object... objects) {
writer.printf(format, objects);
}
public void close() {
writer.close();
}
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
63120c2828fe0ad3dd469d097e8e1349
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import java.util.*;
public class ProblemD {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int cases = s.nextInt();
for (int i = 0; i < cases; i++) {
int n = s.nextInt();
int[] ar = new int[n];
for (int j = 0; j < n; j++) {
ar[j] = s.nextInt();
}
boolean same = true;
for (int j = 0; j < n-1; j++) {
if (ar[j] != ar[j+1]) {
same = false;
break;
}
}
if (!same) {
boolean doubl = false;
int id = -1;
for (int j = 0; j < n; j++) {
if (j == 0) {
if (ar[j] == ar[n - 1]) {
doubl = true;
id = j;
break;
}
} else {
if (ar[j] == ar[j - 1]) {
doubl = true;
id = j;
break;
}
}
}
if (doubl) {
//answer is only 2 colors
if (n % 2 == 0) {
System.out.println("2");
for (int j = 0; j < n / 2; j++) {
System.out.print("1 ");
System.out.print("2 ");
}
} else {
System.out.println("2");
boolean one = true;
for (int j = 0; j < n; j++) {
if (j == id) {
if (j == 0) {
n--;
System.out.print("1 ");
one = false;
} else {
if (one) {
System.out.print("2 ");
} else {
System.out.print("1 ");
}
}
} else {
if (one) {
System.out.print("1 ");
one = false;
} else {
System.out.print("2 ");
one = true;
}
}
}
if (n != ar.length) {
System.out.println("1");
}
}
} else {
if (n % 2 == 0) {
//answer 2 colors
System.out.println("2");
for (int j = 0; j < n / 2; j++) {
System.out.print("1 ");
System.out.print("2 ");
}
} else {
System.out.println("3");
for (int j = 0; j < n / 2; j++) {
System.out.print("1 ");
System.out.print("2 ");
}
System.out.print("3");
}
}
}
else {
System.out.println("1");
for (int j = 0; j < n; j++) {
System.out.print("1 ");
}
}
System.out.println();
}
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
cd084898c1509b0a65f0b393b23458a5
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import java.util.*;
import java.lang.*;
import java.io.*;
public final class Enraged
{
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 Reader in = new Reader();
public static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
final static long mod = 998244353;
public static void main(String[] args) throws IOException
{
int tcase = in.nextInt();
while(tcase > 0)
{
tcase--;
solve();
}
}
public static void solve() throws IOException
{
int n = in.nextInt(), i, j;
ArrayList<Integer> arr = new ArrayList<>();
for(i = 0; i < n; i++)
arr.add(in.nextInt());
boolean r = true;
int index = -1;
for(i = 0; i < n; i++)
{
if(!arr.get(i).equals(arr.get((i + 1) % n))) r = false;
else index = i;
}
if(r)
{
out.write("1\n");
out.flush();
for(i = 0; i < n; i++)
{
out.write("1 ");
out.flush();
}
}
else if((n & 1) == 0)
{
out.write("2\n");
out.flush();
for(i = 0; i < n; i++)
{
out.write((1+(i & 1))+" ");
out.flush();
}
}
else
{
if(index == -1)
{
out.write("3\n");
out.flush();
for(i = 0; i < n-1; i++)
{
out.write((1 + (i & 1)) + " ");
out.flush();
}
out.write("3");
out.flush();
}
else
{
out.write("2\n");
out.flush();
int k = 1;
for(i = 0; i < n; i++)
{
if(index == n-1)
{
if(i == 0 || i == n-1)
{
out.write("2 ");
out.flush();
}
else
{
out.write(k+" ");
k = 3-k;
}
}
else
{
out.write(k + " ");
out.flush();
if (i != index)
{
k = 3 - k;
}
}
}
}
}
out.write("\n");
out.flush();
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
f743fa5b952d5930c42663061b0698ab
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import java.util.Scanner;
public class Main {
private static final int maxn = 200005;
static Scanner in = new Scanner(System.in);
private static int a[] = new int[maxn], ans[] = new int[maxn];
public static void main(String[] args) {
int t = in.nextInt();
while (t-- > 0) {
int n = in.nextInt();
for (int i = 1; i <= n; i++)
a[i] = in.nextInt();
int tot = 1;
for (int i = 1; i <= n; i++) {
if (i == 1)
ans[i] = 1;
else if (a[i] == a[i - 1])
ans[i] = ans[i - 1];
else {
tot = 2;
ans[i] = 3 - ans[i - 1];
}
}
if (a[1] != a[n] && ans[1] == ans[n]) {
ans[n] = 3;
tot = 3;
int pos=-1;
for(int i=n-1;i>=1;i--) if(a[i]==a[i+1]) {
pos=i+1;
break;
}
if(pos!=-1) {
for(int i=pos;i<=n;i++) ans[i]=3-ans[i-1];
tot=2;
}
}
System.out.println(tot);
for (int i = 1; i <= n; i++)
System.out.print(ans[i] + " ");
System.out.println();
}
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
c9d77d595f7dbdf9c410779a484e0f2e
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import java.lang.reflect.Array;
import java.util.*;
import java.io.*;
public class D629
{
public static void main(String [] args)
{
MyScanner sc = new MyScanner();
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int q = sc.nextInt();
while (q > 0) {
int n = sc.nextInt();
int [] s = new int [n]; int prev = -1; int start = -1;
for (int i = 0; i < n; i++) {
s[i] = sc.nextInt();
if (s[i] == prev) {
start = i;
}
prev = s[i];
}
if (s[n-1] == s[0]) start = 0;
if (start == -1) {
if (n % 2 == 0) {
out.println(2);
for (int i = 0; i < n; i++) {
if (i % 2 == 0) out.print(1 + " "); else out.print(2 + " ");
}
} else {
out.println(3);
for (int i = 0; i < n; i++) {
if (i == n - 1) {
out.print(3 + " ");
} else if (i % 2 == 0) {
out.print(1 + " ");
} else {
out.print(2 + " ");
}
}
}
} else {
int [] res = new int [n];
int cur = start + 1; int back = 1; res[start] = 1;
while (cur < n) {
if (s[cur] == s[cur - 1]) {
res[cur] = back;
} else {
res[cur] = 3 - back;
back = 3 - back;
}
cur++;
}
if (s[0] == s[n-1] && res[0] == 0) {
res[0] = back;
} else if (res[0] == 0) {
res[0] = 3 - back; back = 3 - back;
}
if (start != 0) {
cur = 1;
while (cur < start) {
if (s[cur] == s[cur - 1]) {
res[cur] = back;
} else {
res[cur] = 3 - back;
back = 3 - back;
}
cur++;
}
}
boolean two = false;
for (int i = 0; i < n; i++) {
if (res[i] == 2) two = true;
}
if (two) out.println(2); else out.println(1);
for (int i = 0; i < n; i++) out.print(res[i] + " ");
}
out.println();
q--;
}
out.close();
}
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
bbaf1958f71390dba2b3fa8f42bcfe58
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import java.util.*;
public class div3_march_26_contest_629 {
public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
int t=scn.nextInt();
while(t-->0) {
int n=scn.nextInt();
int[]arr=new int[n];
HashSet<Integer>set=new HashSet();
for(int i=0;i<n;i++) {
arr[i]=scn.nextInt();
set.add(arr[i]);
}
if(set.size()==1) {
System.out.println("1");
for(int i=0;i<n;i++)
System.out.print("1 ");
System.out.println();
}else {
int ans=2;
int[]a=new int[n];
for(int i=0;i<n;i++) {
if(i%2==0) {
a[i]=1;
}else {
a[i]=2;
}
}
if(arr[0]!=arr[n-1] && a[0]==a[n-1]) {
boolean flag=false;
for(int i=n-1;i>0;i--) {
if(arr[i]==arr[i-1]) {
flag=true;
a[i]=a[i-1];
for(int j=i+1;j<n;j++) {
a[j]=(a[j-1]%2+1);
}
}
}
if(!flag) {
ans=3;
a[0]=3;
}
}
System.out.println(ans);
for(int i=0;i<n;i++) {
System.out.print(a[i]+" ");
}
System.out.println();
}
}
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
2303a87ab7a1b1ff0409b7bd4ba2fd00
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import java.util.*;
public class Test
{
public static void main(String []args)
{
Scanner sc = new Scanner(System.in);
int t=sc.nextInt();
while(t>0)
{
t--;
int n=sc.nextInt();
int a[]=new int[n];
int b[]=new int[n];
a[0]=sc.nextInt();
int cnt=1,res=-1,k=1;
b[0]=cnt;
for(int i=1;i<n;i++)
{
a[i]=sc.nextInt();
if(a[i]==a[i-1])
{
b[i]=b[i-1];
res=i;
}
else
{
b[i]=3-cnt;
cnt=3-cnt;
k=2;
}
}
if(a[0]!=a[n-1]&&b[0]==b[n-1])
{
if(res>0)
{
for(int i=res;i<n;i++)
{
b[i]=3-b[i];
}
}
else
{
b[n-1]=3;
k=3;
}
}
System.out.println(k);
for(int i=0;i<n;i++)
{
System.out.print(b[i]+" ");
}
System.out.println();
}
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
71ed40bfc8c0bb118a81af2380be6d9b
|
train_000.jsonl
|
1585233300
|
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Learning {
public static void main(String[] args) throws Exception {
FastInput in = new FastInput();
StringBuilder st = new StringBuilder();
int t = in.nextInt();
while (t-- > 0) {
int n = in.nextInt();
int[] arr = new int[n];
boolean same = true;
int pos = 0;
boolean adjeq = false;
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
for (int i = 1; i < n; i++) {
if (arr[i] != arr[i - 1]) {
same = false;
}
if (arr[i] == arr[i - 1]) {
adjeq = true;
pos = i-1;
}
}
if (arr[n - 1] == arr[0]) {
adjeq = true;
pos = n - 1;
}
if (same) {
st.append(1 + "\n");
for (int i : arr) {
st.append(1 + " ");
}
st.append("\n");
continue;
}
if (n % 2 == 0) {
st.append(2 + "\n");
for (int i = 0; i < n; i++) {
st.append(i % 2 == 0 ? 1 : 2).append(" ");
}
st.append("\n");
continue;
}
if (adjeq) {
st.append(2 + "\n");
boolean f = false;
for (int i = 0; i < n; i++) {
st.append(f ? 1 : 2).append(" ");
if (pos == i) {
continue;
}
f = !f;
}
st.append("\n");
continue;
}
st.append(3 + "\n");
for (int i = 0; i < n - 1; i++) {
st.append(i % 2 == 0 ? 1 : 2).append(" ");
}
st.append(3).append("\n");
}
System.out.print(st.toString());
}
}
class FastInput {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
String next() throws IOException {
if (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
Integer nextInt() throws IOException {
return Integer.parseInt(next());
}
Long nextLong() throws IOException {
return Long.parseLong(next());
}
}
|
Java
|
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
|
2 seconds
|
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
| null |
Java 11
|
standard input
|
[
"dp",
"greedy",
"graphs",
"constructive algorithms",
"math"
] |
1f4c3f5e7205fe556b50320cecf66c89
|
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
| 1,800 |
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
|
standard output
| |
PASSED
|
32ed87aee34dbece42a515054fdea930
|
train_000.jsonl
|
1432658100
|
Mike is the president of country What-The-Fatherland. There are n bears living in this country besides Mike. All of them are standing in a line and they are numbered from 1 to n from left to right. i-th bear is exactly ai feet high. A group of bears is a non-empty contiguous segment of the line. The size of a group is the number of bears in that group. The strength of a group is the minimum height of the bear in that group.Mike is a curious to know for each x such that 1 ≤ x ≤ n the maximum strength among all groups of size x.
|
256 megabytes
|
import java.util.Arrays;
import java.util.ArrayDeque;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Agostinho Junior (junior94)
*/
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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.readInt();
}
int[] start = new int[n];
ArrayDeque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < n; i++) {
while (!stack.isEmpty()) {
int x = stack.peek();
if (a[x] > a[i]) {
stack.pop();
} else {
start[i] = x + 1;
break;
}
}
stack.push(i);
}
int[] end = new int[n];
Arrays.fill(end, n - 1);
stack.clear();
for (int i = n - 1; i >= 0; i--) {
while (!stack.isEmpty()) {
int x = stack.peek();
if (a[x] >= a[i]) {
stack.pop();
} else {
end[i] = x - 1;
break;
}
}
stack.push(i);
}
int[] ans = new int[n + 1];
for (int i = 0; i < n; i++) {
ans[end[i] - start[i] + 1] = Math.max(ans[end[i] - start[i] + 1], a[i]);
}
for (int i = n - 1; i > 0; i--) {
ans[i] = Math.max(ans[i], ans[i + 1]);
}
for (int x = 1; x <= n; x++) {
out.print(ans[x] + " ");
}
out.println();
}
}
class InputReader {
private BufferedReader input;
private StringTokenizer line = new StringTokenizer("");
public InputReader(InputStream in) {input = new BufferedReader(new InputStreamReader(in));
}
public void fill() {
try {
if(!line.hasMoreTokens()) line = new StringTokenizer(input.readLine());
} catch(IOException io) { io.printStackTrace(); System.exit(0);}
}
public int readInt() {
fill();
return Integer.parseInt(line.nextToken());
}
}
class OutputWriter {
private PrintWriter output;
public OutputWriter(OutputStream out) {
output = new PrintWriter(out);
}
public void print(Object o) {
output.print(o);
}
public void println() {
output.println();
}
public void close() {
output.close();
}
}
|
Java
|
["10\n1 2 3 4 5 4 3 2 1 6"]
|
1 second
|
["6 4 4 3 3 2 2 1 1 1"]
| null |
Java 8
|
standard input
|
[
"dp",
"dsu",
"binary search",
"data structures"
] |
5cf25cd4a02ce8020258115639c0ee64
|
The first line of input contains integer n (1 ≤ n ≤ 2 × 105), the number of bears. The second line contains n integers separated by space, a1, a2, ..., an (1 ≤ ai ≤ 109), heights of bears.
| 1,900 |
Print n integers in one line. For each x from 1 to n, print the maximum strength among all groups of size x.
|
standard output
| |
PASSED
|
d6a3121319b13377f93d8af81fe47c68
|
train_000.jsonl
|
1432658100
|
Mike is the president of country What-The-Fatherland. There are n bears living in this country besides Mike. All of them are standing in a line and they are numbered from 1 to n from left to right. i-th bear is exactly ai feet high. A group of bears is a non-empty contiguous segment of the line. The size of a group is the number of bears in that group. The strength of a group is the minimum height of the bear in that group.Mike is a curious to know for each x such that 1 ≤ x ≤ n the maximum strength among all groups of size x.
|
256 megabytes
|
import java.util.*;
import java.awt.geom.*;
import java.io.*;
import java.math.*;
public class Main
{
static final int n_max = 200010;
static Scanner fi = new Scanner (System.in);
static PrintWriter fo = new PrintWriter (System.out);
static int[] L = new int[n_max],
R = new int[n_max],
A = new int[n_max],
P = new int[n_max],
V = new int[n_max];
static int n;
static void enter ()
{
n = fi.nextInt();
for (int i = 1; i <= n; ++i) A[i] = fi.nextInt();
}
static void solve ()
{
int bot = 1, top = 0;
for (int i = 1; i <= n; ++i)
{
while (bot <= top && A[P[top]] >= A[i]) --top;
L[i] = (bot <= top ? P[top] : 0);
P[++top] = i;
}
bot = 1; top = 0;
for (int i = n; i > 0; --i)
{
while (bot <= top && A[P[top]] >= A[i]) --top;
R[i] = (bot <= top ? P[top] : n + 1);
P[++top] = i;
}
int k = 0;
for (int i = 1; i <= n; ++i)
{
k = R[i] - L[i] - 1;
V[k] = Math.max(V[k], A[i]);
}
k = 0;
for (int i = n; i > 0; --i)
{
k = Math.max(k, V[i]);
R[i] = k;
}
for (int i = 1; i <= n; ++i)
fo.print(R[i] + " ");
}
public static void main(String[] args)
{
try {fi = new Scanner (new File("test.inp"));}
catch (FileNotFoundException e) {}
enter ();
solve ();
fi.close(); fo.close();
}
}
|
Java
|
["10\n1 2 3 4 5 4 3 2 1 6"]
|
1 second
|
["6 4 4 3 3 2 2 1 1 1"]
| null |
Java 8
|
standard input
|
[
"dp",
"dsu",
"binary search",
"data structures"
] |
5cf25cd4a02ce8020258115639c0ee64
|
The first line of input contains integer n (1 ≤ n ≤ 2 × 105), the number of bears. The second line contains n integers separated by space, a1, a2, ..., an (1 ≤ ai ≤ 109), heights of bears.
| 1,900 |
Print n integers in one line. For each x from 1 to n, print the maximum strength among all groups of size x.
|
standard output
| |
PASSED
|
f09a94bf177c3e030383e2ff2c633b39
|
train_000.jsonl
|
1432658100
|
Mike is the president of country What-The-Fatherland. There are n bears living in this country besides Mike. All of them are standing in a line and they are numbered from 1 to n from left to right. i-th bear is exactly ai feet high. A group of bears is a non-empty contiguous segment of the line. The size of a group is the number of bears in that group. The strength of a group is the minimum height of the bear in that group.Mike is a curious to know for each x such that 1 ≤ x ≤ n the maximum strength among all groups of size x.
|
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.InputMismatchException;
import java.io.IOException;
import java.util.Comparator;
import java.util.TreeSet;
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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
public void solve(int testNumber, FastReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = new int[n];
int[] stack = new int[n];
for (int i = 0; i < n; ++i) a[i] = in.nextInt();
int[] L = new int[n];
int[] R = new int[n];
Arrays.fill(L, -1);
Arrays.fill(R, n);
int ptr;
{
ptr = 0;
for (int i = 0; i < n; ++i) {
while (ptr != 0 && a[stack[ptr - 1]] > a[i]) {
R[stack[--ptr]] = i;
}
stack[ptr++] = i;
}
}
{
ptr = 0;
for (int i = n - 1; i >= 0; --i) {
while (ptr != 0 && a[stack[ptr - 1]] > a[i]) {
L[stack[--ptr]] = i;
}
stack[ptr++] = i;
}
}
TreeSet<TaskB.Pair> set = new TreeSet<>(new Comparator<TaskB.Pair>() {
public int compare(TaskB.Pair o1, TaskB.Pair o2) {
if (o1.value != o2.value) return Integer.compare(o2.value, o1.value);
return o2.range - o1.range;
}
});
for (int i = 0; i < n; ++i) {
set.add(new TaskB.Pair(a[i], R[i] - L[i] - 1));
}
int[] res = new int[n];
for (int i = 0; i < n; ++i) {
while (true) {
TaskB.Pair cur = set.pollFirst();
if (cur == null) break;
if (cur.range >= i + 1) {
res[i] = cur.value;
set.add(cur);
break;
}
}
}
ArrayUtils.printArray(out, res);
}
static class Pair {
int value;
int range;
public Pair(int v, int r) {
value = v;
range = r;
}
public String toString() {
return "Pair{" +
"value=" + value +
", range=" + range +
'}';
}
}
}
static class ArrayUtils {
public static void printArray(PrintWriter out, int[] array) {
if (array.length == 0) return;
for (int i = 0; i < array.length; i++) {
if (i != 0) out.print(" ");
out.print(array[i]);
}
out.println();
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int pnumChars;
public FastReader(InputStream stream) {
this.stream = stream;
}
private int pread() {
if (pnumChars == -1) {
throw new InputMismatchException();
}
if (curChar >= pnumChars) {
curChar = 0;
try {
pnumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (pnumChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = pread();
while (isSpaceChar(c))
c = pread();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = pread();
}
int res = 0;
do {
if (c == ',') {
c = pread();
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = pread();
} while (!isSpaceChar(c));
return res * sgn;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
|
Java
|
["10\n1 2 3 4 5 4 3 2 1 6"]
|
1 second
|
["6 4 4 3 3 2 2 1 1 1"]
| null |
Java 8
|
standard input
|
[
"dp",
"dsu",
"binary search",
"data structures"
] |
5cf25cd4a02ce8020258115639c0ee64
|
The first line of input contains integer n (1 ≤ n ≤ 2 × 105), the number of bears. The second line contains n integers separated by space, a1, a2, ..., an (1 ≤ ai ≤ 109), heights of bears.
| 1,900 |
Print n integers in one line. For each x from 1 to n, print the maximum strength among all groups of size x.
|
standard output
| |
PASSED
|
886aec00ae0dd3ca84829dfc537e8671
|
train_000.jsonl
|
1432658100
|
Mike is the president of country What-The-Fatherland. There are n bears living in this country besides Mike. All of them are standing in a line and they are numbered from 1 to n from left to right. i-th bear is exactly ai feet high. A group of bears is a non-empty contiguous segment of the line. The size of a group is the number of bears in that group. The strength of a group is the minimum height of the bear in that group.Mike is a curious to know for each x such that 1 ≤ x ≤ n the maximum strength among all groups of size x.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Stack;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class cfvc15
{
static BufferedReader reader;
static StringTokenizer tokenizer;
static void init(InputStream input)
{
reader = new BufferedReader( new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
static String next() throws IOException
{
while ( ! tokenizer.hasMoreTokens() )
{
tokenizer = new StringTokenizer(reader.readLine() );
}
return tokenizer.nextToken();
}
static long nextInt() throws IOException
{
return Long.parseLong( next() );
}
static PrintWriter writer;
static void outit(OutputStream outputStream)
{
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
static void print(Object...objects) {
for (int i = 0; i < objects.length; i++)
{
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
static void println(Object...objects)
{
print(objects);
writer.println();
}
static void close()
{
writer.close();
}
static void flush() {
writer.flush();
}
public static void print_a(long [] a)
{
for(long i : a)
{
print(i+" ") ;
}
println() ;
}
static boolean [] prime ;
static int [] fac ;
public static void main(String [] args) throws IOException
{
init(System.in) ;
outit(System.out) ;
// int t = (int) nextInt() ;
// for(int i =0 ; i<t ; i++)
output() ;
flush();
close();
}
public static void output() throws IOException
{
int n = (int)nextInt() ;
int [] a = new int [n] ;
int [] l = new int [n] ;
int [] r = new int [n] ;
for(int i = 0 ;i<n ; i++)
{
a[i] = (int)nextInt() ;
}
Stack<Integer> s = new Stack<Integer>() ;
for(int i = 0 ;i<n ; i++)
{
while(!s.isEmpty())
{
if(a[s.peek()]>=a[i])
{
s.pop();
}
else
{
break ;
}
}
if(s.isEmpty())
{
l[i] = -1 ;
}
else
{
l[i] = s.peek();
}
s.add(i);
}
// for(int i = 0 ; i<n ; i++)
// {
// print(l[i]+" ") ;
// }
s = new Stack<Integer>() ;
for(int i = n-1 ; i>=0 ; i--)
{
while(!s.isEmpty())
{
if(a[s.peek()]>=a[i])
{
s.pop();
}
else
{
break ;
}
}
if(s.isEmpty())
{
r[i] = n ;
}
else
{
r[i] = s.peek() ;
}
s.add(i) ;
}
int [][] diff = new int [n][2] ;
for(int i = 0 ; i<n ; i++)
{
diff[i][0] = a[i] ;
diff[i][1] = r[i]-l[i]-1 ;
}
java.util.Arrays.sort(diff, new java.util.Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return (a[0] < b[0] ? -1 : (a[0] == b[0] ? 0 : 1));
}
});
int max_u = 0 ;
int [] ans = new int [n+1] ;
for(int i = n-1 ; i>=0 ; i--)
{
// println(diff[i][1]) ;
if(diff[i][1]>max_u)
{
for(int j = max_u+1 ; j<=diff[i][1] ; j++)
{
ans[j] = diff[i][0] ;
}
max_u = diff[i][1] ;
}
}
for(int i = 1 ; i<=n ; i++)
{
print(ans[i]+" ") ;
}
println() ;
}
}
|
Java
|
["10\n1 2 3 4 5 4 3 2 1 6"]
|
1 second
|
["6 4 4 3 3 2 2 1 1 1"]
| null |
Java 8
|
standard input
|
[
"dp",
"dsu",
"binary search",
"data structures"
] |
5cf25cd4a02ce8020258115639c0ee64
|
The first line of input contains integer n (1 ≤ n ≤ 2 × 105), the number of bears. The second line contains n integers separated by space, a1, a2, ..., an (1 ≤ ai ≤ 109), heights of bears.
| 1,900 |
Print n integers in one line. For each x from 1 to n, print the maximum strength among all groups of size x.
|
standard output
| |
PASSED
|
17a2dde1fb3767300baad8ed21ed203d
|
train_000.jsonl
|
1432658100
|
Mike is the president of country What-The-Fatherland. There are n bears living in this country besides Mike. All of them are standing in a line and they are numbered from 1 to n from left to right. i-th bear is exactly ai feet high. A group of bears is a non-empty contiguous segment of the line. The size of a group is the number of bears in that group. The strength of a group is the minimum height of the bear in that group.Mike is a curious to know for each x such that 1 ≤ x ≤ n the maximum strength among all groups of size x.
|
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 B547
{
public static int mod = 1000000007;
public static long INF = (1L << 60);
static FastScanner2 in = new FastScanner2();
static OutputWriter out = new OutputWriter(System.out);
public static void main(String[] args)
{
int n=in.nextInt();
int[] arr=new int[n+1];
for(int i=1;i<=n;i++)
{
arr[i]=in.nextInt();
}
int[] l=new int[n+1];
int[] r=new int[n+1];
Arrays.fill(l, 0);
Arrays.fill(r, n+1);
Stack<Integer> stack=new Stack<>();
for(int i=1;i<=n;i++)
{
while(!stack.isEmpty() && arr[stack.peek()]>=arr[i])
{
stack.pop();
}
if(!stack.isEmpty())
{
l[i]=stack.peek();
}
stack.push(i);
}
stack=new Stack<>();
for(int i=n;i>=1;i--)
{
while(!stack.isEmpty() && arr[stack.peek()]>=arr[i])
{
stack.pop();
}
if(!stack.isEmpty())
{
r[i]=stack.peek();
}
stack.push(i);
}
int[] ans=new int[n+2];
Arrays.fill(ans, 0);
for(int i=1;i<=n;i++)
{
int size=r[i]-1-(l[i]+1)+1;
ans[size]=max(ans[size], arr[i]);
}
for(int i=n;i>=1;i--)
{
ans[i]=max(ans[i], ans[i+1]);
}
for(int i=1;i<=n;i++)
{
out.print(ans[i]+" ");
}
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();
}
}
private static boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private static void debug(Object... o)
{
if (!oj)
System.out.println(Arrays.deepToString(o));
}
private static void tr(Object... o)
{
if (!oj)
System.out.println(Arrays.deepToString(o));
}
}
|
Java
|
["10\n1 2 3 4 5 4 3 2 1 6"]
|
1 second
|
["6 4 4 3 3 2 2 1 1 1"]
| null |
Java 8
|
standard input
|
[
"dp",
"dsu",
"binary search",
"data structures"
] |
5cf25cd4a02ce8020258115639c0ee64
|
The first line of input contains integer n (1 ≤ n ≤ 2 × 105), the number of bears. The second line contains n integers separated by space, a1, a2, ..., an (1 ≤ ai ≤ 109), heights of bears.
| 1,900 |
Print n integers in one line. For each x from 1 to n, print the maximum strength among all groups of size x.
|
standard output
| |
PASSED
|
fe04518694fd00de5498749dad0abccd
|
train_000.jsonl
|
1432658100
|
Mike is the president of country What-The-Fatherland. There are n bears living in this country besides Mike. All of them are standing in a line and they are numbered from 1 to n from left to right. i-th bear is exactly ai feet high. A group of bears is a non-empty contiguous segment of the line. The size of a group is the number of bears in that group. The strength of a group is the minimum height of the bear in that group.Mike is a curious to know for each x such that 1 ≤ x ≤ n the maximum strength among all groups of size x.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.StringTokenizer;
import java.util.stream.Stream;
public class Solution implements Runnable {
static final int limit = 2001;
static final int MOD = (int) 1e9 + 7;
static final Reader in = new Reader();
static final PrintWriter out = new PrintWriter(System.out);
StringBuilder answer = new StringBuilder();
public static void main(String[] args) {
new Thread(null, new Solution(), "persefone", 1 << 28).start();
}
@Override
public void run() {
solve(in.nextInt());
printf();
}
void solve(int n) {
int[] a = in.nextIntArray(n);
int[] le = new int[n];
le[0] = -1;
for (int i = 1; i < n; i++) {
if (a[i] > a[i - 1]) le[i] = i - 1;
else {
int k = le[i - 1];
while (k != -1) {
if (a[i] > a[k]) break;
k = le[k];
}
le[i] = k;
}
}
int[] ri = new int[n];
ri[n - 1] = n;
for (int i = n - 2; i > -1; i--) {
if (a[i] > a[i + 1]) ri[i] = i + 1;
else {
int k = ri[i + 1];
while (k != n) {
if (a[i] > a[k]) break;
k = ri[k];
}
ri[i] = k;
}
}
int[] d = new int[n];
Arrays.fill(d, 0);
for (int i = 0; i < n; i++) {
int x = ri[i] - le[i] - 1;
d[x - 1] = max(d[x - 1], a[i]);
}
for (int i = n - 2; i > -1; i--) d[i] = max(d[i], d[i + 1]);
printf(d);
}
void printf() {
out.print(answer);
out.close();
}
void printf(Stream<?> str) {
str.forEach(o -> add(o, " "));
add("\n");
}
void printf(Object... obj) {
printf(false, obj);
}
void printfWithDescription(Object... obj) {
printf(true, obj);
}
private void printf(boolean b, Object... obj) {
if (obj.length > 1) {
for (int i = 0; i < obj.length; i++) {
if (b) add(obj[i].getClass().getSimpleName(), " - ");
if (obj[i] instanceof Collection<?>) {
printf((Collection<?>) obj[i]);
} else printf(obj[i]);
}
return;
}
if (b) add(obj[0].getClass().getSimpleName(), " - ");
printf(obj[0]);
}
void printf(Object o) {
if (o instanceof int[])
printf(Arrays.stream((int[]) o).boxed());
else if (o instanceof char[])
printf(new String((char[]) o));
else if (o instanceof long[])
printf(Arrays.stream((long[]) o).boxed());
else if (o instanceof double[])
printf(Arrays.stream((double[]) o).boxed());
else
add(o, "\n");
}
void printf(Collection<?> col) {
printf(col.stream());
}
<T, K> void add(T t, K k) {
if (t instanceof Collection<?>) {
((Collection<?>) t).forEach(i -> add(i, " "));
} else if (t instanceof Object[]) {
Arrays.stream((Object[]) t).forEach(i -> add(i, " "));
} else
add(t);
add(k);
}
<T> void add(T t) {
answer.append(t);
}
@SuppressWarnings("unchecked")
<T extends Comparable<? super T>> T min(T... t) {
if (t.length == 0)
return null;
T m = t[0];
for (int i = 1; i < t.length; i++)
if (t[i].compareTo(m) < 0)
m = t[i];
return m;
}
@SuppressWarnings("unchecked")
<T extends Comparable<? super T>> T max(T... t) {
if (t.length == 0)
return null;
T m = t[0];
for (int i = 1; i < t.length; i++)
if (t[i].compareTo(m) > 0)
m = t[i];
return m;
}
int mod(int x) { return x % MOD; }
int mod(int x, int y) { return mod(mod(x) + mod(y)); }
long mod(long x) { return x % MOD; }
long mod (long x, long y) { return mod(mod(x) + mod(y)); }
static class Pair<K extends Comparable<? super K>, V extends Comparable<? super V>>
implements Comparable<Pair<K, V>> {
private K k;
private V v;
Pair() {}
Pair(K k, V v) {
this.k = k;
this.v = v;
}
K getK() { return k; }
V getV() { return v; }
void setK(K k) { this.k = k; }
void setV(V v) { this.v = v; }
void setKV(K k, V v) {
this.k = k;
this.v = v;
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || !(o instanceof Pair)) return false;
Pair<K, V> p = (Pair<K, V>) o;
return k.compareTo(p.k) == 0 && v.compareTo(p.v) == 0;
}
@Override
public int hashCode() {
int hash = 31;
hash = hash * 89 + k.hashCode();
hash = hash * 89 + v.hashCode();
return hash;
}
@Override
public int compareTo(Pair<K, V> pair) {
return k.compareTo(pair.k) == 0 ? v.compareTo(pair.v) : k.compareTo(pair.k);
}
@Override
public Pair<K, V> clone() {
return new Pair<K, V>(this.k, this.v);
}
@Override
public String toString() {
return String.valueOf(k).concat(" ").concat(String.valueOf(v)).concat("\n");
}
}
static class Reader {
private BufferedReader br;
private StringTokenizer st;
Reader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
try {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
long nextLong() {
return Long.parseLong(next());
}
String nextLine() {
String s = "";
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
}
}
|
Java
|
["10\n1 2 3 4 5 4 3 2 1 6"]
|
1 second
|
["6 4 4 3 3 2 2 1 1 1"]
| null |
Java 8
|
standard input
|
[
"dp",
"dsu",
"binary search",
"data structures"
] |
5cf25cd4a02ce8020258115639c0ee64
|
The first line of input contains integer n (1 ≤ n ≤ 2 × 105), the number of bears. The second line contains n integers separated by space, a1, a2, ..., an (1 ≤ ai ≤ 109), heights of bears.
| 1,900 |
Print n integers in one line. For each x from 1 to n, print the maximum strength among all groups of size x.
|
standard output
| |
PASSED
|
8d9b9341612f2382d7f77e77d3a72cfd
|
train_000.jsonl
|
1432658100
|
Mike is the president of country What-The-Fatherland. There are n bears living in this country besides Mike. All of them are standing in a line and they are numbered from 1 to n from left to right. i-th bear is exactly ai feet high. A group of bears is a non-empty contiguous segment of the line. The size of a group is the number of bears in that group. The strength of a group is the minimum height of the bear in that group.Mike is a curious to know for each x such that 1 ≤ x ≤ n the maximum strength among all groups of size x.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main
{
public static void main (String [] args) throws Exception
{
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt() ;
int [] a = new int [n] ;
Compressor<Integer> compressor = new Compressor<>() ;
for(int i = 0 ; i < n ; i++)compressor.add(a[i] = sc.nextInt());
compressor.fix();
int MAX = compressor.set.size() + 1;
int N = 1 ; while(N << 1<= MAX) N <<= 1 ;
N <<= 1 ;
SegmentTreeMax max = new SegmentTreeMax(N) ;
SegmentTreeMin min = new SegmentTreeMin(N) ;
int [] L = new int [n], R = new int [n] , ans = new int [n];
for(int i = 0 ;i < n ;i++)
{
L[i] = max.query(1 , compressor.get(a[i]) - 1) ;
if(L[i] == Integer.MIN_VALUE) L[i] = 0 ;
else L[i] ++ ;
max.update_point(compressor.get(a[i]) , i);
}
for(int i = n - 1 ; i >= 0 ; i --)
{
R[i] = min.query(1 , compressor.get(a[i]) - 1) ;
if(R[i] == Integer.MAX_VALUE) R[i] = n - 1;
else R[i] -- ;
min.update_point(compressor.get(a[i]) , i);
}
for(int i = 0 ;i < n ; i++)
{
int sz = R[i] - L[i] + 1 ;
ans[sz - 1] = Math.max(ans[sz - 1] , a[i]) ;
}
for(int i = n - 2 ; i >= 0 ; i--)
ans[i] = Math.max(ans[i + 1] , ans[i]);
for(int i = 0 ; i < n ; i++)
{
if(i > 0) out.print(" ");
out.print(ans[i]);
}
out.flush();
out.close();
}
static class SegmentTreeMin {
int N;
int[] sTree;
SegmentTreeMin(int n) {
N = n;
sTree = new int[N << 1];
Arrays.fill(sTree, Integer.MAX_VALUE);
}
void update_point(int index, int val) {
index += N - 1;
sTree[index] = val;
while (index > 1) {
index >>= 1;
sTree[index] = Math.min(sTree[index << 1], sTree[index << 1 | 1]);
}
}
int query(int i, int j) {
return query(1, 1, N, i, j);
}
int query(int node, int b, int e, int i, int j) {
if (i > e || j < b)
return Integer.MAX_VALUE;
if (b >= i && e <= j)
return sTree[node];
int mid = b + e >> 1;
int q1 = query(node << 1, b, mid, i, j);
int q2 = query(node << 1 | 1, mid + 1, e, i, j);
return Math.min(q1, q2);
}
}
static class SegmentTreeMax {
int N;
int[] sTree;
SegmentTreeMax(int n) {
N = n;
sTree = new int[N << 1];
Arrays.fill(sTree, Integer.MIN_VALUE);
}
void update_point(int index, int val) {
index += N - 1;
sTree[index] = val;
while (index > 1) {
index >>= 1;
sTree[index] = Math.max(sTree[index << 1], sTree[index << 1 | 1]);
}
}
int query(int i, int j) {return query(1, 1, N, i, j); }
int query(int node, int b, int e, int i, int j) {
if (i > e || j < b)
return Integer.MIN_VALUE;
if (i <= b && e <= j) {
return sTree[node];
}
int mid = b + e >> 1;
int q1 = query(node << 1, b, mid, i, j);
int q2 = query(node << 1 | 1, mid + 1, e, i, j);
return Math.max(q1, q2);
}
}
static class Compressor<T> implements Iterable<T>
{
TreeSet<T> set = new TreeSet<>() ;
HashMap<T , Integer> map = new HashMap<>() ;
void add(T x) {set.add(x);}
void fix() {for(T x : set) map.put(x, map.size() + 1) ;}
int get(T x) {return map.get(x) ;}
public Iterator<T> iterator() {return set.iterator();}
}
static class Scanner
{
BufferedReader br;
StringTokenizer st;
Scanner(InputStream in)
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() throws Exception
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws Exception { return Integer.parseInt(next()); }
long nextLong() throws Exception { return Long.parseLong(next()); }
double nextDouble() throws Exception { return Double.parseDouble(next());}
}
}
|
Java
|
["10\n1 2 3 4 5 4 3 2 1 6"]
|
1 second
|
["6 4 4 3 3 2 2 1 1 1"]
| null |
Java 8
|
standard input
|
[
"dp",
"dsu",
"binary search",
"data structures"
] |
5cf25cd4a02ce8020258115639c0ee64
|
The first line of input contains integer n (1 ≤ n ≤ 2 × 105), the number of bears. The second line contains n integers separated by space, a1, a2, ..., an (1 ≤ ai ≤ 109), heights of bears.
| 1,900 |
Print n integers in one line. For each x from 1 to n, print the maximum strength among all groups of size x.
|
standard output
| |
PASSED
|
0a40522901c71643594b1879a99b1699
|
train_000.jsonl
|
1517582100
|
Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r — for every replace ai with D(ai); SUM l r — calculate . Print the answer for each SUM query.
|
256 megabytes
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.Map.Entry;
public class Main
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private PrintWriter pw;
private long mod = 1000000000 + 7;
private StringBuilder ans_sb;
private int block;
private double ans = 0;
int[] s;
private void soln()
{
int n = nextInt();
int m = nextInt();
int[] arr = nextIntArray(n);
// TreeSet<Integer> set = new TreeSet<>();
Segment tree = new Segment(n,arr);
s = new int[1000001];
for(int i=1;i<=1000000;i++) {
for(int j=i;j<=1000000;j+=i)
s[j]++;
}
// debug(s);
for(int i=0;i<m;i++) {
int t = nextInt();
int l = nextInt() - 1;
int r = nextInt() - 1;
if(t==1) {
tree.update(l, r, 1);
}else {
pw.println(tree.query(l, r));
}
}
}
public class Segment
{
private long[] tree;
private int[] base;
private int[] lazy;
private int size;
private int n;
private class Node
{
private int l;
private int r;
private long ans;
}
public Segment(int n, int[] arr)
{
this.base=arr;
int x = (int) (Math.ceil(Math.log(n) / Math.log(2)));
size = 2 * (int) Math.pow(2, x) - 1;
tree = new long[size];
lazy = new int[size];
this.n = n;
//this.set = set1;
build(0, 0, n - 1);
}
public void build(int id, int l, int r)
{
if (l == r)
{
tree[id] = base[l];
if(tree[id] == 1 || tree[id] == 2)
lazy[id] = 1;
return;
}
int mid =( (l + r) >>1);
build(2 * id + 1, l, mid);
build(2 * id + 2, mid + 1, r);
tree[id] = tree[(id<<1)|1]+ tree[(id<<1)+2];
lazy[id] = lazy[(id<<1)|1]+ lazy[(id<<1)+2];
}
public long query(int l, int r)
{
return queryUtil(l, r, 0, 0, n - 1);
}
private long queryUtil(int x, int y, int id, int l, int r)
{
if (l > y || x > r)
return 0;
if (x <= l && r <= y)
{
return tree[id];
}
int mid = ( (l + r) >>1);
// shift(id);
return queryUtil(x, y, (id<<1)|1, l, mid) + queryUtil(x, y, (id<<1)+2, mid + 1, r);
}
public void update(int x, int y, int c) {
update1(x, y, c, 0, 0, n-1);
}
private void update1(int x, int y, int colour, int id, int l, int r)
{
//System.out.println(l+" "+r+" "+x);
if (x > r || y < l)
return;
if (x <= l && r <= y)
{
if(lazy[id] == (r-l+1))
return;
else if(l==r) {
tree[id] = s[(int) tree[id]];
if(tree[id] == 1 || tree[id] == 2)
lazy[id] = 1;
return;
}
}
int mid =( (l + r) >>1);
// shift(id);
if(y<=mid)
update1(x, y, colour, (id<<1) | 1, l, mid);
else if(x>mid)
update1(x, y, colour, (id<<1) + 2, mid + 1, r);
else {
update1(x, y, colour, (id<<1)| 1, l, mid);
update1(x, y, colour, (id<<1) + 2, mid + 1, r);
}
tree[id] = tree[(id<<1)|1] + tree[(id<<1)+2];
lazy[id] = lazy[(id<<1)|1] + lazy[(id<<1)+2];
}
}
private class Pair implements Comparable<Pair>{
long s,h,ans;
public Pair(long a,long b,long c) {
s = a;
h = b;
ans = c;
}
@Override
public int compareTo(Pair arg0)
{
long mul1 = this.s * arg0.h;
long mul2 = this.h * arg0.s;
// if(mul1 != mul2)
if(mul1>mul2)
return -1;
else if(mul2 > mul1)
return 1;
return 0;
// return 0;
}
}
private String solveEqn(long a, long b) {
long x = 0, y = 1, lastx = 1, lasty = 0, temp;
while (b != 0){
long q = a / b;
long r = a % b;
a = b;
b = r;
temp = x;
x = lastx - q * x;
lastx = temp;
temp = y;
y = lasty - q * y;
lasty = temp;
}
return lastx+" "+lasty;
}
private void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
private long pow(long a, long b, long c)
{
if (b == 0)
return 1;
long p = pow(a, b / 2, c);
p = (p * p) % c;
return (b % 2 == 0) ? p : (a * p) % c;
}
private long gcd(long n, long l)
{
if (l == 0)
return n;
return gcd(l, n % l);
}
public static void main(String[] args) throws Exception
{
new Thread(null, new Runnable()
{
@Override
public void run()
{
new Main().solve();
}
}, "1", 1 << 25).start();
// new Main().solve();
}
public StringBuilder solve(){
InputReader(System.in);
/*try {
InputReader(new FileInputStream("C:\\Users\\hardik\\Desktop\\in.txt"));
} catch(FileNotFoundException e) {}
*/
pw = new PrintWriter(System.out);
//ans_sb = new StringBuilder();
soln();
pw.close();
//System.out.println(ans_sb);
return ans_sb;
}
public void InputReader(InputStream stream1)
{
stream = stream1;
}
private boolean isWhitespace(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
private 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++];
}
private 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;
}
private 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;
}
private String nextToken()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private String nextLine()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
private int[] nextIntArray(int n)
{
int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextInt();
}
return arr;
}
private long[] nextLongArray(int n)
{
long[] arr = new long[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextLong();
}
return arr;
}
private void pArray(int[] arr)
{
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
System.out.println();
return;
}
private void pArray(long[] arr)
{
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
System.out.println();
return;
}
private boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
private char nextChar()
{
int c = read();
while (isSpaceChar(c))
c = read();
char c1 = (char) c;
while (!isSpaceChar(c))
c = read();
return c1;
}
private interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
|
Java
|
["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"]
|
2 seconds
|
["30\n13\n4\n22"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"number theory",
"brute force"
] |
078cdef32cb5e60dc66c66cae3d4a57a
|
The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). There is at least one SUM query.
| 2,000 |
For each SUM query print the answer to it.
|
standard output
| |
PASSED
|
8140c5fc7216f8d4a2b533cf61eb022b
|
train_000.jsonl
|
1517582100
|
Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r — for every replace ai with D(ai); SUM l r — calculate . Print the answer for each SUM query.
|
256 megabytes
|
import java.io.*;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class G {
public static void main(String[] args) {
FastReader scan = new FastReader();
PrintWriter out = new PrintWriter(System.out);
Task solver = new Task();
int t = 1;
for(int tt = 1; tt <= t; tt++) solver.solve(tt, scan, out);
out.close();
}
static class Task {
static int n, m, max = (int) 1e6;
static long[] bit;
static int[] a, numDivisor = new int[max+1];
static TreeSet<Integer> canUpdate = new TreeSet<>();
public void solve(int testNumber, FastReader scan, PrintWriter out) {
n = scan.nextInt();
m = scan.nextInt();
bit = new long[n + 1];
a = new int[n];
for(int i = 1; i <= max; i++) {
for(int j = i; j <= max; j += i) numDivisor[j]++;
}
for(int i = 0; i < n; i++) {
a[i] = scan.nextInt();
if(a[i] > 2) canUpdate.add(i);
update(i, a[i]);
}
for(int i = 0; i < m; i++) {
int q = scan.nextInt();
int l = scan.nextInt() - 1, r = scan.nextInt() - 1;
if(q == 2) {
out.println(sum(l - 1, r));
}
else {
Integer at = canUpdate.ceiling(l);
while(at != null && at <= r) {
update(at, numDivisor[a[at]] - a[at]);
a[at] = numDivisor[a[at]];
if(a[at] <= 2) canUpdate.remove(at);
at = canUpdate.higher(at);
}
}
}
}
static void update(int index, int val) {
index++;
while(index <= n) {
bit[index] += val;
index += index & (-index);
}
}
static long sum(int index) {
long ret = 0;
index++;
while(index > 0) {
ret += bit[index];
index -= index & (-index);
}
return ret;
}
static long sum(int l, int r) {
return sum(r) - sum(l);
}
}
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
|
["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"]
|
2 seconds
|
["30\n13\n4\n22"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"number theory",
"brute force"
] |
078cdef32cb5e60dc66c66cae3d4a57a
|
The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). There is at least one SUM query.
| 2,000 |
For each SUM query print the answer to it.
|
standard output
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.