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
e8a4cc4a0c35e72ff388d2d5aae1b21a
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
//cd ~/BAU/ACM-ICPC/Teams/A++/BlackBurn95 //sudo apt-get Accepted import java.io.*; import java.util.*; import java.math.*; import static java.lang.Math.*; import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.Double.parseDouble; import static java.lang.String.*; public class Main { static int n,m; static List<Integer> [] g1,g2; static int [] l; static boolean [][] e; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder out = new StringBuilder(); StringTokenizer tk; tk = new StringTokenizer(in.readLine()); n = parseInt(tk.nextToken()); m = parseInt(tk.nextToken()); g1 = new List[n]; g2 = new List[n]; for(int i=0; i<n; i++) { g1[i] = new ArrayList<>(); g2[i] = new ArrayList<>(); } e = new boolean[n][n]; while(m-- > 0) { tk = new StringTokenizer(in.readLine()); int a = parseInt(tk.nextToken())-1,b = parseInt(tk.nextToken())-1; g1[a].add(b); g1[b].add(a); e[a][b] = e[b][a] = true; } for(int i=0; i<n; i++) { for(int j=i+1; j<n; j++) { if(!e[i][j]) { g2[i].add(j); g2[j].add(i); } } } if(e[0][n-1]) System.out.println(bfs(2,0)); else System.out.println(bfs(1,0)); } static int bfs(int t,int u) { Queue<Integer> q = new LinkedList<>(); q.add(u); l = new int[n]; Arrays.fill(l, -1); l[u] = 0; while(!q.isEmpty()) { u = q.remove(); if(u==n-1) return l[u]; if(t==1) { for(int v : g1[u]) if(l[v]==-1) { l[v] = l[u]+1; q.add(v); } } else if(t==2) { for(int v : g2[u]) if(l[v]==-1) { l[v] = l[u]+1; q.add(v); } } } return -1; } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
a8c3f0985cadb017cb7fe7a669f717d7
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
//cd ~/BAU/ACM-ICPC/Teams/A++/BlackBurn95 //sudo apt-get Accepted import java.io.*; import java.util.*; import java.math.*; import static java.lang.Math.*; import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.Double.parseDouble; import static java.lang.String.*; public class Main { static int n,m; static List<Integer> [] g1,g2; static int [] d; static boolean [][] e; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder out = new StringBuilder(); StringTokenizer tk; tk = new StringTokenizer(in.readLine()); n = parseInt(tk.nextToken()); m = parseInt(tk.nextToken()); g1 = new List[n]; g2 = new List[n]; for(int i=0; i<n; i++) { g1[i] = new ArrayList<>(); g2[i] = new ArrayList<>(); } e = new boolean[n][n]; while(m-- > 0) { tk = new StringTokenizer(in.readLine()); int a = parseInt(tk.nextToken())-1,b = parseInt(tk.nextToken())-1; g1[a].add(b); g1[b].add(a); e[a][b] = e[b][a] = true; } for(int i=0; i<n; i++) { for(int j=i+1; j<n; j++) { if(!e[i][j]) { g2[i].add(j); g2[j].add(i); } } } if(e[0][n-1]) System.out.println(bfs(2,0)); else System.out.println(bfs(1,0)); } static int bfs(int t,int u) { d = new int[n]; Arrays.fill(d, -1); d[0] = 0; Queue<Integer> q = new LinkedList<>(); q.add(0); while(!q.isEmpty()) { u = q.remove(); if(u==n-1) return d[u]; if(t==1) { for(int v : g1[u]) if(d[v]==-1) { d[v] = d[u]+1; q.add(v); } } else { for(int v : g2[u]) if(d[v]==-1) { d[v] = d[u]+1; q.add(v); } } } return -1; } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
e1d27a3e118fe17ac7153fdf019778ea
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.io.PrintWriter; import java.util.*; public class c { public static void main(String[] arg) { new c(); } public c() { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int m = in.nextInt(); int[][] adj = new int[n][n]; int[][] graph = new int[n][n]; for(int i = 0; i < n; i++) { Arrays.fill(adj[i], Integer.MAX_VALUE/3); Arrays.fill(graph[i], Integer.MAX_VALUE/3); } for(int i = 0; i < m; i++) { int v1 = in.nextInt()-1; int v2 = in.nextInt()-1; adj[v1][v2] = adj[v2][v1] = 1; } for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { if(adj[i][j] == Integer.MAX_VALUE/3) graph[i][j] = 1; } } for(int k = 0; k < n; k++) { for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { adj[i][j] = Math.min(adj[i][j], adj[i][k]+adj[k][j]); graph[i][j] = Math.min(graph[i][j], graph[i][k]+graph[k][j]); } } } if(adj[0][n-1] == Integer.MAX_VALUE/3 || graph[0][n-1] == Integer.MAX_VALUE/3) out.println("-1"); else { // System.out.println(adj[0][n-1] + " " + graph[0][n-1]); out.println(Math.max(adj[0][n-1], graph[0][n-1])); } in.close(); out.close(); } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
c11d16bdabd371d0717a9a9f08b82c50
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.util.*; public class A { public static Scanner scn=new Scanner(System.in); public static void main(String[] args) { int n= scn.nextInt(); int m=scn.nextInt(); //Graph boolean g[][]=new boolean[405][405]; boolean visited[]=new boolean[405]; int distance[]=new int[405]; //input edges int u,v; boolean isDirect=false; boolean found=false; for(int i=0;i<m;i++){ u=scn.nextInt(); v=scn.nextInt(); if((u==1 && v==n)||(v==1 && u==n)) isDirect=true; g[u][v]= true; g[v][u]= true; } //TODO: if there is a direct path 1->n, consider second way of commute if(isDirect){ for ( int i=1 ; i<=n ; i++ ) { for (int j=0; j<=n; j++) { if(i!=j){ g[i][j]=!g[i][j]; } } } } //BFS LinkedList<Integer> q = new LinkedList<Integer>(); q.add(1); visited[1]=true; distance[1]=0; int count=0; while(!q.isEmpty()){ int a=q.removeFirst(); if(a==n){ found=true; break;} //get all the childern of "node" into the queue for (int i=1;i<=n;i++) { if(g[a][i] && !visited[i]){ q.add(i); visited[i]=true; distance[i]=distance[a]+1; } } count++; } if(!found) System.out.println(-1); else System.out.println(distance[n]); } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
4eac07e54c29b130793949f9f491fbad
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Queue; import java.util.ArrayDeque; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { int[][] edge; int MAX = (int) 1e8; int n; public void solve(int testNumber, InputReader in, PrintWriter out) { n = in.nextInt(); int m = in.nextInt(); edge = new int[n][n]; for (int i = 0; i < m; i++) { int a = in.nextInt() - 1; int b = in.nextInt() - 1; edge[a][b] = 1; edge[b][a] = 1; } int min = Math.max(bfs(0, 0), bfs(0, 1)); out.print(min >= MAX ? -1 : min); } private int bfs(int start, int ch) { boolean[] vis = new boolean[n]; int[] dis = new int[n]; Arrays.fill(dis, MAX); dis[start] = 0; Queue<Integer> queue = new ArrayDeque<>(); queue.add(start); vis[start] = true; while (!queue.isEmpty()) { int poll = queue.poll(); for (int i = 0; i < n; i++) { if (edge[poll][i] == ch && !vis[i]) { queue.add(i); vis[i] = true; dis[i] = Math.min(dis[i], dis[poll] + 1); } } } return dis[n - 1]; } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch ( IOException e ) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
e1fd93bf5719047fb11fdfedb88cddb5
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
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.LinkedList; import java.util.List; import java.util.Queue; import java.util.StringTokenizer; /** * * @author harera */ public class Main { static int n, m; static List<Integer>[] graph, graph2; static int[] cost; static Boolean[][] e; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer stk = new StringTokenizer(in.readLine()); n = Integer.parseInt(stk.nextToken()); m = Integer.parseInt(stk.nextToken()); cost = new int[n + 1]; Arrays.fill(cost, Integer.MAX_VALUE); cost[1] = 0; graph = new List[n + 1]; graph2 = new List[n + 1]; for (int i = 0; i <= n; i++) { graph[i] = new ArrayList<>(); graph2[i] = new ArrayList<>(); } e = new Boolean[n + 1][n + 1]; for (int i = 0; i < n + 1; i++) { Arrays.fill(e[i], false); } while (m-- > 0) { stk = new StringTokenizer(in.readLine()); int u = Integer.parseInt(stk.nextToken()); int v = Integer.parseInt(stk.nextToken()); graph[u].add(v); graph[v].add(u); e[u][v] = true; e[v][u] = true; } for (int i = 1; i < n + 1; i++) { for (int j = i + 1; j < n + 1; j++) { if (!e[i][j]) { graph2[i].add(j); graph2[j].add(i); } } } if (e[1][n]) { System.out.println(dijkstra(2)); } else { System.out.println(dijkstra(1)); } } public static int dijkstra(int i) { Queue<Integer> q = new LinkedList<>(); q.add(1); Boolean[] visit = new Boolean[n + 1]; Arrays.fill(visit, false); visit[1] = true; while (!q.isEmpty()) { int c = q.poll(); if (c == n) { return cost[c]; } if (i == 1) { for (Integer ind : graph[c]) { if (!visit[ind]) { q.add(ind); visit[ind] = true; cost[ind] = Integer.min(cost[ind], cost[c] + 1); } } } else if (i == 2) { for (Integer ind : graph2[c]) { if (!visit[ind]) { q.add(ind); visit[ind] = true; cost[ind] = Integer.min(cost[ind], cost[c] + 1); } } } } return -1; } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
d5761ace64a3dbbc08515374e24b44a4
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; /** * @author Don Li */ public class TwoRoutes { int n; void solve() { n = in.nextInt(); int m = in.nextInt(); boolean[][] G = new boolean[n][n]; for (int i = 0; i < m; i++) { int u = in.nextInt() - 1, v = in.nextInt() - 1; G[u][v] = true; G[v][u] = true; } int res; if (!G[0][n - 1]) { // there is a road between 0 and n-1 res = bfs(G); } else { // there is a railway between 0 and n-1 reverse(G); res = bfs(G); } out.println(res); } private int bfs(boolean[][] G) { Queue<Integer> qu = new LinkedList<>(); qu.offer(0); boolean[] vis = new boolean[n]; int depth = 0, rightMost = 0, last = 0; while (!qu.isEmpty()) { int u = qu.poll(); if (u == n - 1) return depth; for (int v = 0; v < n; v++) { if (G[u][v] && !vis[v]) { vis[v] = true; qu.offer(v); last = v; } } if (rightMost == u) { rightMost = last; depth++; } } return -1; } private void reverse(boolean[][] G) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i != j) { G[i][j] = !G[i][j]; } } } } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new TwoRoutes().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
743da20da15884d0ca303b7abe7225dc
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) throws FileNotFoundException { //System.setIn(new FileInputStream("input.txt")); Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int m = scanner.nextInt(); int from[] = new int[m]; int to[] = new int[m]; for (int i = 0; i < m; i++) { from[i] = scanner.nextInt(); to[i] = scanner.nextInt(); } Graph graph = new Graph(from,to,n); //graph.show(); int trainRes = graph.bfs(); graph.reverse(); //graph.show(); int autoRes = graph.bfs(); System.out.println(getMaxIfExists(trainRes,autoRes)); } static int getMaxIfExists(int x,int y){ if (x==-1||y==-1){ return -1; }else if(x>=y){return x;} else return y; } } class Graph{ int [][] matrix; Graph(int from[],int to[], int n){ matrix = new int[n][n]; for (int i = 0; i < from.length; i++) { matrix[from[i]-1][to[i]-1] = 1 ; matrix[to[i]-1][from[i]-1] = 1 ; } } void show (){ for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { System.out.print(matrix[i][j]); } System.out.println(); } } int bfs(){//start from 1 Queue queue = new Queue(1000); queue.push(0); int dist[] = new int[matrix.length]; Arrays.fill(dist,-1); dist[0] = 0; while (!queue.isEmpty()){ int v = queue.pop(); for (int i = 0; i < matrix.length; i++) { int to = matrix[v][i]; if (to!=0 && dist[i]==-1) { dist[i] = dist[v]+1; queue.push(i); } } } return dist[matrix.length-1]; } void reverse(){//start from 1 for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { if (matrix[i][j]==0) matrix[i][j]=1; else matrix[i][j]=0; } } } } class Queue{ int [] array; int current; int size; Queue(int size){ array = new int[size]; current = 0; this.size = 0; } void push(int value){ array[size++]= value; } int pop(){ return array[current++]; } boolean isEmpty(){ return current==size; } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
6c54aa1d458b3eec02e4598de1b82810
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.io.*; import java.util.*; public class CF602C { static class Pair { int v, d; Pair(int v, int d) { this.v = v; this.d = d; } @Override public int hashCode() { return v; } @Override public boolean equals(Object o) { Pair p = (Pair) o; return v == p.v; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); boolean[][] bb = new boolean[n][n]; for (int i = 0; i < m; i++) { st = new StringTokenizer(br.readLine()); int u = Integer.parseInt(st.nextToken()) - 1; int v = Integer.parseInt(st.nextToken()) - 1; bb[u][v] = bb[v][u] = true; } Set<Pair> set = new HashSet<>(); LinkedList<Pair> list = new LinkedList<>(); Pair p = new Pair(0, 0); set.add(p); list.addLast(p); while (!list.isEmpty()) { p = list.removeFirst(); if (p.v == n - 1) { System.out.println(p.d); return; } for (int v = 0; v < n; v++) if (bb[0][n - 1] && !bb[p.v][v] || !bb[0][n - 1] && bb[p.v][v]) { Pair q = new Pair(v, p.d + 1); if (set.contains(q)) continue; set.add(q); list.addLast(q); } } System.out.println(-1); } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
cabfcdc1f7b62a5fca5ee2f11d0c2ab2
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class Main { static boolean[][] g; static int n; static boolean [] vis1; static boolean [] vis2; public static void main(String[] args) { Scanner input = new Scanner(System.in); n = input.nextInt(); int m = input.nextInt(); g = new boolean [n+1][n+1]; for(int i = 0;i<m;i++){ int x = input.nextInt(); int y = input.nextInt(); g[x][y]=true; g[y][x]=true; } vis1=new boolean [n+1]; vis2=new boolean [n+1]; int t = bfs(1,n); int r = bfs2(1,n); if(t==-1||r==-1)System.out.println(-1); else System.out.println(Math.max(t, r)); } public static int bfs(int root, int se) { // se = the node we want // root = the node we will began int lev = 0; Queue<Integer> q = new LinkedList<Integer>(); q.add(root); while (!q.isEmpty()) { int size = q.size(); while (size-- > 0) { int a = q.peek(); for (int i = 1; i <= n; i++) { if (g[a][i] == true&&vis1[i]!=true){ if(i==se){ return lev + 1;} q.add(i); vis1[i]=true; } } q.poll(); } lev++; } return -1; } public static int bfs2(int root, int se) { // se = the node we want // root = the node we will began int lev = 0; Queue<Integer> q = new LinkedList<Integer>(); q.add(root); while (!q.isEmpty()) { int size = q.size(); while (size-- > 0) { int a = q.peek(); for (int i = 1; i <= n; i++) { if (g[a][i] == false&&vis2[i]!=true){ if(i==se){ return lev + 1;} q.add(i); vis2[i]=true; } } q.poll(); } lev++; } return -1; } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
d84d3b93e72cf20c172d45c4df82a89b
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.*; import static java.lang.Math.*; public class Main { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); 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 static void main(String[] args) { new Main().run(); // Sworn to fight and die } public static void mergeSort(int[] a) { mergeSort(a, 0, a.length - 1); } private static void mergeSort(int[] a, int levtIndex, int rightIndex) { final int MAGIC_VALUE = 50; if (levtIndex < rightIndex) { if (rightIndex - levtIndex <= MAGIC_VALUE) { insertionSort(a, levtIndex, rightIndex); } else { int middleIndex = (levtIndex + rightIndex) / 2; mergeSort(a, levtIndex, middleIndex); mergeSort(a, middleIndex + 1, rightIndex); merge(a, levtIndex, middleIndex, rightIndex); } } } private static void merge(int[] a, int levtIndex, int middleIndex, int rightIndex) { int length1 = middleIndex - levtIndex + 1; int length2 = rightIndex - middleIndex; int[] levtArray = new int[length1]; int[] rightArray = new int[length2]; System.arraycopy(a, levtIndex, levtArray, 0, length1); System.arraycopy(a, middleIndex + 1, rightArray, 0, length2); for (int k = levtIndex, i = 0, j = 0; k <= rightIndex; k++) { if (i == length1) { a[k] = rightArray[j++]; } else if (j == length2) { a[k] = levtArray[i++]; } else { a[k] = levtArray[i] <= rightArray[j] ? levtArray[i++] : rightArray[j++]; } } } private static void insertionSort(int[] a, int levtIndex, int rightIndex) { for (int i = levtIndex + 1; i <= rightIndex; i++) { int current = a[i]; int j = i - 1; while (j >= levtIndex && a[j] > current) { a[j + 1] = a[j]; j--; } a[j + 1] = current; } } 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); } } class LOL implements Comparable<LOL> { int x; int y; public LOL(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(LOL o) { return (x - o.x); // ----> //return o.x * o.y - x * y; // <---- } } class LOL2 implements Comparable<LOL2> { int x; int y; int z; public LOL2(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } @Override public int compareTo(LOL2 o) { return (z - o.z); // ----> //return o.x * o.y - x * y; // <---- } } class test implements Comparable<test> { long x; long y; public test(long x, long y) { this.x = x; this.y = y; } @Override public int compareTo(test o) { //int compareResult = Long.compare(y, o.y); // ----> //if (compareResult != 0) { // return -compareResult; //} int compareResult = Long.compare(x, o.x); if (compareResult != 0) { return compareResult; } return Long.compare(y, o.y); //return o.x * o.y - x * y; // <---- } } class data { String name; String city; data(String name, String city) { this.city = city; this.name = name; } } class Point { double x; double y; Point(double x, double y) { this.x = x; this.y = y; } double distance(Point temp) { return Math.sqrt((x - temp.x) * (x - temp.x) + (y - temp.y) * (y - temp.y)); } double sqrDist(Point temp) { return ((x - temp.x) * (x - temp.x) + (y - temp.y) * (y - temp.y)); } Point rotate(double alpha) { return new Point(x * cos(alpha) - y * sin(alpha), x * sin(alpha) + y * cos(alpha)); } void sum(Point o) { x += o.x; y += o.y; } void scalarProduct(int alpha) { x *= alpha; y *= alpha; } } class Line { double a; double b; double c; Line(Point A, Point B) { a = B.y - A.y; b = A.x - B.x; c = -A.x * a - A.y * b; } Line(double a, double b, double c) { this.a = a; this.b = b; this.c = c; } Point intersection(Line o) { double det = a * o.b - b * o.a; double det1 = -c * o.b + b * o.c; double det2 = -a * o.c + c * o.a; return new Point(det1 / det, det2 / det); } } /* class Plane { double a; double b; double c; double d; Plane (Point fir, Point sec, Point thi) { double del1 = (sec.y - fir.y) * (thi.z - fir.z) - (thi.y - fir.y) * (sec.z - fir.z); double del2 = (thi.x - fir.x) * (sec.z - fir.z) - (thi.z - fir.z) * (sec.x - fir.x); double del3 = (thi.y - fir.y) * (sec.x - fir.x) - (thi.x - fir.x) * (sec.y - fir.y); a = del1; b = del2; c = del3; d = -fir.x * del1 - fir.y * del2 - fir.z * del3; } double distance(Point point) { return abs(a * point.x + b * point.y + c * point.z + d) / sqrt(a * a + b * b + c * c); } } */ class record implements Comparable<record> { String city; Long score; public record(String name, Long score) { this.city = name; this.score = score; } @Override public int compareTo(record o) { if (o.city.equals(city)) { return 0; } if (score.equals(o.score)) { return 1; } if (score > o.score) { return 666; } else { return -666; } //return Long.compare(score, o.score); } } public long gcd(long a, long b) { if (a == 0 || b == 0) return max(a, b); if (a % b == 0) return b; else return gcd(b, a % b); } boolean prime(long n) { if (n == 1) return false; for (int i = 2; i <= sqrt(n); i++) if (n % i == 0) return false; return true; } public int sum(long n) { int s = 0; while (n > 0) { s += (n % 10); n /= 10; } return s; } /* public void simulation(int k) { long ans = 0; int start = 1; for (int i = 0; i < k; i++) { start *= 10; } for (int i = start/10; i < start; i++) { int locAns = 0; for (int j = start/10; j < start; j++) { if (sum(i + j) == sum(i) + sum(j) ) { ans += 1; locAns += 1; } else { //.println(i + "!!!" + j); } } //out.println(i + " " + locAns); } out.println(ans); }*/ ArrayList<Integer> primes; boolean[] isPrime; public void getPrimes (int n) { isPrime[0] = false; isPrime[1] = false; for (int i = 2; i <= n; i++) { if (isPrime[i]) { primes.add(i); if (1l * i * i <= n) { for (int j = i * i; j <= n; j += i) { isPrime[j] = false; } } } } } public long binPowMod(long a, long b, long mod) { if (b == 0) { return 1 % mod; } if (b % 2 != 0) { return ((a % mod) * (binPowMod(a, b - 1, mod) % mod)) % mod; } else { long temp = binPowMod(a, b / 2, mod) % mod; long ans = (temp * temp) % mod; return ans; } } public long binPow(long a, long b) { if (b == 0) { return 1; } if (b % 2 != 0) { return a * binPow(a, b - 1); } else { long temp = binPow(a, b / 2); long ans = (temp * temp); return ans; } } boolean vis[]; HashMap<Integer, HashSet<Integer>> g; int[] numOfComp; void dfs(int u, int num) { vis[u] = true; numOfComp[u] = num; for (Integer v: g.get(u)) { if (!vis[v]) { dfs(v, num); } } } int p[]; int find(int x) { if (x == p[x]) { return x; } return p[x] = find(p[x]); } boolean merge(int x, int y) { x = find(x); y = find(y); if (p[x] == p[y]) { return false; } p[y] = x; return true; } class Trajectory { double x0; double y0; double vx; double vy; Trajectory(double vx, double vy, double x0, double y0) { this.vx = vx; this.vy = vy; this.x0 = x0; this.y0 = y0; } double y (double x) { return y0 + (x - x0) * (vy / vx) - 5 * (x - x0) * (x - x0) / (vx * vx); } double der(double x) { return (vy / vx) - 10 * (x - x0) / (vx * vx); } } public void solve() throws IOException { int n = readInt(); int maze[][] = new int[n + 1][n + 1]; int m = readInt(); for (int i = 0; i < m; i++) { int u = readInt(); int v = readInt(); maze[u][v] = 1; maze[v][u] = 1; } int dist[] = new int[n + 1]; for (int i = 0; i <= n; i++) { dist[i] = Integer.MAX_VALUE; } ArrayDeque<Integer> q = new ArrayDeque<Integer>(); dist[1] = 0; q.add(1); while(!q.isEmpty()) { int u = q.poll(); for (int v = 1; v <= n; v++) { if (dist[v] > dist[u] + 1 && maze[u][v] == 1) { dist[v] = dist[u] + 1; q.add(v); } } } int bus = dist[n]; for (int i = 0; i <= n; i++) { dist[i] = Integer.MAX_VALUE; } dist[1] = 0; q.add(1); while(!q.isEmpty()) { int u = q.poll(); for (int v = 1; v <= n; v++) { if (dist[v] > dist[u] + 1 && maze[u][v] == 0) { dist[v] = dist[u] + 1; q.add(v); } } } int train = dist[n]; int ans = max(train, bus); if (ans == Integer.MAX_VALUE) { out.print(-1); } else { out.print(ans); } } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
5926c9ae0fbf910cb237d57dfb3205e5
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.util.*; public class C { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int numrw = in.nextInt(); int[][] rw = new int[n][n]; for (int i = 0; i < numrw; i++) { int a = in.nextInt(); int b = in.nextInt(); rw[a-1][b-1] = 1; rw[b-1][a-1] = 1; } int[][] rd = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (rw[i][j] == 0) { rd[i][j] = 1; } else { rd[i][j] = 0; } } } ArrayList<Integer> trainPath = new ArrayList<>(); HashMap<Integer, Integer> trainMap = new HashMap<>(); Queue<Integer> trainQ = new LinkedList<>(); trainQ.add(0); trainMap.put(0, 0); boolean canTr = false; while (!trainQ.isEmpty()) { int vert = trainQ.poll(); if (vert == n-1) { getPath(trainPath, trainMap, n-1); canTr = true; break; } for (int i = 0; i < n; i++) { if (rw[vert][i] == 1 && !trainMap.containsKey(i)) { trainQ.add(i); trainMap.put(i, vert); } } } ArrayList<Integer> roadPath = new ArrayList<>(); HashMap<Integer, Integer> roadMap = new HashMap<>(); Queue<Integer> roadQ = new LinkedList<>(); roadQ.add(0); roadMap.put(0, 0); boolean canR = false; while (!roadQ.isEmpty()) { int vert = roadQ.poll(); if (vert == n-1) { getPath(roadPath, roadMap, n-1); canR = true; break; } for (int i = 0; i < n; i++) { if (rd[vert][i] == 1 && !roadMap.containsKey(i)) { roadQ.add(i); roadMap.put(i, vert); } } } if (canR && canTr) { System.out.println(Math.max(roadPath.size(), trainPath.size())); } else { System.out.println("-1"); } } public static void getPath(ArrayList<Integer> path, HashMap<Integer, Integer> map, int end) { int n = end; while (n != 0) { int temp = map.get(n); n = temp; path.add(n); } Collections.reverse(path); } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
fe31118fb8a7d07e06ed6ea5285b68dd
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class ThetwoRoutes { static ArrayList<Integer> railway[]; static ArrayList<Integer> roads[]; static boolean vis[], taken[][]; static int N, M; static int bfs(ArrayList<Integer>[] adjList) { int[] dist = new int[N]; Arrays.fill(dist, Integer.MAX_VALUE); dist[0] = 0; Queue<Integer> q = new LinkedList<Integer>(); q.add(0); while (!q.isEmpty()) { int u = q.remove(); for (int i = 0; i < adjList[u].size(); i++) { int v = adjList[u].get(i); if (dist[v] == Integer.MAX_VALUE) { dist[v] = dist[u] + 1; q.add(v); } } } return dist[N - 1]; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); N = n; M = m; railway = new ArrayList[n]; roads = new ArrayList[n]; for (int i = 0; i < n; i++) railway[i] = new ArrayList<Integer>(); for (int i = 0; i < n; i++) roads[i] = new ArrayList<Integer>(); taken = new boolean[n][n]; for (int i = 0; i < m; i++) { int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; railway[u].add(v); railway[v].add(u); taken[u][v] = taken[v][u] = true; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) continue; if (!taken[i][j]) { roads[i].add(j); roads[j].add(i); taken[i][j] = true; taken[j][i] = true; } } } // System.out.println("Railways :"); // for (int i = 0; i < n; i++) { // for (int j = 0; j < railway[i].size(); j++) { // System.out.println((i + 1) + " " + (railway[i].get(j) + 1)); // } // } // System.out.println("Roads :"); // for (int i = 0; i < n; i++) { // for (int j = 0; j < roads[i].size(); j++) { // System.out.println((i + 1) + " " + (roads[i].get(j) + 1)); // } // } int railways = bfs(railway); int road = bfs(roads); System.out.println(Math.max(railways, road) == Integer.MAX_VALUE ? -1 : Math.max(railways, road)); // System.out.println(roads); } 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 boolean ready() throws IOException { return br.ready(); } } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
d0e10bfd50e68249df67fbcea09b4f6a
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class C { public static void main(String[] args) { Scanner s = new Scanner(System.in); String[] firstLine = s.nextLine().split(" "); int N = Integer.parseInt(firstLine[0]); int M = Integer.parseInt(firstLine[1]); boolean[][] roads = new boolean[N][N]; boolean done = false; for (int i = 0; i < M; i++) { String[] nextLine = s.nextLine().split(" "); int min = Math.min(Integer.parseInt(nextLine[0]), Integer.parseInt(nextLine[1])); int max = Math.max(Integer.parseInt(nextLine[0]), Integer.parseInt(nextLine[1])); if (min == 1 && max == N) { done = true; } roads[min - 1][max - 1] = true; roads[max - 1][min - 1] = true; } if (done) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { roads[i][j] = !roads[i][j]; } } } int[] distances = new int[N]; for (int i = 0; i < distances.length; i++) { distances[i] = -1; } distances[0] = 0; Queue<Integer> bfs = new LinkedList<Integer>(); bfs.add(0); while (!bfs.isEmpty()) { int considering = bfs.poll(); for (int i = 0; i < roads[considering].length; i++) { if (roads[considering][i] && distances[i] == -1) { distances[i] = distances[considering] + 1; bfs.add(i); } } } System.out.println(distances[N - 1]); s.close(); System.exit(0); } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
36bbf94145aa8acdd35d294e5b84334d
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Queue; import java.util.StringTokenizer; public class C { public static void main(String[] args) { Scanner2 sc = new Scanner2(); final boolean RAIL = true; final boolean ROAD = false; int n = sc.nextInt(); int m = sc.nextInt(); boolean[][] adj = new boolean[n+1][n+1]; for (int i = 0; i < m; i++) { int u = sc.nextInt(); int v = sc.nextInt(); adj[u][v] = RAIL; adj[v][u] = RAIL; } boolean[] marked = new boolean[n+1]; int[] dist = new int[n+1]; Queue<Integer> bfs = new ArrayDeque<>(); bfs.offer(1); marked[1] = true; Arrays.fill(dist, -1); dist[1] = 0; boolean type; if (adj[1][n] == RAIL) { type = ROAD; } else { type = RAIL; } while (!bfs.isEmpty()) { int from = bfs.poll(); for (int to = 1; to <= n; to++) { if (!marked[to] && adj[from][to] == type) { marked[to] = true; dist[to] = dist[from] + 1; bfs.offer(to); } } } System.out.println(dist[n]); } public static class Scanner2 { BufferedReader br; StringTokenizer st; public Scanner2(Reader in) { br = new BufferedReader(in); } public Scanner2() { this(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()); } // Slightly different from java.util.Scanner.nextLine(), // which returns any remaining characters in current line, // if any. String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
62d63da39cdac4d62ad0d27835d1e2e8
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.io.*; import java.util.*; public class B { static private BufferedReader in; static private PrintWriter out; static { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter(new FileWriter("output.txt")); } catch (Exception ex) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } } static StringTokenizer tokenizer; static private String nextString() { while (tokenizer == null || !tokenizer.hasMoreElements()) { try { tokenizer = new StringTokenizer(in.readLine()); } catch (IOException e) { System.err.println("Trouble in reading"); } } return tokenizer.nextToken(); } static private int nextInt() { return Integer.valueOf(nextString()); } static private long nextLong() { return Long.valueOf(nextString()); } static void solve() { int n = nextInt(); int m = nextInt(); boolean[][] adj = new boolean[n][n]; for (int i = 0; i < m; i++) { int lf = nextInt()-1; int r = nextInt()-1; adj[lf][r] = adj[r][lf] = true; } int[] bus = new int[n]; int[] train = new int[n]; int[] pred = new int[n]; boolean[] used = new boolean[n]; Queue<Integer> q = new LinkedList<>(); q.add(0); used[0] = true; while (!q.isEmpty()) { int from = q.poll(); if (from == n-1) break; for (int i = 0; i < n; i++) { if (adj[from][i] && !used[i]) { q.add(i); used[i] = true; pred[i] = from; train[i] = train[from] + 1; } } } if (train[n-1] == 0) { out.print(-1); } else { int prb = n-1; int tmp = train[prb]; train = new int[n]; while (prb != 0) { train[prb] = tmp; tmp--; prb = pred[prb]; } q = new LinkedList<>(); used = new boolean[n]; q.add(0); used[0] = true; while (!q.isEmpty()) { int from = q.poll(); if (from == n-1) break; for (int i = 0; i < n; i++) { if (!adj[from][i] && !used[i] && train[i] != bus[from]+1) { q.add(i); used[i] = true; bus[i] = bus[from] + 1; } } } if (bus[n-1] == 0) out.print(-1); else out.print(Math.max(bus[n-1], train[n-1])); } close(); } public static void close() { if (out != null) out.close(); if (in != null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { solve(); } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
7df708c565729c4deacff05a52660884
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public final class Solution { static int target; static boolean[][] visited , railways , roads; public static void main(String[] args) { Reader input = new Reader(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int n = input.nextInt(), m = input.nextInt() ,u , v; railways = new boolean[n][n]; roads = new boolean[n][n]; visited = new boolean[n][n]; target = n - 1; for(int i = 0 ; i < n ; i++) { Arrays.fill(roads[i], true); roads[i][i] = false; } for(int i = 0 ; i < m ; i++) { u = input.nextInt() - 1; v = input.nextInt() - 1; railways[u][v] = true; railways[v][u] = true; roads[u][v] = false; roads[v][u] = false; } int t1 = bfs1(0) , t2 = bfs2(0); if(t1 == -1 || t2 == -1) out.println(-1); else out.println((int)Math.max(t1 , t2)); out.close(); } public static int bfs1(int start) { LinkedList<Integer> queue = new LinkedList<>(); queue.addLast(start); int count = 0 , count2 = 1; while(!queue.isEmpty()) { int t = 0; for(int j = 0 ; j < count2 ; j++) { int temp = queue.getFirst(); queue.removeFirst(); if(temp == target) { return count; } for(int i = 0 ; i <= target ; i++) { if(!visited[temp][i] && railways[temp][i]) { queue.addLast(i); visited[temp][i] = true; visited[i][temp] = true; t++; } } } count++; count2 = t; } return -1; } public static int bfs2(int start) { LinkedList<Integer> queue = new LinkedList<>(); queue.addLast(start); int count = 0 , count2 = 1; while(!queue.isEmpty()) { int t = 0; for(int j = 0 ; j < count2 ; j++) { int temp = queue.getFirst(); queue.removeFirst(); if(temp == target) { return count; } for(int i = 0 ; i <= target ; i++) { if(!visited[temp][i] && roads[temp][i]) { queue.addLast(i); visited[temp][i] = true; visited[i][temp] = true; t++; } } } count++; count2 = t; } return -1; } public static class Reader { BufferedReader br; StringTokenizer st; public Reader() { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() { try { if(st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); } catch(IOException ex) { ex.printStackTrace(); System.exit(1); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } public String nextLine() { try { return br.readLine(); } catch(IOException ex) { ex.printStackTrace(); System.exit(1); } return ""; } } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
d0d99d8a406ee53eb562fbba854edb8b
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.io.*; import java.lang.reflect.AnnotatedArrayType; import java.lang.reflect.Array; import java.util.*; import java.util.Random; import java.util.StringTokenizer; public class Main { long b = 31; String fileName = ""; ////////////////////// SOLUTION SOLUTION SOLUTION ////////////////////////////// int INF = Integer.MAX_VALUE / 10; long MODULO = 1000*1000*1000+7; void solve() throws IOException { int n = readInt(); int m = readInt(); HashSet<Integer>[] graphTrain = new HashSet[n]; HashSet<Integer>[] graphCar = new HashSet[n]; for (int i = 0; i<n; ++i){ graphTrain[i] = new HashSet<>(); graphCar[i] = new HashSet<>(); for (int j=0; j<n; ++j){ graphCar[i].add(j); } } for (int i=0; i<m; ++i){ int from = readInt() - 1; int to = readInt() - 1; graphTrain[from].add(to); graphTrain[to].add(from); graphCar[from].remove(to); graphCar[to].remove(from); } int[] distTrain = new int[n]; int[] distCar = new int[n]; Arrays.fill(distTrain, INF); Arrays.fill(distCar, INF); distTrain[0] = 0; distCar[0] = 0; ArrayDeque<Integer> q = new ArrayDeque<>(); q.add(0); while (q.size() > 0){ int from = q.poll(); for (int to: graphTrain[from]){ if (distTrain[to] > distTrain[from] + 1){ distTrain[to] = distTrain[from] + 1; q.add(to); } } } q.add(0); while (q.size() > 0){ int from = q.poll(); for (int to: graphCar[from]){ if (distCar[to] > distCar[from] + 1){ distCar[to] = distCar[from] + 1; q.add(to); } } } int ans = Math.max(distCar[n-1], distTrain[n-1]); out.println(ans==INF?-1:ans); } class Point{ int x, y; Point(int x, int y){ this.x = x; this.y = y; } } class Vertex implements Comparable<Vertex>{ int dist, from; Vertex(int b, int c){ this.dist = c; this.from = b; } @Override public int compareTo(Vertex o) { return this.dist-o.dist; } } /////////////////////////////////////////////////////////////////////////////////////////// class DoubleEdge{ int from, to, dist1, dist2; DoubleEdge(int from, int to, int dist1, int dist2){ this.from = from; this.to = to; this.dist1 = dist1; this.dist2 = dist2; } } class Edge{ int from, to, dist; Edge(int from, int to, int dist){ this.from = from; this.to = to; this.dist = dist; } } void readUndirectedGraph (int n, int m, int[][] graph) throws IOException{ Edge[] edges = new Edge[n-1]; int[] countEdges = new int[n]; graph = new int[n][]; for (int i=0; i<n-1; ++i){ int from = readInt() - 1; int to = readInt() - 1; countEdges[from]++; countEdges[to]++; edges[i] = new Edge(from, to, 0); } for (int i=0; i<n; ++i) graph[i] = new int[countEdges[i]]; for (int i=0; i<n-1; ++i){ graph[edges[i].to][--countEdges[edges[i].to]] = edges[i].dist; graph[edges[i].dist][-- countEdges[edges[i].dist]] = edges[i].to; } } class SparseTable{ int[][] rmq; int[] logTable; int n; SparseTable(int[] a){ n = a.length; logTable = new int[n+1]; for(int i = 2; i <= n; ++i){ logTable[i] = logTable[i >> 1] + 1; } rmq = new int[logTable[n] + 1][n]; for(int i=0; i<n; ++i){ rmq[0][i] = a[i]; } for(int k=1; (1 << k) < n; ++k){ for(int i=0; i + (1 << k) <= n; ++i){ int max1 = rmq[k - 1][i]; int max2 = rmq[k-1][i + (1 << (k-1))]; rmq[k][i] = Math.max(max1, max2); } } } int max(int l, int r){ int k = logTable[r - l]; int max1 = rmq[k][l]; int max2 = rmq[k][r - (1 << k) + 1]; return Math.max(max1, max2); } } long checkBit(long mask, int bit){ return (mask >> bit) & 1; } class Dsu{ int[] parent; int countSets; Dsu(int n){ countSets = n; parent = new int[n]; for(int i=0; i<n; ++i){ parent[i] = i; } } int findSet(int a){ if(parent[a] == a) return a; parent[a] = findSet(parent[a]); return parent[a]; } void unionSets(int a, int b){ a = findSet(a); b = findSet(b); if(a!=b){ countSets--; parent[a] = b; } } } static int checkBit(int mask, int bit) { return (mask >> bit) & 1; } boolean isLower(char c){ return c >= 'a' && c <= 'z'; } //////////////////////////////////////////////////////////// class SegmentTree{ int[] t; int n; SegmentTree(int n){ t = new int[4*n]; build(new int[n+1], 1, 1, n); } void build (int a[], int v, int tl, int tr) { if (tl == tr) t[v] = a[tl]; else { int tm = (tl + tr) / 2; build (a, v*2, tl, tm); build (a, v*2+1, tm+1, tr); } } void update (int v, int tl, int tr, int l, int r, int add) { if (l > r) return; if (l == tl && tr == r) t[v] += add; else { int tm = (tl + tr) / 2; update (v*2, tl, tm, l, Math.min(r,tm), add); update (v*2+1, tm+1, tr, Math.max(l,tm+1), r, add); } } int get (int v, int tl, int tr, int pos) { if (tl == tr) return t[v]; int tm = (tl + tr) / 2; if (pos <= tm) return t[v] + get (v*2, tl, tm, pos); else return t[v] + get (v*2+1, tm+1, tr, pos); } } class Fenwik { long[] t; int length; Fenwik(int[] a) { length = a.length + 100; t = new long[length]; for (int i = 0; i < a.length; ++i) { inc(i, a[i]); } } void inc(int ind, int delta) { for (; ind < length; ind = ind | (ind + 1)) { t[ind] = Math.max(delta, t[ind]); } } long getMax(int r) { long sum = 0; for (; r >= 0; r = (r & (r + 1)) - 1) { sum = Math.max(sum, t[r]); } return sum; } } int gcd(int a, int b){ return b == 0 ? a : gcd(b, a%b); } long gcd(long a, long b){ return b == 0 ? a : gcd(b, a%b); } long binPow(long a, long b, long m) { if (b == 0) { return 1; } if (b % 2 == 1) { return ((a % m) * (binPow(a, b - 1, m) % m)) % m; } else { long c = binPow(a, b / 2, m); return (c * c) % m; } } int minInt(int... values) { int min = Integer.MAX_VALUE; for (int value : values) min = Math.min(min, value); return min; } int maxInt(int... values) { int max = Integer.MIN_VALUE; for (int value : values) max = Math.max(max, value); return max; } public static void main(String[] args) throws NumberFormatException, IOException { // TODO Auto-generated method stub new Main().run(); } void run() throws NumberFormatException, IOException { solve(); out.close(); }; BufferedReader in; PrintWriter out; StringTokenizer tok; String delim = " "; Random rnd = new Random(); Main() throws FileNotFoundException { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } catch (Exception e) { if (fileName.isEmpty()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader(fileName + ".in")); out = new PrintWriter(fileName + ".out"); } } tok = new StringTokenizer(""); } String readLine() throws IOException { return in.readLine(); } String readString() throws IOException { while (!tok.hasMoreTokens()) { String nextLine = readLine(); if (null == nextLine) { return null; } tok = new StringTokenizer(nextLine); } return tok.nextToken(); } int readInt() throws NumberFormatException, IOException { return Integer.parseInt(readString()); } byte readByte() throws NumberFormatException, IOException { return Byte.parseByte(readString()); } int[] readIntArray (int n) throws NumberFormatException, IOException { int[] a = new int[n]; for(int i=0; i<n; ++i){ a[i] = readInt(); } return a; } Integer[] readIntegerArray (int n) throws NumberFormatException, IOException { Integer[] a = new Integer[n]; for(int i=0; i<n; ++i){ a[i] = readInt(); } return a; } long readLong() throws NumberFormatException, IOException { return Long.parseLong(readString()); } double readDouble() throws NumberFormatException, IOException { return Double.parseDouble(readString()); } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
4731fb243ad0a597ff3de7e924a6e29d
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.math.BigInteger; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Deque; import java.util.Scanner; public class CFProbC { public static void main(String[] args) { Scanner input = new Scanner(System.in); int towns = input.nextInt(); int railroads = input.nextInt(); boolean[][] railroadAdjacencyMatrix = new boolean[towns][towns]; for (int a = 0; a < railroads; a++) { int start = input.nextInt() - 1; int end = input.nextInt() - 1; railroadAdjacencyMatrix[start][end] = true; railroadAdjacencyMatrix[end][start] = true; } // town 1 is 0 // town n is n-1 if (railroadAdjacencyMatrix[0][towns - 1]) { // the train can go instantly, so we need to just worry about the // bus. // convert the railroad graph to the bus graph invert(railroadAdjacencyMatrix); } else { // The bus can go instantly, just do it normally } Deque<Integer> queue = new ArrayDeque<Integer>(); queue.add(0); boolean[] beenhere = new boolean[towns]; int[] count = new int[towns]; beenhere[0] = true; count[0] = 0; while(queue.size() > 0 && queue.peek() != towns-1){ // System.out.println(queue.toString()); int state = queue.pop(); for(int a = 0; a < towns; a++){ if(railroadAdjacencyMatrix[state][a] && beenhere[a] == false){ queue.add(a); count[a] = count[state] + 1; beenhere[a] = true; } } } if(count[towns-1] == 0){ System.out.println(-1); } else{ System.out.println(count[towns-1]); } } private static void invert(boolean[][] railroadAdjacencyMatrix) { for (int a = 0; a < railroadAdjacencyMatrix.length; a++) { for (int b = 0; b < railroadAdjacencyMatrix.length; b++) { railroadAdjacencyMatrix[a][b] = !railroadAdjacencyMatrix[a][b]; } } } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
5aa5ff56e11fb5ab9f5bc68b423d241e
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.util.Scanner; public class Main { public static class Node{ int index; int level; public Node(int index,int level){ this.index = index; this.level = level; } } public static int bfs(int[][] graph,int edge){ Node source = new Node(0,0); Node [] queue = new Node[graph.length]; int start = 0; int end = 0; queue[end++] = source; boolean[] visited = new boolean[graph.length]; visited[source.index] = true; while(true){ source = queue[start++]; if(source == null)return -1; if(source.index == graph.length-1)return source.level; for(int j=0;j<graph.length;j++){ if(graph[source.index][j] == edge && !visited[j] && source.index!=j){ visited[j] = true; queue[end++] = new Node(j,source.level+1); } } } } public static void main(String [] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int [][] graph = new int[n][n]; for(int i = 0;i<m;i++){ int x = sc.nextInt()-1; int y = sc.nextInt()-1; graph[x][y] = 1; graph[y][x] = 1; } int edge = 1; if(graph[0][n-1] == 1){ edge = 0; } System.out.println(bfs(graph,edge)); } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
22ffdcf735ac77ce0219c32a2dfccf72
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.util.*; import java.io.*; public class C { static List<Integer>[] rails, roads; static int n; public static void main(String... thegame) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); rails = new ArrayList[n]; for(int i = 0; i < n ; i++) rails[i] = new ArrayList<>(); roads = new ArrayList[n]; for(int i = 0; i < n ; i++) roads[i] = new ArrayList<>(); for(int i = 0; i < m; i++){ st = new StringTokenizer(br.readLine()); int u = Integer.parseInt(st.nextToken())-1; int v = Integer.parseInt(st.nextToken())-1; rails[u].add(v); rails[v].add(u); } for(int u = 0; u < n; u++){ for(int v = 0; v < n; v++){ if(u == v) continue; if(!rails[u].contains(v)){ roads[u].add(v); } } } int a = bfs(rails); int b = bfs(roads); if(a == -1 || b == -1) System.out.println(-1); else System.out.println(Math.max(a,b)); } public static int bfs(List<Integer>[] arr){ ArrayList<Integer> q = new ArrayList<>(); q.add(0); int[] dist = new int[n]; Arrays.fill(dist, -1); dist[0] = 0; while(!q.isEmpty()){ int u = q.remove(0); for(int v: arr[u]){ if(dist[v] < 0){ dist[v] = dist[u]+1; q.add(v); } } } return dist[n-1]; } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
45cd27476b61cf16a819a9d8a5d48924
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.util.*; import java.io.*; public class Hue { static class Solution { InputReader in; PrintWriter out; public void bfs(int[] ans,ArrayList<Integer>[] adj) { Queue<Integer> q = new ArrayDeque<Integer>(); ans[1] = 0; q.offer(1); while(!q.isEmpty()) { int now = q.poll(); for (int t : adj[now]) { if (ans[t] == -1) { ans[t] = ans[now]+1; q.offer(t); } } } } public void solve() { int n = in.nextInt(); int m = in.nextInt(); int mat[][] = new int[n+10][n+10]; int ansRoad[] = new int[n+10]; int ansRail[] = new int[n+10]; ArrayList<Integer> road[] = new ArrayList[n+10]; ArrayList<Integer> rail[] = new ArrayList[n+10]; for (int i=1; i<=n; i++) { ansRoad[i] = -1; ansRail[i] = -1; for (int j=1; j<=n; j++) mat[i][j] = -1; } for (int i=0; i<m; i++) { int a = in.nextInt(); int b = in.nextInt(); mat[a][b] = 1; mat[b][a] = 1; } for (int i=1; i<=n; i++) { road[i] = new ArrayList<Integer>(); rail[i] = new ArrayList<Integer>(); for (int j=1; j<=n; j++) { if (mat[i][j] == -1) road[i].add(j); if (mat[i][j] == 1) rail[i].add(j); } } bfs(ansRoad,road); bfs(ansRail,rail); if (ansRoad[n] == -1 || ansRail[n] == -1) out.println(-1); else out.println(Math.max(ansRail[n],ansRoad[n])); } } public static void main(String args[]) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); Solution solution = new Solution(); solution.in = in; solution.out = out; solution.solve(); 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 nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } public String nextLine() { String ret = ""; try { ret = reader.readLine(); } catch(Exception e) {} return ret; } } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
a2052df89a76a9791ef4d34f0ad4752b
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.util.*; public class TwoRoutes { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(); int m = input.nextInt(); int[][] matrix = new int[n][n]; Node[] nodes = new Node[n]; for (int k = 0; k < n; k++) { nodes[k] = new Node(0, k); } for (int i = 0; i < m; i++) { int i1 = input.nextInt(); int i2 = input.nextInt(); matrix[i1 - 1][i2 - 1] = 1; matrix[i2 - 1][i1 - 1] = 1; } int val = matrix[0][n-1]; val = 1 - val; TreeSet<Node> set = new TreeSet<Node>(); PriorityQueue<Node> queue = new PriorityQueue<Node>(); int length = 0; boolean found = false; queue.offer(nodes[0]); while (!queue.isEmpty() && !found) { Node curr = queue.poll(); set.add(curr); for (int i = 0; i < n; i++) { Node nod = nodes[i]; if (matrix[curr.num][i] == val && !set.contains(nodes[i])) { nod.length = curr.length + 1; queue.offer(nod); set.add(nod); if (i == n - 1) { found = true; length = nod.length; } } } } if (found) { System.out.println(length); } else { System.out.println(-1); } } } class Node implements Comparable<Node> { int length; int num; public Node (int length, int num) { this.length = length; this.num = num; } public int compareTo(Node n) { if (length == n.length) { return Integer.compare(num, n.num); } return Integer.compare(length, n.length); } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
950a0a761cef780ed5614486425bfae8
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.io.BufferedReader; import java.io.Closeable; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.List; import java.util.Locale; import java.util.Scanner; import java.util.StringTokenizer; public class Solution { public static final boolean std = true; public static final boolean useFastIn = true; public static final String inputFile = "seq.in"; public static final String outputFile = "seq.out"; public final Scanner in; public final RFScanner fin; public final PrintWriter out; public Solution(Scanner i, PrintWriter o) { in = i; out = o; fin = null; } public Solution(RFScanner i, PrintWriter o) { in = null; out = o; fin = i; } public static void main(String[] args) throws Exception { Solution s; PrintWriter out; Reader is; Closeable in; Locale.setDefault(Locale.ENGLISH); if (std) { is = new InputStreamReader(System.in); out = new PrintWriter(System.out); } else { is = new FileReader(new File(inputFile)); out = new PrintWriter(new File(outputFile)); } if (useFastIn) { in = new RFScanner(is); s = new Solution((RFScanner) in, out); } else { in = new Scanner(is); s = new Solution((Scanner) in, out); } s.run(); in.close(); out.close(); } int n, m; V[] g; public void run() throws Exception { n = fin.nextInt(); m = fin.nextInt(); g = new V[n]; for (int i=0; i<n; i++) { g[i] = new V(i); } for (int i=0; i<m; i++) { V u = g[fin.nextInt()-1]; V v = g[fin.nextInt()-1]; u.iron.add(v); v.iron.add(u); } for (V v : g) { for (V u : g) { if (!v.iron.contains(u)) { v.black.add(u); } } } boolean ironType = false; if (g[0].iron.contains(g[n-1])) { ironType = true; } Deque<V> q = new ArrayDeque<>(); q.add(g[0]); g[0].t = 0; while (!q.isEmpty()) { V cur = q.removeFirst(); List<V> children = !ironType ? cur.iron : cur.black; for (V c : children) { if (cur.t+1 < c.t) { c.t = cur.t+1; c.p = cur; q.add(c); } } } V f = g[n-1]; if (f.p == null) { out.println(-1); return; } out.println(f.t); } class V { public final int id; public final List<V> iron = new ArrayList<>(); public final List<V> black = new ArrayList<>(); public int t = Integer.MAX_VALUE; public V p = null; public V(int i) { id = i; } } static class RFScanner implements Closeable { private BufferedReader reader; private StringTokenizer tokenizer; public RFScanner(Reader is) { reader = new BufferedReader(is); tokenizer = new StringTokenizer(""); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public float nextFloat() throws IOException { return Float.parseFloat(next()); } public String next() throws IOException { if (hasNext()) return tokenizer.nextToken(); return null; } public String nextLine() throws IOException { tokenizer = new StringTokenizer(""); return reader.readLine(); } public boolean hasNext() throws IOException { while (!tokenizer.hasMoreTokens()) { String s = reader.readLine(); if (s == null) { return false; } tokenizer = new StringTokenizer(s); } return true; } @Override public void close() throws IOException { reader.close(); } } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
5171668ec52d99a60c325a0b3f626ee5
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.io.*; import java.util.*; public class C602 { public static void main(String[] args) throws IOException { input.init(System.in); PrintWriter out = new PrintWriter(System.out); int n = input.nextInt(), m = input.nextInt(); int[][] rail = new int[n][n], bus = new int[n][n]; for(int i = 0; i<n; i++) { Arrays.fill(rail[i], 999999); Arrays.fill(bus[i], 999999); rail[i][i] = bus[i][i] = 0; } for(int i = 0; i<m; i++) { int a = input.nextInt()-1, b = input.nextInt()-1; rail[a][b] = rail[b][a] = 1; } for(int i = 0; i<n; i++) for(int j = i+1; j<n; j++) { if(rail[i][j] != 1) bus[i][j] = bus[j][i] = 1; } boolean railCan = rail[0][n-1] == 1; for(int k = 0; k<n; k++) for(int i = 0; i<n; i++) for(int j = 0; j<n; j++) { rail[i][j] = Math.min(rail[i][j], rail[i][k] + rail[k][j]); bus[i][j] = Math.min(bus[i][j], bus[i][k] + bus[k][j]); } int res = 999999; if(railCan) res = (bus[0][n-1]); else res =(rail[0][n-1]); out.println(res > 1e5 ? -1 : res); out.close(); } public static class input { static BufferedReader reader; static StringTokenizer tokenizer; static void init(InputStream input) { reader = new BufferedReader(new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } static String next() throws IOException { while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
325c537079892b84efb96f66e95d2796
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.util.LinkedList; import java.util.HashSet; import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.util.Collection; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Queue; import java.io.IOException; import java.util.Set; import java.util.StringTokenizer; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); boolean[][] adj = new boolean[n+1][n+1]; for (int i=0; i<m; i++){ int v1 = in.nextInt(); int v2 = in.nextInt(); adj[v1][v2] = true; adj[v2][v1] = true; } int dist; if (adj[1][n]){ boolean[][] adj2 = new boolean[n+1][n+1]; for (int i=1; i<=n;i++){ for (int j=1; j<=n; j++){ if (i != j){ adj2[i][j] = !adj[i][j]; } } } dist = bfs(adj2,n); } else { dist = bfs(adj,n); } if (dist == -1){ out.println(-1); } else { out.println(dist); } } static class Element{ int node, cost; public Element(int node, int cost) { this.node = node; this.cost = cost; } } private int bfs(boolean[][] adj, int n) { Queue<Element> q = new LinkedList<Element>(); q.add(new Element(1, 0)); Set<Integer> visited = new HashSet<Integer>(); visited.add(1); while (!q.isEmpty()){ Element e = q.poll(); if (e.node == n){ return e.cost; } for (int i=1; i<=n; i++){ if (adj[e.node][i] && !visited.contains(i)){ visited.add(i); q.add(new Element(i, e.cost+1)); } } } return -1; } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream){ reader = new BufferedReader(new InputStreamReader(stream)); } public String next(){ while (tokenizer == null || !tokenizer.hasMoreTokens()){ try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException("FATAL ERROR", e); } } return tokenizer.nextToken(); } public int nextInt(){ return Integer.valueOf(next()); } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
4612f2b3b888e992ee30cf4673f36eca
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.util.*; import java.io.*; public class Main{ public static void main(String args[]) { InputReader in=new InputReader(System.in); int n = in.nextInt(),m=in.nextInt(); boolean train[][]=new boolean[n+1][n+1]; boolean bus[][]=new boolean[n+1][n+1]; boolean visited[][]=new boolean[n+1][n+1]; int minNum[][]=new int[n+1][n+1]; for(int i=0;i<m;i++) { int a=in.nextInt(),b=in.nextInt(); train[a][b]=true; train[b][a]=true; } for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { if(i!=j) bus[i][j]=!train[i][j]; minNum[i][j]=1000000000; } } visited[1][1]=true; minNum[1][1]=0; Queue<pair> st=new LinkedList<pair>(); st.add(new pair(1,1)); while(!st.isEmpty()) { pair p=st.remove(); //if(p.x==3 && p.y==2) System.out.println(bus[p.x][3] +" "+ !visited[p.x][3] +" "+ (3!=p.x || 3==n)); for(int i=1;i<=n;i++) { if(train[p.x][i] && !visited[i][p.y] && (i!=p.y || i==n)) { visited[i][p.y]=true; minNum[i][p.y]=minNum[p.x][p.y]+1; st.add(new pair(i,p.y)); //System.out.println(p.x+" "+p.y+" "+i+" "+p.y); } if(bus[p.y][i] && !visited[p.x][i] && (i!=p.x || i==n)) { visited[p.x][i]=true; minNum[p.x][i]=minNum[p.x][p.y]+1; st.add(new pair(p.x,i)); //System.out.println(p.x+" "+p.y+" "+p.x+" "+i); } } } if(minNum[n][n]==1000000000) System.out.println("-1"); else System.out.println(minNum[n][n]-1); } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } } class pair{ int x,y; pair(int x,int y){ this.x=x; this.y=y; } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
5c8a08aaec59fb467ac3a81494c758f4
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Queue; import java.util.LinkedList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author mthai */ 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); CF_602C solver = new CF_602C(); solver.solve(1, in, out); out.close(); } static class CF_602C { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(), m = in.nextInt(); boolean[][] rails = new boolean[n + 1][n + 1]; boolean[][] roads = new boolean[n + 1][n + 1]; for (int i = 1; i <= n; ++i) Arrays.fill(roads[i], true); for (int i = 0; i < m; ++i) { int x = in.nextInt(), y = in.nextInt(); rails[x][y] = rails[y][x] = true; roads[x][y] = roads[y][x] = false; } int rail = bfs(rails, n);//System.out.println("--------------"); int road = bfs(roads, n); out.println(rail * road < 0 ? -1 : Math.max(rail, road)); } int bfs(boolean[][] graph, int n) { Queue<Integer> q = new LinkedList<>(); boolean[] visited = new boolean[n + 1]; q.add(1); visited[1] = true; int min = -1; int[] len = new int[n + 1]; while (q.size() > 0) { int v = q.poll(); //System.out.println("visit " + v); for (int i = 1; i <= n; ++i) { if (!visited[i] && graph[v][i]) { q.add(i); visited[i] = true; len[i] = len[v] + 1; if (i == n) { min = (min == -1) ? len[i] : Math.min(len[i], min); } } } } return min; } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
6acebaf3a725259413b39dcad498e22c
train_002.jsonl
1535387700
This problem is interactive.You should guess hidden number $$$x$$$ which is between $$$1$$$ and $$$M = 10004205361450474$$$, inclusive.You could use up to $$$5$$$ queries.In each query, you can output an increasing sequence of $$$k \leq x$$$ integers, each between $$$1$$$ and $$$M$$$, inclusive, and you will obtain one of the following as an answer: either the hidden number belongs to your query sequence, in this case you immediately win; or you will be given where the hidden number is located with respect to your query sequence, that is, either it is less than all numbers from the sequence, greater than all numbers from the sequence, or you will be given such an $$$i$$$ that the hidden number $$$x$$$ is between the $$$i$$$-th and the $$$(i+1)$$$-st numbers of your sequence. See the interaction section for clarity.Be aware that the interactor is adaptive, i.e. the hidden number can depend on queries the solution makes. However, it is guaranteed that for any solution the interactor works non-distinguishable from the situation when the hidden number is fixed beforehand.Hacks are allowed only with fixed hidden number. A hack is represented by a single integer between $$$1$$$ and $$$M$$$. In all pretests the hidden number is fixed as well.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class G { static PrintWriter out = new PrintWriter(System.out); static FS in = new FS(); static long dp[][]; static int MAXK = 10000; static final boolean debug = false; static long goal = 21; public static void main(String[] args) { dp = new long[6][MAXK+1]; for(long a[] : dp) Arrays.fill(a, -1); int qsLeft = 5; long startOfRange = 1; while(qsLeft > 0) { long print[] = getQs(qsLeft, startOfRange); int res = query(print); if(res == -1 || res == -2) break; qsLeft--; if(res != 0) startOfRange = print[res-1]+1; } out.close(); } static int query(long vals[]) { out.println(vals.length); for(long ll : vals) out.print(ll+" "); out.println(); out.flush(); if(!debug) { return in.nextInt(); } else { for(int i = 0; i < vals.length; i++) { if(goal == vals[i]) return -1; if(goal < vals[i]) return i; } return vals.length; } } static long[] getQs(int qsLeft, long startOfRange) { int leftBound = (int) Math.min(MAXK, startOfRange); long res[] = new long[leftBound]; if(qsLeft == 1) { for(int i = 0; i < leftBound; i++) res[i] = startOfRange+i; return res; } long canCover = 0; int curL = leftBound; for(int i = 0; i < leftBound; i++) { canCover += go(qsLeft-1, curL) + 1; curL = (int) Math.min(MAXK, curL + go(qsLeft-1, curL) + 1); res[i] = canCover + startOfRange - 1; } return res; } // returns the range we can cover with X queries left and maxK static long go(int qsLeft, int leftBound) { if(qsLeft == 1) return leftBound; if(dp[qsLeft][leftBound] != -1) return dp[qsLeft][leftBound]; long res = 0; int curL = leftBound; for(int i = 0; i < leftBound; i++) { res += go(qsLeft-1, curL) + 1; // guess some val and worst case is to the left curL = (int) Math.min(MAXK, curL + go(qsLeft-1, curL) + 1); } res += go(qsLeft-1, curL); return dp[qsLeft][leftBound] = res; } static class FS{ BufferedReader br; StringTokenizer st; public FS() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while(st == null || !st.hasMoreElements()) { try {st = new StringTokenizer(br.readLine());} catch(Exception e) { throw null;} } return st.nextToken(); } int nextInt() { return Integer.parseInt(next());} double nextDouble() { return Double.parseDouble(next());} long nextLong() { return Long.parseLong(next());} int[] NIA(int n) { int r[] = new int[n]; for(int i = 0; i < n; i++) r[i] = nextInt(); return r; } long[] NLA(int n) { long r[] = new long[n]; for(int i = 0; i < n; i++) r[i] = nextLong(); return r; } char[][] grid(int r, int c){ char res[][] = new char[r][c]; for(int i = 0; i < r; i++) { char l[] = next().toCharArray(); for(int j = 0; j < c; j++) { res[i][j] = l[j]; } } return res; } } }
Java
["2\n\n0\n\n-1"]
2 seconds
["2 2 3\n\n2 20 30\n\n3 5 7 9"]
NoteIn the first example the number $$$5$$$ is hidden.
Java 8
standard input
[ "dp", "interactive" ]
fff0deb3f5f2df8935684abfe07c31bf
null
3,000
null
standard output
PASSED
434ff89d3ce7f40ca64001878fa313ea
train_002.jsonl
1535387700
This problem is interactive.You should guess hidden number $$$x$$$ which is between $$$1$$$ and $$$M = 10004205361450474$$$, inclusive.You could use up to $$$5$$$ queries.In each query, you can output an increasing sequence of $$$k \leq x$$$ integers, each between $$$1$$$ and $$$M$$$, inclusive, and you will obtain one of the following as an answer: either the hidden number belongs to your query sequence, in this case you immediately win; or you will be given where the hidden number is located with respect to your query sequence, that is, either it is less than all numbers from the sequence, greater than all numbers from the sequence, or you will be given such an $$$i$$$ that the hidden number $$$x$$$ is between the $$$i$$$-th and the $$$(i+1)$$$-st numbers of your sequence. See the interaction section for clarity.Be aware that the interactor is adaptive, i.e. the hidden number can depend on queries the solution makes. However, it is guaranteed that for any solution the interactor works non-distinguishable from the situation when the hidden number is fixed beforehand.Hacks are allowed only with fixed hidden number. A hack is represented by a single integer between $$$1$$$ and $$$M$$$. In all pretests the hidden number is fixed as well.
256 megabytes
import java.io.*; import java.util.*; public class Codeforces1028G { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //StringTokenizer st = new StringTokenizer(br.readLine()); //Make sure size equals M - in fact it equals M+1! //System.out.println(size(5, 1)); long start = 1; int query = 5; boolean notfound = true; while (notfound) { query--; int length = (int) Math.min(10000, start); System.out.print(length + " "); if (query == 0) { for (int i = 0; i < length; i++) { System.out.print((start+i) + " "); } System.out.println(); System.out.flush(); StringTokenizer st = new StringTokenizer(br.readLine()); notfound = false; } else { long[] list = new long[length]; list[0] = size(query, start)+1; System.out.print(list[0] + " "); for (int i = 1; i < length; i++) { list[i] = size(query, list[i-1]+1)+1; System.out.print(list[i] + " "); } System.out.println(); System.out.flush(); //determine next start value StringTokenizer st = new StringTokenizer(br.readLine()); int val = Integer.parseInt(st.nextToken()); if (val == -1) { notfound = false; } else if (val > 0) { start = list[val-1]+1; } } } } public static long size(int query, long start) { if (query == 1) { return (start-1 + Math.min(10000, start)); } else if (start >= 10000) { return ((long) Math.pow(10001, query)+start-2); } else { int length = (int) Math.min(10000, start); long[] list = new long[length]; list[0] = size(query-1, start)+1; for (int i = 1; i < length; i++) { list[i] = size(query-1, list[i-1]+1)+1; } return (size(query-1, list[length-1]+1)); } } }
Java
["2\n\n0\n\n-1"]
2 seconds
["2 2 3\n\n2 20 30\n\n3 5 7 9"]
NoteIn the first example the number $$$5$$$ is hidden.
Java 8
standard input
[ "dp", "interactive" ]
fff0deb3f5f2df8935684abfe07c31bf
null
3,000
null
standard output
PASSED
b0a9cf83962ca19bd8e0ceaef287697a
train_002.jsonl
1535387700
This problem is interactive.You should guess hidden number $$$x$$$ which is between $$$1$$$ and $$$M = 10004205361450474$$$, inclusive.You could use up to $$$5$$$ queries.In each query, you can output an increasing sequence of $$$k \leq x$$$ integers, each between $$$1$$$ and $$$M$$$, inclusive, and you will obtain one of the following as an answer: either the hidden number belongs to your query sequence, in this case you immediately win; or you will be given where the hidden number is located with respect to your query sequence, that is, either it is less than all numbers from the sequence, greater than all numbers from the sequence, or you will be given such an $$$i$$$ that the hidden number $$$x$$$ is between the $$$i$$$-th and the $$$(i+1)$$$-st numbers of your sequence. See the interaction section for clarity.Be aware that the interactor is adaptive, i.e. the hidden number can depend on queries the solution makes. However, it is guaranteed that for any solution the interactor works non-distinguishable from the situation when the hidden number is fixed beforehand.Hacks are allowed only with fixed hidden number. A hack is represented by a single integer between $$$1$$$ and $$$M$$$. In all pretests the hidden number is fixed as well.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.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 Egor Kulikov (egor@egork.net) */ 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); G solver = new G(); solver.solve(1, in, out); out.close(); } static class G { long[] moves = {204761410474L}; public void solve(int testNumber, InputReader in, OutputWriter out) { long left = 1; long right = 10004205361450474L; for (int i = 0; i < 5; i++) { long[] request; if (i == 0) { request = new long[2]; request[0] = 1; request[1] = moves[0]; } else { request = request(5 - i, left, right); } out.printLine(request); out.flush(); int result = in.readInt(); if (result == -1) { return; } if (result == 0) { right = request[1] - 1; } else if (result == request[0]) { left = request[result] + 1; } else { left = request[result] + 1; right = request[result + 1] - 1; } } } long bigMove(int moves) { long result = 0; for (int i = 0; i < moves; i++) { result *= 10001; result += 10000; } return result; } long[] request(int moves, long left, long right) { long[] request = new long[(int) (1 + Math.min(left, 10000))]; request[0] = request.length - 1; for (int i = 1; i < request.length; i++) { if (left > right) { request[0] = i - 1; request = Arrays.copyOf(request, i); return request; } if (left >= 10000) { long next = bigMove(moves - 1) + left; request[i] = Math.min(next, right); left = next + 1; } else { long from = left; long to = right; while (from < to) { long middle = (from + to + 1) >> 1; if (fit(moves - 1, left, middle - 1)) { from = middle; } else { to = middle - 1; } } request[i] = from; left = from + 1; } } if (!fit(moves - 1, left, right)) { return null; } return request; } private boolean fit(int moves, long left, long right) { if (left > right) { return true; } if (moves == 0) { return false; } long max = Math.min(left, 10000); for (int i = 1; i < moves; i++) { max *= 10001; max += 10000; } if (right - left >= max) { return false; } if (left >= 10000) { return true; } int length = (int) (1 + Math.min(left, 10000)); for (int i = 1; i < length; i++) { if (left > right) { return true; } if (left >= 10000) { long next = bigMove(moves - 1) + left; left = next + 1; } else { long from = left; long to = right; while (from < to) { long middle = (from + to + 1) >> 1; if (fit(moves - 1, left, middle - 1)) { from = middle; } else { to = middle - 1; } } left = from + 1; } } if (!fit(moves - 1, left, right)) { return false; } return true; } } 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(long[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) { writer.print(' '); } writer.print(array[i]); } } public void printLine(long[] array) { print(array); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } 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 readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["2\n\n0\n\n-1"]
2 seconds
["2 2 3\n\n2 20 30\n\n3 5 7 9"]
NoteIn the first example the number $$$5$$$ is hidden.
Java 8
standard input
[ "dp", "interactive" ]
fff0deb3f5f2df8935684abfe07c31bf
null
3,000
null
standard output
PASSED
e3fb180458d3a637c7688b7815cbdf79
train_002.jsonl
1535387700
This problem is interactive.You should guess hidden number $$$x$$$ which is between $$$1$$$ and $$$M = 10004205361450474$$$, inclusive.You could use up to $$$5$$$ queries.In each query, you can output an increasing sequence of $$$k \leq x$$$ integers, each between $$$1$$$ and $$$M$$$, inclusive, and you will obtain one of the following as an answer: either the hidden number belongs to your query sequence, in this case you immediately win; or you will be given where the hidden number is located with respect to your query sequence, that is, either it is less than all numbers from the sequence, greater than all numbers from the sequence, or you will be given such an $$$i$$$ that the hidden number $$$x$$$ is between the $$$i$$$-th and the $$$(i+1)$$$-st numbers of your sequence. See the interaction section for clarity.Be aware that the interactor is adaptive, i.e. the hidden number can depend on queries the solution makes. However, it is guaranteed that for any solution the interactor works non-distinguishable from the situation when the hidden number is fixed beforehand.Hacks are allowed only with fixed hidden number. A hack is represented by a single integer between $$$1$$$ and $$$M$$$. In all pretests the hidden number is fixed as well.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.io.OutputStreamWriter; import java.io.OutputStream; import java.io.PrintStream; import java.io.IOException; import java.io.UncheckedIOException; import java.io.Closeable; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); GGuessTheNumber solver = new GGuessTheNumber(); solver.solve(1, in, out); out.close(); } } static class GGuessTheNumber { FastInput in; FastOutput out; long M = 10004205361450474L; long[][] dp = new long[10001][6]; { SequenceUtils.deepFill(dp, -1L); } public void solve(int testNumber, FastInput in, FastOutput out) { this.in = in; this.out = out; try { solve(); } catch (RuntimeException e) { } } public void solve() { long l = 1; LongList list = new LongList(10000); System.err.println("dp(1,2)=" + dp(1, 2)); for (int q = 5; q >= 1; q--) { long len = 0; list.clear(); for (int i = 0; i < l && i < 10000; i++) { len += dp(l + len + i, q - 1); list.add(l + len + i); } while (list.tail() > M) { list.pop(); } int ans = ask(list); if (ans == 0) { continue; } l = list.get(ans - 1) + 1; } } public long dp(long l, int q) { return dp((int) Math.min(l, 10000), q); } public long dp(int l, int q) { if (q == 0) { return 0; } if (dp[l][q] == -1) { long len = 0; for (int i = 0; i <= l; i++) { if (l + len >= 10000) { long a = dp(l + len + i, q - 1); long b = l - i + 1; len += DigitUtils.isMultiplicationOverflow(a, b, M) ? M : a * b; break; } len += dp(l + len + i, q - 1); } len += l; dp[l][q] = Math.min(M, len); } return dp[l][q]; } private int ask(LongList points) { out.println(points.size()); for (int i = 0; i < points.size(); i++) { out.append(points.get(i)).append(' '); } out.println().flush(); int ans = in.readInt(); if (ans < 0) { throw new RuntimeException(); } return ans; } } static class DigitUtils { private DigitUtils() { } public static boolean isMultiplicationOverflow(long a, long b, long limit) { if (limit < 0) { limit = -limit; } if (a < 0) { a = -a; } if (b < 0) { b = -b; } if (a == 0 || b == 0) { return false; } //a * b > limit => a > limit / b return a > limit / b; } } static class SequenceUtils { public static void deepFill(Object array, long val) { if (!array.getClass().isArray()) { throw new IllegalArgumentException(); } if (array instanceof long[]) { long[] longArray = (long[]) array; Arrays.fill(longArray, val); } else { Object[] objArray = (Object[]) array; for (Object obj : objArray) { deepFill(obj, val); } } } public static boolean equal(long[] a, int al, int ar, long[] b, int bl, int br) { if ((ar - al) != (br - bl)) { return false; } for (int i = al, j = bl; i <= ar; i++, j++) { if (a[i] != b[j]) { return false; } } return true; } } static class FastOutput implements AutoCloseable, Closeable, Appendable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput append(char c) { cache.append(c); return this; } public FastOutput append(long c) { cache.append(c); return this; } public FastOutput println(int c) { cache.append(c); println(); return this; } public FastOutput println() { cache.append(System.lineSeparator()); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static class LongList implements Cloneable { private int size; private int cap; private long[] data; private static final long[] EMPTY = new long[0]; public LongList(int cap) { this.cap = cap; if (cap == 0) { data = EMPTY; } else { data = new long[cap]; } } public LongList(LongList list) { this.size = list.size; this.cap = list.cap; this.data = Arrays.copyOf(list.data, size); } public LongList() { this(0); } public void ensureSpace(int req) { if (req > cap) { while (cap < req) { cap = Math.max(cap + 10, 2 * cap); } data = Arrays.copyOf(data, cap); } } private void checkRange(int i) { if (i < 0 || i >= size) { throw new ArrayIndexOutOfBoundsException(); } } public long get(int i) { checkRange(i); return data[i]; } public void add(long x) { ensureSpace(size + 1); data[size++] = x; } public void addAll(long[] x, int offset, int len) { ensureSpace(size + len); System.arraycopy(x, offset, data, size, len); size += len; } public void addAll(LongList list) { addAll(list.data, 0, list.size); } public long tail() { checkRange(0); return data[size - 1]; } public long pop() { return data[--size]; } public int size() { return size; } public long[] toArray() { return Arrays.copyOf(data, size); } public void clear() { size = 0; } public String toString() { return Arrays.toString(toArray()); } public boolean equals(Object obj) { if (!(obj instanceof LongList)) { return false; } LongList other = (LongList) obj; return SequenceUtils.equal(data, 0, size - 1, other.data, 0, other.size - 1); } public int hashCode() { int h = 1; for (int i = 0; i < size; i++) { h = h * 31 + Long.hashCode(data[i]); } return h; } public LongList clone() { LongList ans = new LongList(); ans.addAll(this); return ans; } } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } } }
Java
["2\n\n0\n\n-1"]
2 seconds
["2 2 3\n\n2 20 30\n\n3 5 7 9"]
NoteIn the first example the number $$$5$$$ is hidden.
Java 8
standard input
[ "dp", "interactive" ]
fff0deb3f5f2df8935684abfe07c31bf
null
3,000
null
standard output
PASSED
6a2b6a1c5f1f58e8a5e5bc5f3fb909ab
train_002.jsonl
1535387700
This problem is interactive.You should guess hidden number $$$x$$$ which is between $$$1$$$ and $$$M = 10004205361450474$$$, inclusive.You could use up to $$$5$$$ queries.In each query, you can output an increasing sequence of $$$k \leq x$$$ integers, each between $$$1$$$ and $$$M$$$, inclusive, and you will obtain one of the following as an answer: either the hidden number belongs to your query sequence, in this case you immediately win; or you will be given where the hidden number is located with respect to your query sequence, that is, either it is less than all numbers from the sequence, greater than all numbers from the sequence, or you will be given such an $$$i$$$ that the hidden number $$$x$$$ is between the $$$i$$$-th and the $$$(i+1)$$$-st numbers of your sequence. See the interaction section for clarity.Be aware that the interactor is adaptive, i.e. the hidden number can depend on queries the solution makes. However, it is guaranteed that for any solution the interactor works non-distinguishable from the situation when the hidden number is fixed beforehand.Hacks are allowed only with fixed hidden number. A hack is represented by a single integer between $$$1$$$ and $$$M$$$. In all pretests the hidden number is fixed as well.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Vadim Semenov */ 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); TaskG solver = new TaskG(); solver.solve(1, in, out); out.close(); } static final class TaskG { private static final int MAX_QUERIES = 5; private static final int MAX_QUERY_LENGTH = 10000; private static final long MAX_VALUE = 10004205361450474L; private long[][] mem = new long[MAX_QUERIES + 1][MAX_QUERY_LENGTH + 1]; public void solve(int __, InputReader in, PrintWriter out) { long left = 1; long right = MAX_VALUE + 1; for (int queriesLeft = MAX_QUERIES; queriesLeft >= 1; queriesLeft--) { long[] query = new long[(int) Math.min(left, MAX_QUERY_LENGTH)]; long from = left; int size = -1; while (++size < query.length && from < right) { query[size] = Math.min(right - 1, from + canGuess(queriesLeft - 1, from)); from = query[size] + 1; } int result = makeQuery(query, size, in, out); if (result < 0) return; if (result == 0) { right = query[result]; } else if (result == size) { left = query[result - 1] + 1; } else { left = query[result - 1] + 1; right = query[result]; } } throw new AssertionError(); } private int makeQuery(long[] query, int size, InputReader in, PrintWriter out) { out.print(size); for (int i = 0; i < size; ++i) { out.print(' '); out.print(query[i]); } out.println(); out.flush(); return in.nextInt(); } private long canGuess(int queriesLeft, long left) { return canGuess(queriesLeft, (int) Math.min(left, MAX_QUERY_LENGTH)); } private long canGuess(int queriesLeft, int left) { if (queriesLeft < 2) { return queriesLeft * left; } if (mem[queriesLeft][left] == 0) { long length = canGuess(queriesLeft - 1, left) + 1; for (int i = 1; i < left; ++i) { length += canGuess(queriesLeft - 1, left + length) + 1; if (length > MAX_VALUE) break; } length += canGuess(queriesLeft - 1, left + length); mem[queriesLeft][left] = Math.min(length, MAX_VALUE); // mem[queriesLeft][left] = length; } return mem[queriesLeft][left]; } } static class InputReader { private final BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); } public int nextInt() { return Integer.parseInt(next()); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(readLine()); } return tokenizer.nextToken(); } public String readLine() { String line; try { line = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return line; } } }
Java
["2\n\n0\n\n-1"]
2 seconds
["2 2 3\n\n2 20 30\n\n3 5 7 9"]
NoteIn the first example the number $$$5$$$ is hidden.
Java 8
standard input
[ "dp", "interactive" ]
fff0deb3f5f2df8935684abfe07c31bf
null
3,000
null
standard output
PASSED
dfe8d7bdbf35102edd57e8f89007e8a9
train_002.jsonl
1535387700
This problem is interactive.You should guess hidden number $$$x$$$ which is between $$$1$$$ and $$$M = 10004205361450474$$$, inclusive.You could use up to $$$5$$$ queries.In each query, you can output an increasing sequence of $$$k \leq x$$$ integers, each between $$$1$$$ and $$$M$$$, inclusive, and you will obtain one of the following as an answer: either the hidden number belongs to your query sequence, in this case you immediately win; or you will be given where the hidden number is located with respect to your query sequence, that is, either it is less than all numbers from the sequence, greater than all numbers from the sequence, or you will be given such an $$$i$$$ that the hidden number $$$x$$$ is between the $$$i$$$-th and the $$$(i+1)$$$-st numbers of your sequence. See the interaction section for clarity.Be aware that the interactor is adaptive, i.e. the hidden number can depend on queries the solution makes. However, it is guaranteed that for any solution the interactor works non-distinguishable from the situation when the hidden number is fixed beforehand.Hacks are allowed only with fixed hidden number. A hack is represented by a single integer between $$$1$$$ and $$$M$$$. In all pretests the hidden number is fixed as well.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; import java.util.stream.*; public class G { static final int K = 10000; static final int Q = 5; static final long M = 10004205361450475L; long[][] dp = new long[Q + 1][K + 1]; { for (long[] row : dp) { Arrays.fill(row, -1); } } long go(long low, int qs) { if (qs == 0) { return 0; } // if (qs == 1) { // return Math.min(low, K); // } int now = (int) Math.min(low, K); if (dp[qs][now] != -1) { return dp[qs][now]; } long cur = now; long ret = 0; for (int i = 0; i < now + 1; i++) { long add = go(cur, qs - 1); ret += add; if (i != now) { ret++; } cur = Math.min(K, cur + add + 1); } return dp[qs][now] = ret; } void go(long l, long r, int qs) { ArrayList<Long> ask = new ArrayList<>(); long cur = l; for (int i = 0; i < Math.min(l, K); i++) { long advance = go(cur, qs - 1); cur += advance; if (cur >= r) { break; } ask.add(cur); cur++; } out.print(ask.size() + " "); for (long x : ask) { out.print(x + " "); } out.println(); out.flush(); int ret = nextInt(); if (ret == -1) { return; } if (ret == 0) { go(l, ask.get(0), qs - 1); } else if (ret == ask.size()) { go(ask.get(ask.size() - 1) + 1, r, qs - 1); } else { go(ask.get(ret - 1) + 1, ask.get(ret), qs - 1); } } void submit() { // System.err.println(go(7, 2)); // System.err.println(go(7, 1)); go(1, M, 5); } void test() { } void stress() { for (int tst = 0;; tst++) { if (false) { throw new AssertionError(); } System.err.println(tst); } } G() throws IOException { is = System.in; out = new PrintWriter(System.out); submit(); // stress(); // test(); out.close(); } static final Random rng = new Random(); static final int C = 5; static int rand(int l, int r) { return l + rng.nextInt(r - l + 1); } public static void main(String[] args) throws IOException { new G(); } private InputStream is; PrintWriter out; private byte[] buf = new byte[1 << 14]; private int bufSz = 0, bufPtr = 0; private int readByte() { if (bufSz == -1) throw new RuntimeException("Reading past EOF"); if (bufPtr >= bufSz) { bufPtr = 0; try { bufSz = is.read(buf); } catch (IOException e) { throw new RuntimeException(e); } if (bufSz <= 0) return -1; } return buf[bufPtr++]; } private boolean isTrash(int c) { return c < 33 || c > 126; } private int skip() { int b; while ((b = readByte()) != -1 && isTrash(b)) ; return b; } String nextToken() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!isTrash(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nextString() { int b = readByte(); StringBuilder sb = new StringBuilder(); while (!isTrash(b) || b == ' ') { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } double nextDouble() { return Double.parseDouble(nextToken()); } char nextChar() { return (char) skip(); } int nextInt() { int ret = 0; int b = skip(); if (b != '-' && (b < '0' || b > '9')) { throw new InputMismatchException(); } boolean neg = false; if (b == '-') { neg = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { ret = ret * 10 + (b - '0'); } else { if (b != -1 && !isTrash(b)) { throw new InputMismatchException(); } return neg ? -ret : ret; } b = readByte(); } } long nextLong() { long ret = 0; int b = skip(); if (b != '-' && (b < '0' || b > '9')) { throw new InputMismatchException(); } boolean neg = false; if (b == '-') { neg = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { ret = ret * 10 + (b - '0'); } else { if (b != -1 && !isTrash(b)) { throw new InputMismatchException(); } return neg ? -ret : ret; } b = readByte(); } } }
Java
["2\n\n0\n\n-1"]
2 seconds
["2 2 3\n\n2 20 30\n\n3 5 7 9"]
NoteIn the first example the number $$$5$$$ is hidden.
Java 8
standard input
[ "dp", "interactive" ]
fff0deb3f5f2df8935684abfe07c31bf
null
3,000
null
standard output
PASSED
a3da1f4c3465bbdb14a561c5e71e32e7
train_002.jsonl
1535387700
This problem is interactive.You should guess hidden number $$$x$$$ which is between $$$1$$$ and $$$M = 10004205361450474$$$, inclusive.You could use up to $$$5$$$ queries.In each query, you can output an increasing sequence of $$$k \leq x$$$ integers, each between $$$1$$$ and $$$M$$$, inclusive, and you will obtain one of the following as an answer: either the hidden number belongs to your query sequence, in this case you immediately win; or you will be given where the hidden number is located with respect to your query sequence, that is, either it is less than all numbers from the sequence, greater than all numbers from the sequence, or you will be given such an $$$i$$$ that the hidden number $$$x$$$ is between the $$$i$$$-th and the $$$(i+1)$$$-st numbers of your sequence. See the interaction section for clarity.Be aware that the interactor is adaptive, i.e. the hidden number can depend on queries the solution makes. However, it is guaranteed that for any solution the interactor works non-distinguishable from the situation when the hidden number is fixed beforehand.Hacks are allowed only with fixed hidden number. A hack is represented by a single integer between $$$1$$$ and $$$M$$$. In all pretests the hidden number is fixed as well.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; public class AIM_5F { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter printer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int cGuess = 1; long min = 1; while (true) { // printer.println(f(cGuess, min, true)); f(cGuess, min, true); int distinct = 1; for (int i = 1; i < guesses.length; i++) { if (guesses[i] > guesses[i - 1] && guesses[i] <= 10004205361450474L) { distinct++; } } StringBuilder str = new StringBuilder(); printer.println(distinct); for (int i = 0; i < guesses.length; i++) { if (i == 0 || guesses[i] > guesses[i - 1] && guesses[i] <= 10004205361450474L) { str.append(guesses[i]); str.append(' '); } } printer.println(str.toString()); printer.flush(); int resp = Integer.parseInt(reader.readLine()); if (resp < 0) { return; } if (resp != 0) { min = guesses[resp - 1] + 1; } cGuess++; } } static long[] guesses; static long f(int g, long l, boolean store) { if (l >= 10004205361450474L) { return 10004205361450475L; } int nGuesses = (int) Math.min(l, 10_000); if (g == 5) { if (store) { guesses = new long[nGuesses]; for (int i = 0; i < nGuesses; i++) { guesses[i] = l + i; } } return Math.min(10004205361450475L, l + nGuesses); } if (store) { guesses = new long[nGuesses]; long cur = guesses[0] = f(g + 1, l, false); for (int i = 1; i < nGuesses; i++) { cur = guesses[i] = f(g + 1, cur + 1, false); } return f(g + 1, cur + 1, false); } else if (g == 3) { long cur = f(g + 1, l, false); for (int i = 1; i < nGuesses; i++) { if (cur + 1 >= 10_000) { cur += (nGuesses - i + 1) * 10_001L * 10_001; return Math.min(10004205361450475L, cur); } cur = f(g + 1, cur + 1, false); } return f(g + 1, cur + 1, false); } else if (g == 4) { long cur = f(g + 1, l, false); for (int i = 1; i < nGuesses; i++) { if (cur + 1 >= 10_000) { cur += (nGuesses - i + 1) * 10_001L; return Math.min(10004205361450475L, cur); } cur = f(g + 1, cur + 1, false); } return f(g + 1, cur + 1, false); } else { long cur = f(g + 1, l, false); for (int i = 1; i < nGuesses; i++) { cur = f(g + 1, cur + 1, false); } return f(g + 1, cur + 1, false); } } }
Java
["2\n\n0\n\n-1"]
2 seconds
["2 2 3\n\n2 20 30\n\n3 5 7 9"]
NoteIn the first example the number $$$5$$$ is hidden.
Java 8
standard input
[ "dp", "interactive" ]
fff0deb3f5f2df8935684abfe07c31bf
null
3,000
null
standard output
PASSED
dd24b4bf9db423d38e523f29a6a1dbac
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.io.*; import java.util.HashSet; import java.util.StringTokenizer; public class A778 { public static void main(String args[]) throws Exception { Reader reader = new Reader(); reader.initConsoleReading(); String a = reader.next(); String b = reader.next(); int n = a.length(); int[] pos = new int[n + 1]; for (int i = 1; i <= n; i++) { pos[i] = reader.nextInt(); } int l = 1, h = n; while (l + 1 < h) { int m = (l + h) >> 1; if (pass(a, b, n, pos, m)) { l = m; } else h = m - 1; } for (int x = Math.min(h + 3, n); x >= Math.max(1, l - 3); x--) { if(pass(a, b, n, pos, x)){ System.out.println(x); return; } } System.out.println(0); reader.dispose(); } private static boolean pass(String a, String b, int n, int[] pos, int m) { HashSet<Integer> p = new HashSet<>(); for (int i = 1; i <= m; i++) p.add(pos[i] - 1); int r = b.length() - 1; int l = a.length() - 1; while (r >= 0) { if (l < 0) { return false; } if (p.contains(l)) l--; else if (a.charAt(l) == b.charAt(r)) { r--; l--; } else l--; } return r < 0; } /************************************Helper Methods Begin Here**********************************************/ private static String reverse(String toRev) { return new StringBuilder(toRev).reverse().toString(); } public static class Pair<F extends Comparable<F>, S extends Comparable<S>> implements Comparable<Pair<F, S>> { static final int prime = 31; private F first; private S second; public Pair(F f, S s) { this.first = f; this.second = s; } @Override public int hashCode() { int result = 1; result = prime * result + this.first.hashCode(); result = prime * result + this.second.hashCode(); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair<F, S> s = (Pair<F, S>) obj; return this.first.equals(s.first) && this.second.equals(s.second); } @Override public int compareTo(Pair<F, S> p) { int c1 = this.first.compareTo(p.first); if (c1 == 0) { return this.second.compareTo(p.second); } return c1; } } public static int swap(int a, int b) { /*a = Main.swap(b,b=a); goes from left to right*/ return a; } public static long swap(long a, long b) { /*a = Main.swap(b,b=a); goes from left to right*/ return a; } public static boolean next_permutation(int[] p) { for (int a = p.length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (int b = p.length - 1; ; --b) if (p[b] > p[a]) { int t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } return false; } public static long gcd(long a, long b) { if (a < 0) a *= -1; if (b < 0) b *= -1; return b == 0 ? a : gcd(b, a % b); } public static class Reader { public BufferedReader reader; public StringTokenizer tokenizer; public Reader() { } public Reader initConsoleReading() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; return this; } public Reader initFileReading(String filePath) throws FileNotFoundException { reader = new BufferedReader(new FileReader(filePath), 32768); tokenizer = null; return this; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public String nextLine() throws IOException { return reader.readLine(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public void dispose() throws IOException { this.reader.close(); } } /************************************Helper Methods Ends Here**********************************************/ }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
09935ae276e915615353cc820b104378
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.io.*; import java.math.*; import java.util.*; public class icpc { public static void main(String[] args) throws IOException { // Reader in = new Reader(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String s = in.readLine(); String p = in.readLine(); int n = s.length(); int[] A = new int[n]; String s1[] = in.readLine().split(" "); for (int i=0;i<n;i++) A[i] = Integer.parseInt(s1[i]) - 1; int l = 0; int r = n - 1; int ans = 0; while (l <= r) { StringBuilder stringBuilder = new StringBuilder(); int mid = (l + r) / 2; HashSet<Integer> h = new HashSet<>(); for (int i=0;i<=mid;i++) h.add(A[i]); for (int i=0;i<s.length();i++) { if(!h.contains(i)) stringBuilder.append(s.charAt(i)); } boolean flag = check(stringBuilder.toString(), p); if (flag) { ans = mid + 1; l = mid + 1; continue; } else { r = mid - 1; continue; } } System.out.println(ans); } public static boolean check(String s, String p) { boolean flag = true; int i = 0; int j = 0; if(s.length() < p.length()) return false; else { while (i < s.length() && j < p.length()) { if(s.charAt(i) == p.charAt(j)) { i++; j++; } else { i++; } } if(j == p.length()) return true; else return false; } } } class NumberTheory { public boolean isPrime(long n) { if(n < 2) return false; for(long x = 2;x * x <= n;x++) { if(n % x == 0) return false; } return true; } public ArrayList<Integer> primeFactorisation(int n) { ArrayList<Integer> f = new ArrayList<>(); for(int x=2;x * x <= n;x++) { while(n % x == 0) { f.add(x); n /= x; } } if(n > 1) f.add(n); return f; } public int[] sieveOfEratosthenes(int n) { int[] sieve = new int[n + 1]; for(int x=2;x<=n;x++) { if(sieve[x] != 0) continue; sieve[x] = x; for(int u=2*x;u<=n;u+=x) if(sieve[u] == 0) sieve[u] = x; } return sieve; } public long gcd(long a, long b) { if(b == 0) return a; return gcd(b, a % b); } public long phi(long n) { double result = n; for(long p=2;p*p<=n;p++) { if(n % p == 0) { while (n % p == 0) n /= p; result *= (1.0 - (1.0 / (double)p)); } } if(n > 1) result *= (1.0 - (1.0 / (double)n)); return (long)result; } public Name extendedEuclid(long a, long b) { if(b == 0) return new Name(a, 1, 0); Name n1 = extendedEuclid(b, a % b); Name n2 = new Name(n1.d, n1.y, n1.x - (long)Math.floor((double)a / b) * n1.y); return n2; } public long modularExponentiation(long a, long b, long n) { long d = 1L; String bString = Long.toBinaryString(b); for(int i=0;i<bString.length();i++) { d = (d * d) % n; if(bString.charAt(i) == '1') d = (d * a) % n; } return d; } } class Name { long d; long x; long y; public Name(long d, long x, long y) { this.d = d; this.x = x; this.y = y; } } class SuffixArray { int ALPHABET_SZ = 256, N; int[] T, lcp, sa, sa2, rank, tmp, c; public SuffixArray(String str) { this(toIntArray(str)); } private static int[] toIntArray(String s) { int[] text = new int[s.length()]; for (int i = 0; i < s.length(); i++) text[i] = s.charAt(i); return text; } public SuffixArray(int[] text) { T = text; N = text.length; sa = new int[N]; sa2 = new int[N]; rank = new int[N]; c = new int[Math.max(ALPHABET_SZ, N)]; construct(); kasai(); } private void construct() { int i, p, r; for (i = 0; i < N; ++i) c[rank[i] = T[i]]++; for (i = 1; i < ALPHABET_SZ; ++i) c[i] += c[i - 1]; for (i = N - 1; i >= 0; --i) sa[--c[T[i]]] = i; for (p = 1; p < N; p <<= 1) { for (r = 0, i = N - p; i < N; ++i) sa2[r++] = i; for (i = 0; i < N; ++i) if (sa[i] >= p) sa2[r++] = sa[i] - p; Arrays.fill(c, 0, ALPHABET_SZ, 0); for (i = 0; i < N; ++i) c[rank[i]]++; for (i = 1; i < ALPHABET_SZ; ++i) c[i] += c[i - 1]; for (i = N - 1; i >= 0; --i) sa[--c[rank[sa2[i]]]] = sa2[i]; for (sa2[sa[0]] = r = 0, i = 1; i < N; ++i) { if (!(rank[sa[i - 1]] == rank[sa[i]] && sa[i - 1] + p < N && sa[i] + p < N && rank[sa[i - 1] + p] == rank[sa[i] + p])) r++; sa2[sa[i]] = r; } tmp = rank; rank = sa2; sa2 = tmp; if (r == N - 1) break; ALPHABET_SZ = r + 1; } } private void kasai() { lcp = new int[N]; int[] inv = new int[N]; for (int i = 0; i < N; i++) inv[sa[i]] = i; for (int i = 0, len = 0; i < N; i++) { if (inv[i] > 0) { int k = sa[inv[i] - 1]; while ((i + len < N) && (k + len < N) && T[i + len] == T[k + len]) len++; lcp[inv[i] - 1] = len; if (len > 0) len--; } } } } class ZAlgorithm { public int[] calculateZ(char input[]) { int Z[] = new int[input.length]; int left = 0; int right = 0; for(int k = 1; k < input.length; k++) { if(k > right) { left = right = k; while(right < input.length && input[right] == input[right - left]) { right++; } Z[k] = right - left; right--; } else { //we are operating inside box int k1 = k - left; //if value does not stretches till right bound then just copy it. if(Z[k1] < right - k + 1) { Z[k] = Z[k1]; } else { //otherwise try to see if there are more matches. left = k; while(right < input.length && input[right] == input[right - left]) { right++; } Z[k] = right - left; right--; } } } return Z; } public ArrayList<Integer> matchPattern(char text[], char pattern[]) { char newString[] = new char[text.length + pattern.length + 1]; int i = 0; for(char ch : pattern) { newString[i] = ch; i++; } newString[i] = '$'; i++; for(char ch : text) { newString[i] = ch; i++; } ArrayList<Integer> result = new ArrayList<>(); int Z[] = calculateZ(newString); for(i = 0; i < Z.length ; i++) { if(Z[i] == pattern.length) { result.add(i - pattern.length - 1); } } return result; } } class KMPAlgorithm { public int[] computeTemporalArray(char[] pattern) { int[] lps = new int[pattern.length]; int index = 0; for(int i=1;i<pattern.length;) { if(pattern[i] == pattern[index]) { lps[i] = index + 1; index++; i++; } else { if(index != 0) { index = lps[index - 1]; } else { lps[i] = 0; i++; } } } return lps; } public ArrayList<Integer> KMPMatcher(char[] text, char[] pattern) { int[] lps = computeTemporalArray(pattern); int j = 0; int i = 0; int n = text.length; int m = pattern.length; ArrayList<Integer> indices = new ArrayList<>(); while(i < n) { if(pattern[j] == text[i]) { i++; j++; } if(j == m) { indices.add(i - j); j = lps[j - 1]; } else if(i < n && pattern[j] != text[i]) { if(j != 0) j = lps[j - 1]; else i = i + 1; } } return indices; } } class Hashing { public long[] computePowers(long p, int n, long m) { long[] powers = new long[n]; powers[0] = 1; for(int i=1;i<n;i++) { powers[i] = (powers[i - 1] * p) % m; } return powers; } public long computeHash(String s) { long p = 31; long m = 1_000_000_009; long hashValue = 0L; long[] powers = computePowers(p, s.length(), m); for(int i=0;i<s.length();i++) { char ch = s.charAt(i); hashValue = (hashValue + (ch - 'a' + 1) * powers[i]) % m; } return hashValue; } } class BasicFunctions { public long min(long[] A) { long min = Long.MAX_VALUE; for(int i=0;i<A.length;i++) { min = Math.min(min, A[i]); } return min; } public long max(long[] A) { long max = Long.MAX_VALUE; for(int i=0;i<A.length;i++) { max = Math.max(max, A[i]); } return max; } } class Matrix { long a; long b; long c; long d; public Matrix(long a, long b, long c, long d) { this.a = a; this.b = b; this.c = c; this.d = d; } } class MergeSortInt { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(int arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ int L[] = new int[n1]; int R[] = new int[n2]; /*Copy data to temp arrays*/ for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() void sort(int arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l + r) / 2; // Sort first and second halves sort(arr, l, m); sort(arr, m + 1, r); // Merge the sorted halves merge(arr, l, m, r); } } } class MergeSortLong { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(long arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ long L[] = new long[n1]; long R[] = new long[n2]; /*Copy data to temp arrays*/ for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() void sort(long arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l + r) / 2; // Sort first and second halves sort(arr, l, m); sort(arr, m + 1, r); // Merge the sorted halves merge(arr, l, m, r); } } } class Node { String a; String b; Node(String s1,String s2) { this.a = s1; this.b = s2; } @Override public boolean equals(Object ob) { if(ob == null) return false; if(!(ob instanceof Node)) return false; if(ob == this) return true; Node obj = (Node)ob; if(this.a.equals(obj.a) && this.b.equals(obj.b)) return true; return false; } @Override public int hashCode() { return (int)this.a.length(); } } 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(); } } class FenwickTree { public void update(long[] fenwickTree,long delta,int index) { index += 1; while(index < fenwickTree.length) { fenwickTree[index] += delta; index = index + (index & (-index)); } } public long prefixSum(long[] fenwickTree,int index) { long sum = 0L; index += 1; while(index > 0) { sum += fenwickTree[index]; index -= (index & (-index)); } return sum; } } class SegmentTree { public int nextPowerOfTwo(int num) { if(num == 0) return 1; if(num > 0 && (num & (num - 1)) == 0) return num; while((num &(num - 1)) > 0) { num = num & (num - 1); } return num << 1; } public int[] createSegmentTree(int[] input) { int np2 = nextPowerOfTwo(input.length); int[] segmentTree = new int[np2 * 2 - 1]; for(int i=0;i<segmentTree.length;i++) segmentTree[i] = Integer.MIN_VALUE; constructSegmentTree(segmentTree,input,0,input.length-1,0); return segmentTree; } private void constructSegmentTree(int[] segmentTree,int[] input,int low,int high,int pos) { if(low == high) { segmentTree[pos] = input[low]; return; } int mid = (low + high)/ 2; constructSegmentTree(segmentTree,input,low,mid,2*pos + 1); constructSegmentTree(segmentTree,input,mid+1,high,2*pos + 2); segmentTree[pos] = Math.max(segmentTree[2*pos + 1],segmentTree[2*pos + 2]); } public int rangeMinimumQuery(int []segmentTree,int qlow,int qhigh,int len) { return rangeMinimumQuery(segmentTree,0,len-1,qlow,qhigh,0); } private int rangeMinimumQuery(int segmentTree[],int low,int high,int qlow,int qhigh,int pos) { if(qlow <= low && qhigh >= high){ return segmentTree[pos]; } if(qlow > high || qhigh < low){ return Integer.MIN_VALUE; } int mid = (low+high)/2; return Math.max(rangeMinimumQuery(segmentTree, low, mid, qlow, qhigh, 2 * pos + 1), rangeMinimumQuery(segmentTree, mid + 1, high, qlow, qhigh, 2 * pos + 2)); } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
a319a91dc53ceea79dfcecffee3b187c
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
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.StringTokenizer; public class StringGame implements Closeable { private InputReader in = new InputReader(System.in); private PrintWriter out = new PrintWriter(System.out); public void solve() { char[] a = in.next().toCharArray(), b = in.next().toCharArray(); int n = a.length, m = b.length; int[] d = new int[n]; for (int i = 0; i < n; i++) { d[i] = in.ni() - 1; } int left = 0, right = n - 1; int result = -1; while (left <= right) { int mid = (left + right) / 2; boolean[] deleted = new boolean[n]; for (int i = 0; i <= mid; i++) { deleted[d[i]] = true; } int idx = 0; for (int i = 0; i < n && idx < m; i++) { if (!deleted[i]) { if (a[i] == b[idx]) { idx++; } } } boolean preserve = idx == m; if (preserve) { result = Math.max(result, mid); left = mid + 1; } else { right = mid - 1; } } out.println(result + 1); } @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 (StringGame instance = new StringGame()) { instance.solve(); } } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
9c85ce5321c14a339a76215156397779
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.util.HashSet; import java.util.Scanner; public class cf_778a { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s1 = in.nextLine(); String s2 = in.nextLine(); int len = s1.length(); int[] p = new int[len]; for (int i = 0; i < len; i++) p[i] = in.nextInt(); int count = 0; int l = 0, h = len - 1; while (l <= h) { int m = (l + h) / 2; HashSet<Integer> hs = new HashSet<Integer>(); StringBuilder sb = new StringBuilder(); for (int i = 0; i <= m; i++) { hs.add(p[i]); } for (int i = 0; i < len; i++) { if (!hs.contains(i + 1)) { sb.append(s1.charAt(i)); } } if (!subseq(sb.toString(), s2)) { h = m - 1; } else { l = m + 1; count = m + 1; } } System.out.println(count); } public static boolean subseq(String str, String s2) { int j = 0; for (int i = 0; i < str.length() && j < s2.length(); i++) { if (str.charAt(i) == s2.charAt(j)) { j++; } } if (j == s2.length()) return true; return false; } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
fa1be29f5726feba9827ed9b7396dca4
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.awt.*; import java.io.*; import java.util.*; public class Abc { public static void main(String[] args) throws Exception { // Scanner sc = new Scanner(System.in); FastReader sc=new FastReader(); String t=sc.next(),p=sc.next(); int ind[]=new int[t.length()]; for (int i=0;i<t.length();i++){ ind[sc.nextInt()-1]=i; } int l=0,r=t.length(); int ans=0; while (l<=r){ int m=l+(r-l)/2; int c=0; for (int i=0;i<t.length();i++){ if (ind[i]<m)continue; if (p.charAt(c)==t.charAt(i)){ c++; if (c==p.length())break; } } if (c!=p.length()){ r=m-1; }else { ans=m; l=m+1; } } System.out.println(ans); } 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; } } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
04fee3d046b7088fb5ed24567f4fdfaf
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.util.Scanner; /** * Created by nikr0716 on 2/28/2017. */ public class BinarySearchMain { static StringBuffer S; static StringBuffer t; static int len; static int[] numbers; static int[] prioritiesToDelete; public static void main(String[] args) { Scanner in = new Scanner(System.in); S = new StringBuffer(in.nextLine()); t = new StringBuffer(in.nextLine()); String[] stringNumbers = in.nextLine().split(" "); char ch; numbers = new int[stringNumbers.length]; prioritiesToDelete = new int[stringNumbers.length]; for(int i = 0; i < numbers.length ; i++){ numbers[i] = Integer.parseInt(stringNumbers[i]) - 1; prioritiesToDelete[numbers[i]] = i; } len = numbers.length; int left = 0; int right = S.length(); int count=0; while (left <= right){ int mid = (left+right)/2; if(isResidueContainsSubstring(mid)){ left = mid + 1; count = mid+1; } else{ right = mid - 1; } } // boolean substringExists = isSubstringExists(S, t); System.out.println(count); } static boolean isResidueContainsSubstring(int mid){ StringBuffer sb = new StringBuffer(); for (int i = 0; i < len; i++){ if (prioritiesToDelete[i] > mid){ sb.append(S.charAt(i)); } } int i, j; for (i = 0, j = 0; i < t.length() && j < sb.length(); j++ ){ if (sb.charAt(j) == t.charAt(i)){ i++; } } return i == t.length(); } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
6629d90f4f93c394517448c15651706f
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.util.Scanner; public class _4_str { public static void main(String[] args) { Scanner scn = new Scanner(System.in); String s = scn.next(); String s2 = scn.next(); int[] arr = new int[s.length()]; int[] time = new int[s.length()]; for (int i = 0; i < s.length(); i++) { arr[i] = scn.nextInt(); time[arr[i]-1] = i+1; } int left = 0; int right = s.length(); while (left <= right) { int mid = left + (right - left) / 2; int p = 0; boolean b = false; boolean b2=false; for (int i = 0; i < s.length(); i++) { int v = arr[i]; if (time[i] > mid && s2.charAt(p) == s.charAt(i)) { p++; } if (p == s2.length()) { b = true; break; } } p=0; for (int i = 0; i < s.length(); i++) { int v = arr[i]; if (time[i] > (mid+1) && s2.charAt(p) == s.charAt(i)) { p++; } if (p == s2.length()) { b2 = true; break; } } if(b&&!b2){ System.out.println(mid); } if (b) { left = mid+1; } else { right = mid - 1; } } } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
ac6a4c5284640906aff77f9bba2a58bc
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.io.*; import java.util.*; public class StringGame { static String s , x; static int arr[]; static boolean check(int r){ char[]c= s.toCharArray(); for (int i = 0; i < r; i++) { c[arr[i]]='A'; } int y=0; for (int i = 0; i < c.length; i++) { if (c[i]==x.charAt(y)) { y++; } if (y==x.length()) { return true; } } return false; } public static void main(String[] args) { Scanner in = new Scanner(System.in); s = in.next(); x = in.next(); arr = new int[s.length()]; for (int i = 0; i < s.length(); i++) { arr[i]=in.nextInt()-1; } int l = 0; int r = s.length()-1; int os =0; int mid=(r+l+1)/2; while(l<=r){ if (check(mid)) { l=mid+1; os=mid; mid=(r+l+1)/2; }else { r=mid-1; mid=(r+l+1)/2; } } System.out.println(os); } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
7b75dbc1e622f517a9c7a9743438cd80
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.util.Scanner; public class A778 { public static void main(String[] args) { Scanner in = new Scanner(System.in); char[] S = in.next().toCharArray(); char[] T = in.next().toCharArray(); int[] A = new int[S.length]; for (int n=1; n<=S.length; n++) { A[in.nextInt()-1] = n; } int low = 0; int high = S.length; while (low < high) { int mid = (low + high + 1)/2; int tIdx = 0; for (int i=0; i<S.length; i++) { if (A[i] > mid && T[tIdx] == S[i]) { tIdx++; if (tIdx == T.length) { break; } } } if (tIdx == T.length) { low = mid; } else { high = mid-1; } } System.out.println(low); } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
e825bbd422ece0a742e38f733211dc73
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class Main implements Runnable { static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new Main(),"Main",1<<26).start(); } public void run() { InputReader sc= new InputReader(System.in); PrintWriter w= new PrintWriter(System.out); String t = sc.next(); String s = sc.next(); int a[] = new int[t.length()]; for(int i = 0; i < t.length(); ++i) a[i] = sc.nextInt(); int start = 0, end = t.length(); int ans = 0; while(start <= end) { int mid = (start + end) / 2; HashMap<Integer, Integer> map = new HashMap<>(); for(int i = 0; i < mid; ++i) map.put(a[i] - 1, 1); int u = 0; for(int i = 0; i < t.length() && u != s.length(); ++i) { if(map.get(i) == null && t.charAt(i) == s.charAt(u)) u++; } if(u == s.length()) { ans = mid; start = mid + 1; } else end = mid - 1; } w.print(ans); w.close(); } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
6726c63ed3e41b0cda9e612535aba9c6
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.*; import java.util.*; public class Main { ////// static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } ////// static boolean check(char[] A,char[] B,boolean[] visited){ int i=0,j=0; for(i=0;i<A.length;i++){ if(visited[i]==false&&j!=B.length){ if(B[j]==A[i]){ j++; } } } if(j==B.length){ return true; } return false; } public static void main(String[] args) throws IOException { FastReader scan = new FastReader(); /*String a="anna"; String b="banana"; a=a.replace("",".*"); System.out.println(b.matches(a)); */ PrintWriter pw = new PrintWriter(System.out); String input1=scan.next(); String input2=scan.next(); int[] num=new int[input1.length()]; int len1=input1.length(); for(int i=0;i<len1;i++){ num[i]=scan.nextInt(); } int len2=input2.length(); char[] A=input1.toCharArray(); char[] B=input2.toCharArray(); int l=0,r=len1; int mid=(l+r)/2; int mid1=mid; boolean[] visited=new boolean[len1]; boolean[] ans=new boolean[len1+1]; int i=0; int flag=0; while(true){ Arrays.fill(visited,false); i=0; while(mid1-->0){ visited[num[i]-1]=true; i++; } if(check(A,B,visited)==true){ l=mid+1; ans[mid]=true; }else{ r=mid-1; ans[mid]=false; //if(flag==1){ // System.out.println(mid); // return; //} } mid=(l+r)/2; mid1=mid; if(ans[mid]==true){ System.out.println(mid); return; } // if(mid==0||mid==len1||(ans[mid+1]==false&&ans[mid-1]==true)){ // System.out.println(mid); // return; // } } //System.out.println(check(A,B,visited)); /*input1=input1.replace("",".*"); System.out.println(input1); System.out.println(input2.matches(input1)); System.out.println(); //System.out.println(hm.get('b')); */ // pw.close(); } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
5f0666d51871730ead66537b00f2b5ec
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.io.*; import java.util.*; public class Solution { static int ssearch(StringBuffer a,String b){ int n1=a.length(); int n2=b.length(); int i=0; for( int j=0;i<n2&&j<n1;j++){ if(b.charAt(i)==a.charAt(j)) i++; }if(i==n2) return 1; else return 0;} static int bsearch(StringBuffer s,String p,int[] a){ int lo=0; int hi=s.length(); while(lo<hi){ int x=lo+(hi-lo+1)/2; StringBuffer temp=new StringBuffer(s); for(int i=0;i<x;i++) temp.setCharAt(a[i]-1,'/'); if(ssearch(temp,p)==1) lo=x; else hi=x-1; } return lo; } public static void main(String[] args) { Scanner in=new Scanner(System.in); StringBuffer s=new StringBuffer(); s.append(in.next()); String p=in.next(); int a[]=new int[s.length()]; for(int i=0;i<s.length();i++) a[i]=in.nextInt(); System.out.println(bsearch(s,p,a)); } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
294f053f7f0ef0600c5962380d7ad54c
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.util.*; public class buying { public static String p; public static String t; public static int pp; public static int tt; public static int[] n = new int[200000]; public static int find(int left, int right){ if(left==right){ return left; } int middle=(left+right)/2+1; int i,j; i=0; for(j=0; j<tt; j++){ if(n[j]>=middle && p.charAt(i)==t.charAt(j)){ i++; // if characters in p and t match and character is not deleted, then search for next character } if(i==pp){ int sol = find(middle,right); return sol; // if stable state (found whole p), then search in the right half (delete more characters) } } int sol = find(left,middle-1); return sol; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); t = sc.next(); p = sc.next(); pp = p.length(); tt = t.length(); int nn,i; for(i=0; i<tt; i++){ nn = sc.nextInt(); n[nn-1] = i; } sc.close(); int sol = find(0,tt-pp); System.out.println(sol); return; } /*// checking for stable state. Time complexity in O(cur.length()) public static boolean b(String cur, String key){ int i; int j = 0; for(i = 0; i< cur.length(); i++){ if(cur.charAt(i)== key.charAt(j)){ j++; if(j == key.length()){ return true; } } } return false; } public static void main(String[] args) { // reading input. Time complexity in O(input.length() + key.length()) Scanner sc = new Scanner(System.in); String input = sc.next(); String key = sc.next(); int len = input.length(); int[] index = new int[len]; for(int i = 0; i< len; i++){ index[i] = sc.nextInt(); } sc.close(); // binary search. A bit less hacky than last time. double bin = Math.floor(Math.log(len)/Math.log(2)); int expo = (int) Math.pow(2,bin); int sol = expo; int[] part; int rindex; do{ int lindex=0; expo /= 2; String cur = ""; // most expensive part. if(sol >= (len/2)){ part = Arrays.copyOfRange(index, sol, len); Arrays.sort(part); for(int i=0; i<part.length; i++){ cur= cur + input.charAt(part[i]-1); } } else{ part = Arrays.copyOfRange(index, 0, sol); Arrays.sort(part); for(int i=0; i<part.length; i++){ rindex = part[i]-1; cur= cur + input.substring(lindex, rindex); lindex = rindex + 1; } if(lindex <= len){ cur += input.substring(lindex); } } // adjusting sol accordingly. if(stableState(cur, key)){ if(sol + expo < input.length()){sol += expo;} } else{ sol -= expo; } }while(expo > 0); // making sure we leaf at a stable state and reduce sol by one otherwise. Time complexity in O(index.length * log (index.length)). part = Arrays.copyOfRange(index, sol, index.length); Arrays.sort(part); String cur=""; for(int i=0; i<part.length; i++){ cur= cur + input.charAt(part[i]-1); } if(!stableState(cur, key)){ sol -= 1; } // print solution and terminate System.out.println(sol); return; }*/ }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
9c0026f29ee34d5843d495c9dee0ae43
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.util.*; public class C { static boolean isSubSequence(char[] str1, char[] str2, int m, int n){ int j = 0; for (int i = 0; i < n && j < m; i++) if (str1[j] == str2[i]) j++; return (j == m); } public static void main(String[] args) throws IOException { try { BufferInput in = new BufferInput(); String a = in.nextString(); String b = in.nextString(); int[] arr = new int[a.length()]; for (int i = 0; i < a.length(); i++) { arr[in.nextInt() - 1] = i + 1; } char[] aa = a.toCharArray(); char[] bb = b.toCharArray(); //int j = 0; int l = 0; int r = a.length()+1; while (l + 1 < r) { int m = (l + r) / 2; int j = 0; boolean flag = false; for (int i = 0; i < aa.length; i++) { if (arr[i] > m && aa[i] == bb[j]) { j++; } if (j == bb.length) { flag = true; break; } } if (flag) { l = m; } else { r = m; } } System.out.println(l); }catch(Exception e) {} } static class BufferInput { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public BufferInput() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public BufferInput(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public String nextString() throws IOException{ byte c = read(); while(Character.isWhitespace(c)){ c = read(); } StringBuilder builder = new StringBuilder(); builder.append((char)c); c = read(); while(!Character.isWhitespace(c)){ builder.append((char)c); c = read(); } return builder.toString(); } 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 int[] nextIntArray(int n) throws IOException { int arr[] = new int[n]; for(int i = 0; i < n; i++){ arr[i] = nextInt(); } return arr; } public long 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 long[] nextLongArray(int n) throws IOException { long arr[] = new long[n]; for(int i = 0; i < n; i++){ arr[i] = nextLong(); } return arr; } public char nextChar() throws IOException{ byte c = read(); while(Character.isWhitespace(c)){ c = read(); } return (char) c; } 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; } public double[] nextDoubleArray(int n) throws IOException { double arr[] = new double[n]; for(int i = 0; i < n; i++){ arr[i] = nextDouble(); } return arr; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
1b8fe5fed4ece379392884f70aec7ab7
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
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.Arrays; import java.util.StringTokenizer; public class StringGame { static final int N = 100000+10; static int n , m ,v[] = new int [2*N]; static char s[] = new char[2*N]; static char t[] = new char[2*N]; static boolean rem[] = new boolean[2*N]; 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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.flush(); } static class TaskB{ void solve(int test , InputReader in , PrintWriter out) { s = in.next().toCharArray(); t = in.next().toCharArray(); n = s.length; m = t.length; for(int i = 0 ; i< n ;i++){ v[i] = in.nextInt(); v[i]--; } int lo = 0 , hi = n , mid = 0, bst = 0; while(lo <= hi){ mid = (lo+hi)/2; if(can(mid)){ bst = mid; lo = mid +1; } else { hi = mid-1; } } out.println(bst); } boolean can(int mid){ Arrays.fill(rem,false); for(int i = 0;i<mid;i++) rem[v[i]] = true; int j = 0; for(int i = 0;i < n;i++){ if(rem[i]) continue; if(j<m && s[i] == t[j]) ++j; } return j == m; } } static class InputReader{ public BufferedReader reader; public StringTokenizer tk; public InputReader(InputStream stream){ reader = new BufferedReader(new InputStreamReader(stream)); tk = null; } String next(){ while (tk == null || !tk.hasMoreTokens()) { try{ tk = new StringTokenizer(reader.readLine()); } catch(IOException e){ throw new RuntimeException(); } } return tk.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
98b0f3d8c20b0e92d9d31247d133d9b9
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Books { static int [] arr; static String s,sub; public static void main(String[] args) { FastReader sc=new FastReader(); s=sc.next(); sub=sc.next(); arr=new int[s.length()]; for (int i = 0; i <s.length() ; i++) { arr[i]=sc.nextInt(); } int best=0; int l=0, r=s.length(),m=(s.length())/2; while(l<=r){ m=(l+r)/2; if(can(m)){ l=m+1; }else { r = m-1 ; best=m; } } System.out.println(best-1); } static boolean can(int m){ boolean [] isTaken=new boolean[s.length()]; for (int i = 0; i <m ; i++) { isTaken[arr[i]-1]=true; } int j = 0; aa :for (int i = 0; i <sub.length() ; i++) { for (; j <s.length() ; j++) { if(sub.charAt(i)==s.charAt(j) && !isTaken[j]){ j++; continue aa; } } return false; } return true; } } class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ InputStreamReader inr=new InputStreamReader(System.in); br=new BufferedReader(inr); } 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()); } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
a0dbe8552ca2a4ed430012eeeae3f8b2
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top * * @author crodoc */ 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); A solver = new A(); solver.solve(1, in, out); out.close(); } static class A { public void solve(int testNumber, Scanner in, PrintWriter out) { String bigString = in.next(); String smallString = in.next(); int[] when = new int[bigString.length()]; for (int i = 0; i < bigString.length(); i++) { when[in.nextInt() - 1] = i; } int lo = 0; int hi = bigString.length(); while (lo < hi) { int mid = (lo + hi + 1) / 2; if (foo(bigString, smallString, mid, when)) { lo = mid; } else { hi = mid - 1; } } out.println(lo); } private boolean foo(String bigString, String smallString, int mid, int[] when) { int bigPosition = 0; int smallPosition = 0; while (bigPosition < bigString.length() && smallPosition < smallString.length()) { while (bigPosition < bigString.length() && (bigString.charAt(bigPosition) != smallString.charAt(smallPosition) || when[bigPosition] < mid)) { bigPosition++; } if (bigPosition == bigString.length()) { break; } bigPosition++; smallPosition++; } return smallPosition == smallString.length(); } } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
e904556288a8fa9ad9cee43a169d02e3
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Map; import java.util.Scanner; import java.util.HashMap; /** * Built using CHelper plug-in * Actual solution is at the top * * @author crodoc */ 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); A solver = new A(); solver.solve(1, in, out); out.close(); } static class A { public void solve(int testNumber, Scanner in, PrintWriter out) { String t = in.next(); String p = in.next(); Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < t.length(); i++) { map.put(in.nextInt() - 1, i); } int lo = 0; int hi = t.length(); while (lo < hi) { int mid = (lo + hi + 1) / 2; if (foo(t, p, mid, map)) { lo = mid; } else { hi = mid - 1; } } out.println(lo); } private boolean foo(String t, String p, int mid, Map<Integer, Integer> map) { int p1 = 0; int p2 = 0; while (p1 < t.length() && p2 < p.length()) { while (p1 < t.length() && (t.charAt(p1) != p.charAt(p2) || map.get(p1) < mid)) { p1++; } if (p1 >= t.length()) { break; } p1++; p2++; } return p2 == p.length(); } } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
d97fe284f94b55534c8091a6ca9531c4
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.io.*; import java.util.StringTokenizer; public class Sample { private static final Scanner sc = new Scanner(System.in); private static final PrintWriter pw = new PrintWriter(System.out); private static StringBuffer ans = new StringBuffer(); private static char[] p; private static int[] a; public static void main(String[] args) throws Exception { String t = sc.next(); p = sc.next().toCharArray(); int low = 0, high = t.length() - 1; a = new int[high]; for (int i = 0; i < high; i++) a[i] = sc.nextInt(); while (low < high) { int mid = low + (high - low) / 2; boolean can = canMake(t.toCharArray(), mid); if (!can) high = mid; else low = mid + 1; } ans.append(low); pw.print(ans); sc.close(); pw.close(); } private static boolean canMake(char[] s, int x) throws Exception { int j = 0; for (int i = 0; i <= x; i++) s[a[i] - 1] = '-'; for (int i = 0; i < s.length; i++) { if (s[i] == p[j]) { j++; if (j == p.length) break; } } return j == p.length; } } class Scanner { private final BufferedReader br; private StringTokenizer st; public Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = new StringTokenizer(""); } public String next() throws IOException { if (!st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public void close() throws IOException { br.close(); } } class PrintWriter { private final BufferedOutputStream pw; public PrintWriter(OutputStream out) { pw = new BufferedOutputStream(out); } public void print(Object o) throws IOException { pw.write(o.toString().getBytes()); pw.flush(); } public void println(Object o) throws IOException { print(o + "\n"); } public void close() throws IOException { pw.close(); } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
4986244829d04c46f057f4f032636cc1
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.io.*; import java.util.*; /** * Created by noureldin on 2/20/17. */ public class main { private static String A,B; private static int n,m; private static int [] T; private static boolean can(int end){ boolean [] dont = new boolean[n]; for(int i = 0;i <= end;i++) dont[T[i]] = true; Queue<Character> q1,q2; q1 = new LinkedList<Character>(); q2 = new LinkedList<Character>(); for(int i = 0;i < n;i++) if(!dont[i]) q1.add(A.charAt(i)); for(int i = 0;i < m;i++) q2.add(B.charAt(i)); while (!q1.isEmpty() && !q2.isEmpty()){ if(q1.peek() == q2.peek()) q2.poll(); q1.poll(); } return q2.isEmpty(); } public static void main(String[] args) throws Exception{ BufferedReader br = br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out));; StringTokenizer st ; A = br.readLine().trim(); B = br.readLine().trim(); n = A.length(); m = B.length(); T = new int[n]; st = new StringTokenizer(br.readLine()); for (int i = 0;i < n;i++) T[i] = Integer.parseInt(st.nextToken()) - 1; int s = 0,e = n-1; while(s < e){ int m = s + (e - s + 1)/2; if(can(m)) s = m; else e = m - 1; } if(!can(s)) s--; writer.println(s+1); writer.close(); br.close(); } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
ee0c5d1ffe5da7f81a54885998beb8ac
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.io.*; import java.util.*; public class ready { public static class FastReaderFile { BufferedReader br; StringTokenizer st; public FastReaderFile(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static PrintWriter out; public static int ser ( int x[] , int start , int end , int val ) { while ( start <= end ) { int mid = ( start + end ) / 2 ; if ( x[mid] == val ) return mid ; if ( x[mid] <= val ) start = mid + 1 ; else end = mid - 1 ; } return -start - 1 ; } public static boolean isPrime(long n) { if (n < 2) return false; if (n < 4) return true; if (n%2 == 0 || n%3 == 0) return false; for (long i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0) return false ; return true; } static long gcd(long a, long b) { return b == 0 ? (a < 0 ? -a : a) : gcd(b, a % b); } static long lcm(long a, long b) { long lcm = (a / gcd(a, b)) * b; return lcm > 0 ? lcm : -lcm ; } public static int search( int x[] , int val ) { return ser( x , 0 , x.length - 1 , val ); } public static String remove ( String s , int i ) { return s.substring(0, i) + s.substring(i+1) ; } static boolean check( String y , String ss , int o , int x[] ) { int j = 0 , i = o ; // out.println(y) char s[] = new char[y.length()] ; s = y.toCharArray() ; for ( int h = 0 ; h <= i ; ++h ) s[x[h]] = 0 ; // out.println(s); i = 0 ; for ( ; i < s.length ; ++i ) { if ( s[i] == ss.charAt(j) ) ++j ; if ( j == ss.length() ) return true ; } return false ; } // for (Map.Entry<Integer, Integer> e : x.entrySet()) // { // e.getValue() , e.getKey public static void main(String[] args) throws FileNotFoundException { // TODO code application logic here FastReader in = new FastReader(); // Scanner in = new Scanner(System.in) ; // FastReaderFile in = new FastReaderFile(new FileInputStream("fruits.in")) ; // StringBuilder r = new StringBuilder(); // out = new PrintWriter(new BufferedOutputStream(new FileOutputStream("output.txt")), true) ; out = new PrintWriter(new BufferedOutputStream(System.out), true) ; String s = in.next() , ss = in.next() ; int x[] = new int[s.length()] ; for ( int i = 0 ; i < s.length() ; ++i ) x[i] = in.nextInt() - 1 ; int l = 0 , r = s.length() - 1 , med = 0 , ans = 0; boolean h = true ; while ( l <= r ) { med = ( l + r ) / 2 ; if ( check( s , ss , med , x ) ) { ans = med ; l = med + 1 ; h = false ; } else r = med - 1 ; } if ( h ) out.println(0); else out.println(ans+1); } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
84711ca2b136f08a0557dc2c06ad9f89
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; /* 4 1 1011 0000 0010 1000 */ public class MYpro { static ArrayList<Integer> adj[]; static boolean used[]; static int dovjunu[]; public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String s = reader.readLine(); char[] mas = s.toCharArray(); String s1 = reader.readLine(); char[] mas1 = s1.toCharArray(); String f = reader.readLine(); String[] ff=f.split(" "); int[] array=new int[ff.length]; for (int i=0;i<ff.length;i++) { array[i]=Integer.parseInt(ff[i])-1; } int l=0; int eee=1100; int r=mas.length-1; int mid=0; while (eee!=0) { char[] prob = new char[mas.length]; for (int i=0;i<prob.length;i++) { prob[i]=mas[i]; } eee--; mid = (l + r) / 2; for (int i = 0; i < mid; i++) { prob[array[i]] = ' '; } int j = 0; boolean t = false; for (int i = 0; i < mas.length; i++) { if (prob[i] == mas1[j]) j++; if (j == mas1.length) { t = true; break; } } if (t) { l = mid; } else { r = mid; } } eee--; mid = (l + r) / 2; if (mid!=array.length-1) mid++; for (int i = 0; i < mid; i++) { mas[array[i]] = ' '; } int j = 0; boolean t = false; for (int i = 0; i < mas.length; i++) { if (mas[i] == mas1[j]) j++; if (j == mas1.length) { t = true; break; } } if (t) System.out.println(mid); else System.out.println(mid-1); } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
f1ab8698174d2395cfc82ce80d457974
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * Created by akash.bansal on 03/03/17. */ public class CodeF778A { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String abc = new String(scan.next()); String def = new String(scan.next()); int a[] = new int[200005]; int visited[] = new int[200005]; for(int i=0;i<abc.length();i++){ a[i]=scan.nextInt(); } int mid=0,end=abc.length(); mid = (mid+end)/2; int ans=-1; while(mid<end){ for(int i=0;i<=mid;i++){ visited[a[i]-1]=1; } if(checkIfsubsequence(abc,def,visited)){ ans=mid; mid=(mid+1+end)/2; } else{ end=mid; mid=(0+end)/2; } for(int i=0;i<abc.length();i++){ visited[a[i]-1]=0; } } System.out.println(ans+1); } public static boolean checkIfsubsequence(String abc, String def, int[] visited){ int j=0; int i=0; for(i=0;i<def.length();i++){ boolean status=false; while (j<abc.length()){ if(def.charAt(i)==abc.charAt(j) && visited[j]==0){ status=true; j++; break; } else j++; } if(status==false) break; } if(i==def.length() ) return true; return false; } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
8073620f32721f0f5fbbe8b33a859c85
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.util.Arrays; import java.util.Scanner; public class StG { public static void main(String[] args){ Scanner scan = new Scanner(System.in); char[] a = scan.next().toCharArray(), b = scan.next().toCharArray(); int n = a.length; int[] arr = new int[n]; for (int i = 0; i < arr.length; i++) { arr[i] = scan.nextInt(); } int low = 0 , high = n ; while(low<=high){ int mid = (low+high)/2; char[] a2 = Arrays.copyOf(a, n); StringBuilder sb = new StringBuilder(); for(int i = 0 ; i < mid ; ++i){ a2[arr[i]-1] = '?'; } for (int i = 0; i < a2.length; i++) { if(a2[i] != '?')sb.append(Character.toString(a2[i])); } int p = 0 , s =0; while(p < b.length && s < sb.length()){ if(b[p]==sb.charAt(s)){ p++; } s++; } if(p == b.length){ low = mid +1; } else { high = mid-1; } } System.out.println(low-1); } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
eeabbad8eb568c9bc280458573de6be4
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import static java.lang.Integer.*; import static java.lang.Long.parseLong; import static java.lang.Short.parseShort; import static java.lang.Byte.parseByte; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Contest { static int nextInt() throws IOException { return parseInt(next()); } static long nextLong() throws IOException { return parseLong(next()); } static short nextShort() throws IOException { return parseShort(next()); } static byte nextByte() throws IOException { return parseByte(next()); } static String next() throws IOException { while (tok == null || !tok.hasMoreTokens()) tok = new StringTokenizer(in.readLine()); return tok.nextToken(); } static String nextLine() throws IOException { return in.readLine(); } private static BufferedReader in; private static StringTokenizer tok; private static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws Exception { in = new BufferedReader(new InputStreamReader(System.in)); /*--------------------SolutionStarted-------------------*/ solve(); /*--------------------SolutionEnded--------------------*/ in.close(); out.close(); } static void solve() throws IOException { char[] t = next().toCharArray(), p = next().toCharArray(), modifiedT = new char[t.length]; int[] indices = new int[t.length]; for (int i = 0; i < t.length; i++) { modifiedT[i] = t[i]; indices[i] = nextInt() - 1; } int l = 0, r = t.length - 1, mid = 0, pointer = 0, maxTrue = Integer.MIN_VALUE; while (r > l) { mid = (l + r) / 2; if (pointer <= mid) { for (int i = l; i <= mid; i++) modifiedT[indices[i]] = '0'; } else { for (int i = mid + 1; i <= pointer; i++) modifiedT[indices[i]] = t[indices[i]]; } pointer = mid; if (check(modifiedT, p)) { l = mid + 1; int zeroes = 0; for (int i = 0; i <modifiedT.length ; i++) if(modifiedT[i]=='0') zeroes++; maxTrue = Math.max(maxTrue, zeroes); } else { for (int i = mid; i <= pointer; i++) modifiedT[indices[i]] = t[indices[i]]; r = mid - 1; if(check(modifiedT, p)){ int zeroes = 0; for (int i = 0; i <modifiedT.length ; i++) if(modifiedT[i]=='0') zeroes++; maxTrue = Math.max(maxTrue, zeroes); } pointer = r; } } out.println(maxTrue== MIN_VALUE?0:maxTrue); } static boolean check(char[] modifiedT, char[] p) { int i = 0; for (int j = 0; j < modifiedT.length; j++) if (p[i] == modifiedT[j]) if (++i == p.length) return true; return false; } } class IntPair implements Comparable<IntPair> { int key, value; boolean visited; IntPair() { } IntPair(int key) { this.key = key; } @Override public int compareTo(IntPair o) { return key - o.key; } } class BooleanPair { boolean key, value; BooleanPair() { } BooleanPair(boolean key, boolean value) { this.key = key; this.value = value; } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
4cc9d3e783f4ec0acb06ba50921a2654
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.io.*; import java.util.*; public class c{ static int mod=1000000007; static PrintWriter out = new PrintWriter(System.out); static boolean ok(char t[],char p[],int a[],int mid){ boolean v[] = new boolean[a.length]; for(int i=0;i<mid;i++) v[a[i]-1]=true; int it=0,ip=0; while(it<t.length&&ip<p.length){ if(v[it]==true){it++;continue;} else if(t[it]==p[ip]){it++;ip++;} else it++; } if(ip==p.length) return true; return false; } public static void main(String[] args){ char t[] = n().toCharArray(); char p[] = n().toCharArray(); int n = t.length; int a[] = new int[n]; for(int i=0;i<n;i++) a[i] = ni(); int l=0,r=n+1; while((r-l)>1){ int mid = (l+r)/2; if(ok(t,p,a,mid)) l= mid; else r=mid; } out.println(l); out.flush(); } static FastReader sc=new FastReader(); static int ni(){ int x = sc.nextInt(); return(x); } static long nl(){ long x = sc.nextLong(); return(x); } static String n(){ String str = sc.next(); return(str); } static String ns(){ String str = sc.nextLine(); return(str); } static double nd(){ double d = sc.nextDouble(); return(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; } } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
05d39260c0aa1a7d73c05b6b6faef8bb
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
/* Keep solving problems. */ import java.util.*; import java.io.*; public class CFA { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; final long MOD = 1000L * 1000L * 1000L + 7; int[] dx = {0, -1, 0, 1}; int[] dy = {1, 0, -1, 0}; void solve() throws IOException { char[] all = nextString().toCharArray(); char[] needle = nextString().toCharArray(); int[] perm = nextIntArr(all.length); int l = 0; int r = all.length; while (l < r) { int mid = (l + r) / 2; List<Integer> available = new ArrayList<>(); for (int i = mid; i < perm.length; i++) { available.add(perm[i]); } Collections.sort(available); boolean valid = check(available, all, needle); if (valid) { l = mid + 1; } else { r = mid; } } out(l - 1); } boolean check(List<Integer> available, char[] all, char[] needle) { if (available.size() < needle.length) { return false; } int i = 0; int j = 0; while (i < available.size() && j < needle.length) { if (all[available.get(i) - 1] == needle[j]) { i++; j++; } else { i++; } } return j == needle.length; } void shuffle(int[] a) { int n = a.length; for(int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } long gcd(long a, long b) { while(a != 0 && b != 0) { long c = b; b = a % b; a = c; } return a + b; } private void outln(Object o) { out.println(o); } private void out(Object o) { out.print(o); } public CFA() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new CFA(); } public long[] nextLongArr(int n) throws IOException{ long[] res = new long[n]; for(int i = 0; i < n; i++) res[i] = nextLong(); return res; } public int[] nextIntArr(int n) throws IOException { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } public String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
6a9c3fd1e7e06e50d7154ff3aa2121d7
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.io.*; import java.util.StringTokenizer; /** * 778A * O(n*log(n)) time * θ(n) space * * @author artyom */ public class _778A implements Runnable { private BufferedReader in; private StringTokenizer tok; private int solve() throws IOException { String t = nextToken(), p = nextToken(); int n = t.length(); int[] rm = readIntArray(n); boolean[] b = new boolean[n]; int l = 0, r = n - p.length() - 1; for (boolean d = true; l <= r; ) { int m = (l + r) >> 1; if (d) { for (int i = l; i <= m; i++) { b[rm[i]] = true; } } else { for (int i = m + 1, lim = r + 1; i <= lim; i++) { b[rm[i]] = false; } } if (contains(t, p, b)) { l = m + 1; d = true; } else { r = m - 1; d = false; } } return l; } private static boolean contains(String t, String p, boolean[] b) { for (int i = 0, j = 0, n = t.length(), m = p.length(); i < n; i++) { if (!b[i]) { if (t.charAt(i) == p.charAt(j)) { j++; if (j == m) { return true; } } } } return false; } //-------------------------------------------------------------- public static void main(String[] args) { new _778A().run(); } @Override public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); tok = null; System.out.print(solve()); in.close(); } catch (IOException e) { System.exit(0); } } private String nextToken() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } private int[] readIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt() - 1; } return arr; } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
5ab8dc6839ffb9c8dd7a9652ab61ff1c
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import java.io.*; import java.math.*; public class Main7{ static public void main(String args[])throws IOException{ int tt=1; StringBuilder sb=new StringBuilder(); for(int ttt=1;ttt<=tt;ttt++){ String s=s(); String s1=s(); int n=s.length(); int[] a=new int[n]; for(int i=0;i<n;i++){ a[i]=i(); } int low=1; int high=n; int ans=0; while(low<=high){ int mid=low+(high-low)/2; boolean value=check(mid,s,s1,a); // pln(mid+" "+value); if(value){ ans=mid; low=mid+1; }else{ high=mid-1; } } sb.append(ans+"\n"); } System.out.print(sb.toString()); } static boolean check(int mid,String s, String pat,int[] a){ int n=a.length; HashSet<Integer> hash=new HashSet<>(); for(int i=0;i<mid;i++){ hash.add(a[i]); } StringBuilder sb=new StringBuilder(); for(int i=0;i<n;i++){ if(hash.contains(i+1)==false){ sb.append(s.charAt(i)); } } String s1=sb.toString(); int k=0; for(int i=0;i<s1.length();i++){ if(k<pat.length() && s1.charAt(i)==pat.charAt(k)){ k++; } } if(k==pat.length()) return true; return false; } static InputReader in=new InputReader(System.in); static OutputWriter out=new OutputWriter(System.out); static ArrayList<ArrayList<Integer>> graph; static int mod=1000000007; static class Pair{ String x; String y; Pair(String x,String y){ this.x=x; this.y=y; } } public static int[] sort(int[] a){ int n=a.length; ArrayList<Integer> ar=new ArrayList<>(); for(int i=0;i<a.length;i++){ ar.add(a[i]); } Collections.sort(ar); for(int i=0;i<n;i++){ a[i]=ar.get(i); } return a; } public static long pow(long a, long b){ long result=1; while(b>0){ if (b % 2 != 0){ result=(result*a); b--; } a=(a*a); b /= 2; } return result; } public static long gcd(long a, long b){ if (a == 0){ return b; } return gcd(b%a, a); } public static long lcm(long a, long b){ return a*(b/gcd(a,b)); } public static long l(){ String s=in.String(); return Long.parseLong(s); } public static void pln(String value){ System.out.println(value); } public static int i(){ return in.Int(); } public static String s(){ return in.String(); } } 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 Int() { 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 String() { 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 String(); } 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(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.Int(); return array; } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
d21a4af8781299eed64f91fd27a2e408
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.util.*; import java.io.*; public class cf { static int n; static int k; static String s1; static String s2; static int arr[]; public static boolean check(int num) { Set<Integer> hs=new HashSet<Integer>(); for(int i = 0 ;i<num;i++) { hs.add(arr[i]); } StringBuilder s=new StringBuilder(""); for(int i =0 ;i<s1.length();i++) { if(!hs.contains(i+1)) s=s.append(s1.charAt(i)); } int j = 0; for (int i=0; i<s.length()&&j<s2.length(); i++) if (s2.charAt(j) == s.charAt(i)) j++; return (j==s2.length()); } public static void main(String[] args)throws IOException { PrintWriter out= new PrintWriter(System.out); BufferedReader sc = new BufferedReader(new InputStreamReader(System.in)); s1=sc.readLine(); s2=sc.readLine(); arr=new int[s1.length()]; StringTokenizer st = new StringTokenizer(sc.readLine()); for(int i=0;i<s1.length();i++) arr[i]=Integer.parseInt(st.nextToken()); int low=0; int high=s1.length()-1; while(low<high) { int mid=(low+high+1)/2; if(check(mid)) low=mid; else high=mid-1; } System.out.println(low); } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
2bc28dc2df0871fcfc73b330156b9129
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.util.Arrays; import java.util.Scanner; public class CF778A { static char[] src; static char[] target; static int[] p; // static char[][] states; public static void main(String[] args) { Scanner sc = new Scanner(System.in); src = sc.next().toCharArray(); target = sc.next().toCharArray(); p = new int[src.length]; // states = new char[src.length][src.length]; for(int i=0; i<src.length; i++) { p[i] = sc.nextInt()-1; // states[i] = Arrays.copyOf(i==0 ? src : states[i-1], src.length); // states[i][index] = '_'; } System.out.println(getAns(0, src.length)); } static int getAns(int start, int end) { if(end-start==1) { if(isSub(start)) return end; else return start; } else { int mid = (end+start)/2; if(isSub(mid)) return getAns(mid, end); else return getAns(start, mid); } } static boolean isSub(int x) { char[] state = Arrays.copyOf(src, src.length); for(int i=0; i<=x; i++) state[p[i]] = '_'; int index = 0; for(int i=0; i<target.length; i++) { if(index==state.length) return false; while(target[i]!=state[index]) { index++; if(index==state.length) return false; } index++; } return true; } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
32a0f74a82d3ab4041c50aff2ba9c257
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; /** * * @author Ala Abid */ public class JavaApplication98 { /** * @param args the command line arguments * */ static String s; static String p; static int[] perm; public static void main(String[] args) throws IOException { // TODO code application logic here BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); s = br.readLine(); p=br.readLine(); StringTokenizer st = new StringTokenizer(br.readLine()); perm = new int[s.length()]; for (int i=0;i<s.length();i++){ perm[i]=Integer.parseInt(st.nextToken()); } int mid; int lo = 0; int hi =s.length()-1; while(lo<=hi){ mid = lo + (hi-lo)/2; if(check(mid)==true){ if (check(mid+1)==false){ System.out.println((mid+1)); return; } lo=mid+1; } else hi=mid-1; } System.out.println("0"); } static boolean check(int ind){ int j=0; int sLen=s.length(); int pLen=p.length(); char[] aux = s.toCharArray(); for(int i =0 ; i<=ind ; i++){ aux[perm[i]-1]='0'; } for(int i=0;i<sLen;i++){ if(aux[i]==p.charAt(j)) { j++; if (j==p.length()) return true; } } return false; } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
5515cbf6c302fc69ad9f7a0b926d1125
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.util.*; public class PlayOnTheLine { public void run() { Scanner in = new Scanner(System.in); String t = in.next(); String p = in.next(); int[] A = new int[t.length()]; for (int i = 0; i < t.length(); i++) { A[i] = in.nextInt(); } int l = 0, r = t.length(); while (l < r) { int m = (l + r) / 2; StringBuilder t_ = new StringBuilder(t); for (int i = 0; i <= m; i++) { t_.setCharAt(A[i] - 1, '.'); } int i_ = 0; for (int i = 0; i < t.length(); i++) { if (t_.charAt(i) == p.charAt(i_)) { i_++; if (i_ == p.length()) { break; } } } if (i_ == p.length()) { l = m + 1; } else r = m; } System.out.println(l); } public static void main(String[] args) { new PlayOnTheLine().run(); } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
a40e99732b465a677561d5264fd23206
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.awt.Point; 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.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; public class A { public static int a[] = new int[200001]; public static String s1,s2; public static boolean was[] = new boolean[a.length]; public static boolean check(int m) { Arrays.fill(was, false); for (int i = 0; i < m; i++) was[a[i] - 1] = true; int q = 0; for (int i = 0; i < s1.length(); i++) { if (was[i]) continue; if (s2.charAt(q) == s1.charAt(i)) q++; if (q == s2.length()) return true; } return false; } public static void main(String[] args) throws IOException { // Scanner in = new Scanner(System.in); // PrintWriter out = new PrintWriter(System.out); BufferedReader scan = new BufferedReader(new InputStreamReader(System.in)); s1 = scan.readLine(); s2 = scan.readLine(); String k[] = scan.readLine().split(" "); for (int i = 0; i < k.length; i++) a[i] = Integer.parseInt(k[i]); int l = 0, r = s1.length() - 1,m = 0; while (l <= r) { m = (l + r) / 2; boolean ok = check(m); //System.out.println(m + " " + ok); if (ok) { l = m + 1; } else { r = m - 1; } } System.out.println(l - 1); } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
8c4f351347002f86b1d43b9272f54f2a
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.io.*; import java.text.*; import java.util.*; import java.math.*; public class A { public static void main(String[] args) throws Exception { new A().run(); } public void run() throws Exception { FastScanner f = new FastScanner(); PrintWriter out = new PrintWriter(System.out); char[] s = f.next().toCharArray(), t = f.next().toCharArray(); int n = s.length, m = t.length; int[] arr = new int[n]; for(int i = 0; i < n; i++) arr[i] = f.nextInt()-1; int l = 0, r = n; while(l < r) { int md = (l+r)/2; boolean[] skip = new boolean[n]; for(int i = 0; i < md; i++) skip[arr[i]] = true; int j = 0; for(int i = 0; i < n && j < m; i++) { if(skip[i]) continue; if(s[i] == t[j]) j++; } if(j == m) l = md+1; else r = md; } out.println(l-1); out.flush(); } 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); } } } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
c0db9063b67befd6f0f3f9ef43a54eaf
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.util.*; import java.util.Arrays; public class stringgame { /*public static boolean stableState(String cur, String key){ int i; int j = 0; int found = 0; for(i = 0; i< cur.length(); i++){ if(cur.charAt(i)== key.charAt(j)){ j++; if(j == key.length()){ return true; } } } return false; } public static String getSubstring(String input,int[] index,int start){ String cur = new String(new char[index.length-start]).replace('\0', ' '); //System.out.println(input); for(int i=start;i<index.length;i++){ System.out.println(part[j]); /* if(i==part[j]-1){ ++j; if(j>=part.length){ j--; } } else{ cur = cur + input.charAt(i); }*/ //cur[input.charAt(index[i]-1); /* } System.out.println(cur); return cur; }*/ public static boolean isFeasible(int index,String input,String key,int[] indizes){ boolean[] removed = new boolean[input.length()]; for(int i = 0; i < index+1; ++i){ removed[indizes[i]-1] = true; } int k = 0; for(int i = 0; i <key.length(); ++i){ boolean found = false; int j; for(j=k;j < input.length(); ++j){ if(key.charAt(i)==input.charAt(j) && !removed[j]){ found = true; break; } } if(!found){ return false; } else { k = j+1; } } return true; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); String input = sc.next(); String key = sc.next(); int[] index = new int[input.length()]; for(int i = 0; i< input.length(); i++){ index[i]= sc.nextInt(); } int sol = 0; int low = 0; int high = index.length; int middle; if(!isFeasible(0,input,key,index)){ System.out.println("0"); return; } sol = -1; do{ int[] part; middle = (low+high)/2; //part = Arrays.copyOfRange(index, middle+1, index.length); //Arrays.sort(part); //String cur=""; //int j = 0; //cur = getSubstring(input,index,middle+1); //System.out.println("Cur: " +cur); //if(stableState(cur, key)){ if(isFeasible(middle,input,key,index)){ // We are still stable // Set low = end; // start = end // Want to start searching from the old end low = middle+1; sol = middle; } else{ // We are unstable high = middle-1; } } while(low<=high); System.out.println(sol+1); return; } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
0aaad068ee07fdc7d987364ebfb3b117
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.util.*; import java.io.*; import java.net.*; import java.sql.*; import java.awt.*; import java.text.*; import java.math.*; import java.time.*; import javax.swing.*; public class Main { //http://codeforces.com/problemset/problem/778/A(����) private static char[] string_t,string_p; private static boolean[]vis; private static int[]indexs; private static int mid,l,r; private static int ans; public static void main(String[] args) { // TODO Auto-generated method stub Scanner in=new Scanner(System.in); string_t=in.next().toCharArray(); string_p=in.next().toCharArray(); indexs=new int[string_t.length]; for(int i=0;i<string_t.length;i++)indexs[i]=in.nextInt(); vis=new boolean[string_t.length]; for(int i=0;i<string_t.length;i++)vis[i]=false; l=0;r=string_t.length-1; /*System.out.println("string_t="+string_t); System.out.println("string_p="+string_p);*/ //for(int i=0;i<string_t.length();i++)System.out.print(indexs[i]+" "); while(l<=r){ mid=(r+l)/2; //System.out.println("mid="+mid); if(judge(mid)){ l=mid+1; ans=mid; } else r=mid-1; } System.out.println(ans); } public static boolean judge(int index){ for(int i=0;i<string_t.length;i++)vis[i]=false; for(int i=0;i<index;i++)vis[indexs[i]-1]=true; int xx=0; for(int i=0;i<string_t.length;i++){ if(!vis[i]&&string_t[i]==string_p[xx])xx++; if(xx>=string_p.length)return true; } return false; } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
d1656e8f63e3267a803cac956d1b667a
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
/* DHUOJ solution #356081 @ 2018-07-26 19:11:12.450 */ import java.io.*; import java.util.*; public class Main { public static void main(String args[]) { Solution solution = new Solution(); solution.compute(); } } class Solution { String t; String p; int[] a; boolean[] moved; void compute() { Scanner scanner = new Scanner(new BufferedInputStream(System.in)); t = scanner.next(); p = scanner.next(); a = new int[t.length()]; moved = new boolean[t.length()]; for (int i = 0; i < t.length(); i++) { a[i] = scanner.nextInt(); a[i]--; } int lef = -1; int rig = t.length() - 1; int mid; while (lef < rig) { mid = lef + (int) Math.ceil((rig - lef) / 2.0); if (check(mid)) { lef = mid; } else { rig = mid - 1; } } System.out.println(rig); scanner.close(); } boolean check(int mid) { Arrays.fill(moved, false); for (int i = 0; i < mid; i++) { moved[a[i]] = true; } int j = 0; for (int i = 0; i < t.length() && j < p.length(); i++) { if (!moved[i] && t.charAt(i) == p.charAt(j)) { j++; } } return j == p.length(); } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
6968a05564e421ce95fd5cee1057562f
train_002.jsonl
1488096300
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
512 megabytes
import java.io.*; import java.util.*; public class MyClass { public static void main(String args[]) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)) ; String t=br.readLine(); String p=br.readLine(); String[] Str = br.readLine().split(" ") ; int a[]=new int[t.length()]; for(int i=0;i<t.length();i++) a[i]=Integer.parseInt(Str[i]); int l=0; int r=t.length(); while(l<r) { int mid=(l+r+1)/2; if(f(t,p,a,mid)==true) l=mid; else r=mid-1; } System.out.println(l); } public static boolean f(String a,String b,int a3[],int m) { boolean b1[]=new boolean[a.length()+1]; for(int i=0;i<m;i++) b1[a3[i]]=true; int i=0; int j=0; while(i<a.length()&&j<b.length()) { char ch1=a.charAt(i); char ch2=b.charAt(j); if(ch1==ch2&&b1[i+1]==false) { i++; j++; } else i++; } if(j==b.length()) return true; else return false; } }
Java
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
2 seconds
["3", "4"]
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
Java 8
standard input
[ "binary search", "greedy", "strings" ]
0aed14262c135d1624df9814078031ae
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| &lt; |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
1,700
Print a single integer number, the maximum number of letters that Nastya can remove.
standard output
PASSED
49f7f45ae02e70f699e6f73d48c5e529
train_002.jsonl
1469804400
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
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) Math.pow(10, 16); 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 = 1000000007; private static final int MAXN = 200001; private static final int MAXA = 1000007; 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"))); /* */ int n = in.nextInt(); int m = in.nextInt(); Set<Long> cities = new HashSet<>(); Set<Long> towers = new HashSet<>(); for(int i = 0; i < n; i++) { long val = in.nextLong(); cities.add(val); } for(int i = 0; i < m; i++) { long val = in.nextLong(); towers.add(val); } List<Long> list1 = new ArrayList<>(cities); Collections.sort(list1); List<Long> list2 = new ArrayList<>(towers); Collections.sort(list2); int sz = list2.size(); long maxr = NEG_INF; for(long e : list1) { int cnt = (int)upperBound(list2, e); if(cnt == 0) { maxr = max(abs(e - list2.get(0)), maxr); } else if(cnt == sz) { maxr = max(abs(e - list2.get(sz - 1)), maxr); } else { maxr = max(min(abs(e - list2.get(cnt)), abs(e - list2.get(cnt - 1))), maxr); } } out.println(maxr); 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 long lcm(long a, long b) { return (a * b) / gcd(a, b); } 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 int log(long x, long 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
["3 2\n-2 2 4\n-3 0", "5 3\n1 5 10 14 17\n4 11 15"]
3 seconds
["4", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation" ]
9fd8e75cb441dc809b1b2c48c4012c76
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
1,500
Print minimal r so that each city will be covered by cellular network.
standard output
PASSED
f3a6e3859529b1094be72ffaaf782224
train_002.jsonl
1469804400
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main { static BufferedReader in; static PrintWriter out; static StringTokenizer buffer; public static void solve() { int n=ni(), m=ni(); int[]a = ni(n), b = ni(m); Arrays.sort(a); Arrays.sort(b); int t = 0; long res = 0; for (int i=0;i<n;i++) { while (t<m-1 && Math.abs(a[i]-b[t+1]) <= Math.abs(a[i]-b[t])) t++; int x = Math.abs(a[i]-b[t]); res = Math.max(res, Math.abs(a[i]-b[t])); } out.println(res); } public static void main(String[] args) throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } static String next() { while (buffer == null || !buffer.hasMoreElements()) { try { buffer = new StringTokenizer(in.readLine()); } catch (IOException e) { } } return buffer.nextToken(); } static int ni() { return Integer.parseInt(next()); } static long nl() { return Long.parseLong(next()); } static double nd() { return Double.parseDouble(next()); } static String ns() { return next(); } static int[] ni(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) res[i] = Integer.parseInt(next()); return res; } static long[] nl(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) res[i] = Long.parseLong(next()); return res; } static double[] nd(int n) { double[] res = new double[n]; for (int i = 0; i < n; i++) res[i] = Double.parseDouble(next()); return res; } static String[] ns(int n) { String[] res = new String[n]; for (int i = 0; i < n; i++) res[i] = next(); return res; } }
Java
["3 2\n-2 2 4\n-3 0", "5 3\n1 5 10 14 17\n4 11 15"]
3 seconds
["4", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation" ]
9fd8e75cb441dc809b1b2c48c4012c76
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
1,500
Print minimal r so that each city will be covered by cellular network.
standard output
PASSED
14a09981dd62fbd69fc6bc9ff92b52f6
train_002.jsonl
1469804400
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; public class Problem3 { static int ptr; public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); int n = in.nextInt(); int m = in.nextInt(); int[] a = new int[n]; for(int i = 0; i < n; ++i) { a[i] = in.nextInt(); } int[] b = new int[m]; for(int j = 0; j < m ; ++j) { b[j] = in.nextInt(); } int ans = -1; int c, l, r; for(int i = 0; i < n; ++i) { c = a[i]; l = b[left(c, b)]; r = b[right(c, b)]; ans = Math.max(ans, Math.min(dist(c,l), dist(c,r))); } out.println(ans); out.close(); } static int left(int c, int[] b) { int lo = 0, hi = b.length - 1; while(hi>lo) { int mid = lo + (hi - lo + 1)/2; if( c < b[mid]) { hi = mid - 1; } else { lo = mid; } } return lo; } static int right(int c, int[] b) { int lo = 0, hi = b.length - 1; while(hi>lo) { int mid = lo + (hi - lo)/2; if( c < b[mid]) { hi = mid; } else { lo = mid + 1; } } return lo; } static int dist(int c, int s) { return Math.abs(c-s); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["3 2\n-2 2 4\n-3 0", "5 3\n1 5 10 14 17\n4 11 15"]
3 seconds
["4", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation" ]
9fd8e75cb441dc809b1b2c48c4012c76
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
1,500
Print minimal r so that each city will be covered by cellular network.
standard output
PASSED
0fa6eeb178836e85a4ba6249fd380ec2
train_002.jsonl
1469804400
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
256 megabytes
//package contest702; import java.util.ArrayList; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); ArrayList<Integer> a = new ArrayList<Integer>(); for(int i = 0; i < n; i++){ int temp = in.nextInt(); if(i == 0 || a.get(a.size()-1) != temp){ a.add(temp); } } ArrayList<Integer> b = new ArrayList<Integer>(); for(int i = 0; i < m; i++){ int temp = in.nextInt(); if(i == 0 || b.get(b.size()-1) != temp){ b.add(temp); } } int max = 0; int j = 0; for(int i = 0; i < a.size(); i++){ if(a.get(i) > b.get(j)){ while(j+1 < b.size() && Math.abs(a.get(i)-b.get(j))>Math.abs(a.get(i)-b.get(j+1))){ j++; } // System.out.println(a.get(i) + " " + b.get(j)); int closest = Math.abs(a.get(i)-b.get(j)); if(max < closest) max = closest; }else if(a.get(i) == b.get(j)){ int closest = 0; }else{ // System.out.println(a.get(i) + " " + b.get(j)); int closest = Math.abs(a.get(i)-b.get(j)); if(max < closest) max = closest; } } System.out.println(max); } }
Java
["3 2\n-2 2 4\n-3 0", "5 3\n1 5 10 14 17\n4 11 15"]
3 seconds
["4", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation" ]
9fd8e75cb441dc809b1b2c48c4012c76
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
1,500
Print minimal r so that each city will be covered by cellular network.
standard output
PASSED
8fdc0e34d6f1fe488b18c472b953488b
train_002.jsonl
1469804400
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
256 megabytes
/* * Author- Priyam Vora * BTech 2nd Year DAIICT */ import java.io.*; import java.math.*; import java.util.*; import javax.print.attribute.SetOfIntegerSyntax; public class Graph1 { private static InputStream stream; private static byte[] buf = new byte[1024]; private static int curChar; private static int numChars; private static SpaceCharFilter filter; private static PrintWriter pw; private static long count = 0,mod=1000000007; private static TreeSet<Integer>ts[]=new TreeSet[200000]; public static void main(String args[]) throws Exception { InputReader(System.in); pw = new PrintWriter(System.out); //ans(); soln(); pw.close(); } public static long gcd(long x, long y) { if (x == 0) return y; else return gcd( y % x,x); } private static int BinarySearch(int a[], int low, int high, int target) { if (low > high) return -1; int mid = low + (high - low) / 2; if (a[mid] == target) return mid; if (a[mid] > target) high = mid - 1; if (a[mid] < target) low = mid + 1; return BinarySearch(a, low, high, target); } public static String reverseString(String s) { StringBuilder sb = new StringBuilder(s); sb.reverse(); return (sb.toString()); } public static long pow(long n, long p) { if(p==0) return 1; if(p==1) return n%mod; if(p%2==0){ long temp=pow(n, p/2); return (temp*temp)%mod; }else{ long temp=pow(n,p/2); temp=(temp*temp)%mod; return(temp*n)%mod; } } public static int[] radixSort(int[] f) { int[] to = new int[f.length]; { int[] b = new int[65537]; for (int i = 0; i < f.length; i++) b[1 + (f[i] & 0xffff)]++; for (int i = 1; i <= 65536; i++) b[i] += b[i - 1]; for (int i = 0; i < f.length; i++) to[b[f[i] & 0xffff]++] = f[i]; int[] d = f; f = to; to = d; } { int[] b = new int[65537]; for (int i = 0; i < f.length; i++) b[1 + (f[i] >>> 16)]++; for (int i = 1; i <= 65536; i++) b[i] += b[i - 1]; for (int i = 0; i < f.length; i++) to[b[f[i] >>> 16]++] = f[i]; int[] d = f; f = to; to = d; } return f; } public static int nextPowerOf2(final int a) { int b = 1; while (b < a) { b = b << 1; } return b; } public static boolean PointInTriangle(int p1, int p2, int p3, int p4, int p5, int p6, int p7, int p8) { int s = p2 * p5 - p1 * p6 + (p6 - p2) * p7 + (p1 - p5) * p8; int t = p1 * p4 - p2 * p3 + (p2 - p4) * p7 + (p3 - p1) * p8; if ((s < 0) != (t < 0)) return false; int A = -p4 * p5 + p2 * (p5 - p3) + p1 * (p4 - p6) + p3 * p6; if (A < 0.0) { s = -s; t = -t; A = -A; } return s > 0 && t > 0 && (s + t) <= A; } public static float area(int x1, int y1, int x2, int y2, int x3, int y3) { return (float) Math.abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0); } public static boolean isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } //merge Sort static long sort(int a[]) { int n=a.length; int b[]=new int[n]; return mergeSort(a,b,0,n-1);} static long mergeSort(int a[],int b[],long left,long right) { long c=0;if(left<right) { long mid=left+(right-left)/2; c= mergeSort(a,b,left,mid); c+=mergeSort(a,b,mid+1,right); c+=merge(a,b,left,mid+1,right); } return c; } static long merge(int a[],int b[],long left,long mid,long right) {long c=0;int i=(int)left;int j=(int)mid; int k=(int)left; while(i<=(int)mid-1&&j<=(int)right) { if(a[i]>a[j]) {b[k++]=a[i++]; } else { b[k++]=a[j++];c+=mid-i;}} while (i <= (int)mid - 1) b[k++] = a[i++]; while (j <= (int)right) b[k++] = a[j++]; for (i=(int)left; i <= (int)right; i++) a[i] = b[i]; return c; } public static boolean isSubSequence(String large, String small, int largeLen, int smallLen) { //base cases if (largeLen == 0) return false; if (smallLen == 0) return true; // If last characters of two strings are matching if (large.charAt(largeLen - 1) == small.charAt(smallLen - 1)) isSubSequence(large, small, largeLen - 1, smallLen - 1); // If last characters are not matching return isSubSequence(large, small, largeLen - 1, smallLen); } // To Get Input // Some Buffer Methods public static void InputReader(InputStream stream1) { stream = stream1; } private static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private static boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } private static 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 static 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 static 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 static 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 static 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 static int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } private static int[][] next2dArray(int n, int m) { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = nextInt(); } } return arr; } private static char[][] nextCharArray(int n,int m){ char [][]c=new char[n][m]; for(int i=0;i<n;i++){ String s=nextLine(); for(int j=0;j<s.length();j++){ c[i][j]=s.charAt(j); } } return c; } private static long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private static void pArray(int[] arr) { for (int i = 0; i < arr.length; i++) { pw.print(arr[i] + " "); } pw.println(); return; } private static void pArray(long[] arr) { for (int i = 0; i < arr.length; i++) { pw.print(arr[i] + " "); } pw.println(); return; } private static void pArray(boolean[] arr) { for (int i = 0; i < arr.length; i++) { pw.print(arr[i] + " "); } pw.println(); return; } private static boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } private interface SpaceCharFilter { public boolean isSpaceChar(int ch); } //----------------------------------------My Code------------------------------------------------// static int[] ht, lev,indeg,sub_size; static boolean visited[]; static LinkedList<Integer> adj[]; private static void center_of_tree(){ Queue <Integer> q=new LinkedList<Integer>(); for(int i=1;i<indeg.length;i++){ if(indeg[i]==0){ q.add(i); for(int j=0;j<adj[i].size();j++){ indeg[adj[i].get(j)]--; } } } q.add(-1); while(q.size()>2){ int temp=q.poll(); if(temp==-1){ q.add(temp); }else{ for(int j=0;j<adj[temp].size();j++){ indeg[adj[temp].get(j)]--; if(indeg[adj[temp].get(j)]==0) q.add(adj[temp].get(j)); } } } int ele1=q.poll(); if(ele1==-1){ pw.println("center "+q.poll()); }else{ pw.println("Center-1 "+q.poll() +"\n Center-2 "+q.poll()); } } private static void height (int par,int curr){ visited[curr]=true; for(int x:adj[curr]){ if(!visited[x]){ height(curr,x); } } ht[par]=Math.max(ht[par], ht[curr]+1); //sub_size[curr]=1; sub_size[par]+=sub_size[curr]; } private static int BFS(int st){ Arrays.fill(lev, 0); visited[st]=true; Queue<Integer> q=new LinkedList<Integer>(); q.add(st); int far=-1; while(!q.isEmpty()){ int top=q.poll(); far=top; for(int x:adj[top]){ if(!visited[x]) { q.add(x); lev[x]=(lev[top]+1); visited[x]=true; } } } return far; } static HashSet<Long> hs; static long []a,b; private static void soln() { hs=new HashSet<Long>(); int n=nextInt(); int m=nextInt(); a=nextLongArray(n); b=nextLongArray(m); for(int i=0;i<m;i++){ hs.add(b[i]); } long low=0,high=(long)1e18,mid=0; while(high>=low){ mid=(low+high)/2; //System.out.println(low+" "+high); if(check(mid)){ high=mid-1; }else{ low=mid+1; } } pw.println(low); } private static boolean check(long r){ int ptr1=0,ptr2=0; while(ptr1<a.length && ptr2<b.length){ long ex=b[ptr2]+r; long el=b[ptr2]-r; if(a[ptr1]>=el && a[ptr1]<=ex){ ptr1++; }else{ ptr2++; } } if(ptr1==a.length){ return true; } return false; } //-----------------------------------------The End--------------------------------------------------------------------------// } class Hashing { static final int multiplier = 43; static final Random rnd = new Random(); static final int mod1 = BigInteger.valueOf((int) (1e9 + rnd.nextInt((int) 1e9))).nextProbablePrime().intValue(); static final int mod2 = BigInteger.valueOf((int) (1e9 + rnd.nextInt((int) 1e9))).nextProbablePrime().intValue(); static final int invMultiplier1 = BigInteger.valueOf(multiplier).modInverse(BigInteger.valueOf(mod1)).intValue(); static final int invMultiplier2 = BigInteger.valueOf(multiplier).modInverse(BigInteger.valueOf(mod2)).intValue(); long[] hash1, hash2; long[] inv1, inv2; int n; public Hashing(String s) { n = s.length(); hash1 = new long[n + 1]; hash2 = new long[n + 1]; inv1 = new long[n + 1]; inv2 = new long[n + 1]; inv1[0] = 1; inv2[0] = 1; long p1 = 1; long p2 = 1; for (int i = 0; i < n; i++) { hash1[i + 1] = (hash1[i] + s.charAt(i) * p1) % mod1; p1 = p1 * multiplier % mod1; inv1[i + 1] = inv1[i] * invMultiplier1 % mod1; hash2[i + 1] = (hash2[i] + s.charAt(i) * p2) % mod2; p2 = p2 * multiplier % mod2; inv2[i + 1] = inv2[i] * invMultiplier2 % mod2; } } public long getHash(int i, int r) { i--; return (((hash1[r] - hash1[i] + mod1) * inv1[i] % mod1) << 32) + (hash2[r] - hash2[i] + mod2) * inv2[i] % mod2; } } class Pair implements Comparable<Pair>{ int ind; int len; Pair(int ind,int len){ this.ind=ind; this.len=len; } @Override public int compareTo(Pair o) { // TODO Auto-generated method stub // Sort in increasing order return ind-o.ind; } } class Graph{ private static int V,level[][],count=-1,lev_dfs[],degree=0,no_vert_conn_comp=0; private Stack <Integer>st=new Stack(); private static LinkedList<Integer > adj[]; private boolean[][] Visite; private static boolean [] Visited; private static HashSet<Integer> Vis=new HashSet(); private static Stack<Integer> topo_sort=new Stack<>(); private static HashMap<String,Integer> hm=new HashMap<>(); private static int ht[]; Graph(int V){ V++; this.V=(V); adj=new LinkedList[V]; Visite=new boolean[100][100]; ht=new int[V]; Visited=new boolean[V]; level=new int[100][100]; lev_dfs=new int[V]; for(int i=0;i<V;i++) adj[i]=new LinkedList<Integer>(); } void addEdge(int v,int w){ if(adj[v]==null){ adj[v]=new LinkedList(); } adj[v].add(w); } private static void height (int par,int curr){ Visited[curr]=true; for(int x:adj[curr]){ if(!Visited[x]){ height(curr,x); } } ht[par]=Math.max(ht[par], ht[curr]+1); } public static void top_ans(){ while(topo_sort.size()!=0) { System.out.print(hm.get(topo_sort.peek())); topo_sort.pop(); } } public static void topoSort(int startVert){ if(!Vis.contains(startVert)){ topoSortUtil(startVert); } } public static void topoSortUtil(int curr_Vert){ Vis.add(curr_Vert); Iterator<Integer> it=adj[curr_Vert].listIterator(); while(it.hasNext()){ int n=it.next(); // System.out.println(n); if(!Vis.contains(n)){ topoSortUtil(n); } } topo_sort.push(curr_Vert); } public static int BFS2(int startVert){ Visited=new boolean[V]; for(int i=1;i<V;i++){ lev_dfs[i]=-1; } // System.out.println(startVert); Queue<Integer> q=new LinkedList<Integer>(); q.add(startVert); lev_dfs[startVert]=0; while(!q.isEmpty()){ int top=q.poll(); Iterator<Integer> i= adj[top].listIterator(); while(i.hasNext()){ int n=i.next(); // System.out.println(top+" "+n); if(!Visited[n]){ q.add(n); Visited[n]=true; lev_dfs[n]=lev_dfs[top]+1; } } } // q.clear(); return -1; } public static int getAn(int end){ return lev_dfs[end]; } public int getEd(){ return degree/2; } public void get(int from,int to){ int h=lev_dfs[from]-lev_dfs[to]; if(h<=0){ System.out.println(-1); }else{ System.out.println(h-1); } } private static boolean check(int x,int y,char c[][]){ if((x>=0 && y>=0) && (x<c.length && y<c[0].length) && c[x][y]!='#'){ return true; } return false; } public int BFS(int x,int y,int k,char[][] c) { LinkedList<Pair> queue = new LinkedList<Pair>(); //Visited[s]=true; // queue.add(new Pair(x,y)); int count=0; level[x][y]=-1; c[x][y]='M'; while (!queue.isEmpty()) { Pair temp = queue.poll(); } return V; } public long dfs(int startVertex,int end){ // getAns(startVertex); Visited=new boolean[V]; if(!Visited[startVertex]) { return dfsUtil(startVertex,end); //return getAns(); } return 0; } private long dfsUtil(int startVertex,int end) {//0-Blue 1-Pink int c=1; long cout=0; degree=0; Visited[startVertex]=true; lev_dfs[startVertex]=0; st.push(startVertex); int temp=-1; while(!st.isEmpty()){ int top=st.pop(); temp=Math.max(temp, top); // ts.add(top); Iterator<Integer> i=adj[top].listIterator(); while(i.hasNext()){ // System.out.println(top); int n=i.next(); if( !Visited[n]){ Visited[n]=true; // col_freq[col[n-1]]++; c++; st.push(n); lev_dfs[n]=lev_dfs[top]+1; if(n==end){ return lev_dfs[n]; } } } } // System.out.println(temp); if(lev_dfs[temp]+(end-temp)<=0){ return end-startVertex; } return Math.min(end-startVertex, lev_dfs[temp]+(end-temp)); } } class Dsu{ private int rank[], parent[] ,n; Dsu(int size){ this.n=size+1; rank=new int[n]; parent=new int[n]; makeSet(); } void makeSet(){ for(int i=0;i<n;i++){ parent[i]=i; } } int find(int x){ if(parent[x]!=x){ parent[x]=find(parent[x]); } return parent[x]; } void union(int x,int y){ int xRoot=find(x); int yRoot=find(y); if(xRoot==yRoot) return; if(rank[xRoot]<rank[yRoot]){ parent[xRoot]=yRoot; }else if(rank[yRoot]<rank[xRoot]){ parent[yRoot]=xRoot; }else{ parent[yRoot]=xRoot; rank[xRoot]++; } } } class Heap{ public static void build_max_heap(long []a,int size){ for(int i=size/2;i>0;i--){ max_heapify(a, i,size); } } private static void max_heapify(long[] a,int i,int size){ int left_child=2*i; int right_child=(2*i+1); int largest=0; if(left_child<size && a[left_child]>a[i]){ largest=left_child; }else{ largest=i; } if(right_child<size && a[right_child]>a[largest]){ largest=right_child; } if(largest!=i){ long temp=a[largest]; a[largest]=a[i]; a[i]=temp; max_heapify(a, largest,size); } } private static void min_heapify(int[] a,int i){ int left_child=2*i; int right_child=(2*i+1); int largest=0; if(left_child<a.length && a[left_child]<a[i]){ largest=left_child; }else{ largest=i; } if(right_child<a.length && a[right_child]<a[largest]){ largest=right_child; } if(largest!=i){ int temp=a[largest]; a[largest]=a[i]; a[i]=temp; min_heapify(a, largest); } } public static void extract_max(int size,long a[]){ if(a.length>1){ long max=a[1]; a[1]=a[a.length-1]; size--; max_heapify(a, 1,a.length-1); } } } class MyComp implements Comparator<Long>{ @Override public int compare(Long o1, Long o2) { if(o1<o2){ return 1; }else if(o1>o2){ return -1; } return 0; } }
Java
["3 2\n-2 2 4\n-3 0", "5 3\n1 5 10 14 17\n4 11 15"]
3 seconds
["4", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation" ]
9fd8e75cb441dc809b1b2c48c4012c76
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
1,500
Print minimal r so that each city will be covered by cellular network.
standard output
PASSED
8f3d0968adfd0f8c68ae4ae6fcca3115
train_002.jsonl
1469804400
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
256 megabytes
import java.io.*; import java.util.*; public class Ultimo { public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(System.in); int n = Integer.parseInt(in.next()); int m = Integer.parseInt(in.next()); int v1[] = new int[n]; int v2[] = new int[m]; for(int i = 0; i < n; i ++) v1[i] = Integer.parseInt(in.next()); for(int i = 0; i < m; i ++) v2[i] = Integer.parseInt(in.next()); int min = 0; int j = 0; for(int i = 0; i < n; i ++) { int minD = Integer.MAX_VALUE; int p = (int)(-1E9 + 1); int d = (int)(1E9 + 1); for(; j < m; j ++) { if(v2[j] < v1[i]) { p = v2[j]; }else { d = v2[j]; break; } } if(j == m) { minD = Math.abs(v2[m - 1] - v1[i]); }else { if(p != (int)(-1E9 + 1)) minD = Math.min(Math.abs(p - v1[i]), Math.abs(d - v1[i])); else minD = Math.abs(d - v1[i]); } if(minD > min) min = minD; if(j > 0) j --; } System.out.println(min); } }
Java
["3 2\n-2 2 4\n-3 0", "5 3\n1 5 10 14 17\n4 11 15"]
3 seconds
["4", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation" ]
9fd8e75cb441dc809b1b2c48c4012c76
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
1,500
Print minimal r so that each city will be covered by cellular network.
standard output
PASSED
6a5e1ed88757ac52aea4e0701c226df4
train_002.jsonl
1469804400
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
256 megabytes
import java.util.List; import java.util.Scanner; public class problemF { public static int runBinarySearchIteratively(long[] sortedArray, long key, int low, int high) { while (low < high) { int mid = (low + high + 1) / 2; if (mid >= sortedArray.length) { break; } if (sortedArray[mid]< key) { low = mid; } else if (sortedArray[mid] > key) { high = mid - 1; } else if (sortedArray[mid] == key) { return mid; } } return low; } public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int m = scan.nextInt(); long[] a = new long[n]; long[] b = new long[m]; for (int i = 0; i < n; i++) { a[i] = scan.nextLong(); } for (int i = 0; i < m; i++) { b[i] = scan.nextLong(); } int counter = 0; int index = -1; long res = Long.MIN_VALUE; for (int i = 0; i < n; i++) { long num = Math.abs(a[i] - b[counter]); int j = counter + 1; for (j = j; j < m; j++) { long temp = Math.abs(a[i] - b[j]); if (temp <= num) { num = temp; index = j; } else { break; } } if (index != -1) { counter = index; } if (res < num) { res = num; } } System.out.print(res); } }
Java
["3 2\n-2 2 4\n-3 0", "5 3\n1 5 10 14 17\n4 11 15"]
3 seconds
["4", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation" ]
9fd8e75cb441dc809b1b2c48c4012c76
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
1,500
Print minimal r so that each city will be covered by cellular network.
standard output
PASSED
c21dc5ba2b8e9805ea05ba16f3087637
train_002.jsonl
1469804400
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
256 megabytes
import java.util.*; public class Towers { static long Max(long a, long b){ if(a>b) return a; return b; } static long Min(long a, long b){ if(a>b) return b; return a; } static long Abs(long a){ if (a<0) return -a; return a; } //COMMENT /* static int FindNext(ArrayList<Long> Cities, ArrayList<Long> Towers, int i, int j){ if(j==Towers.size()-1){ return j; } if(Towers.get(j)>=Cities.get(i)){ return j; } if(Towers.get(j+1)>= Cities.get(i)){ return j+1; } else { return FindNext(Cities, Towers, i, j+1); } } static void ComputeMin(ArrayList<Long> Cities, ArrayList<Long> Towers){ long r = 0; int i = 0; int j = 0; while(i<Cities.size()){ if((i>=1)&&(Cities.get(i-1)==Cities.get(i))) {i++; continue; } int next = FindNext(Cities, Towers, i, j); if (next == j){ r = Max(r, Abs(Towers.get(j)-Cities.get(i))); i++; continue; } else { long d = Min(Abs(Towers.get(next)-Cities.get(i)), Abs(Cities.get(i)-Towers.get(next-1))); r = Max(d, r); i++; j = next; continue; } } System.out.println(r); } */ //END OF COMMENT static void ComputeMin(ArrayList<Long> Cities, ArrayList<Long> Towers, int n, int m){ long r = 0; for(int i = 0, left = 0; i<n; i++){ while(left<m-1 && Towers.get(left+1)<Cities.get(i)) left++; long d = Abs(Towers.get(left)-Cities.get(i)); if(left<m-1) d = Min(d, Abs(Towers.get(left+1)-Cities.get(i))); r = Max(r, d); } System.out.println(r); } public static void main(String[] args) { // TODO Auto-generated method stub ArrayList<Long> Cities = new ArrayList<Long>(); ArrayList<Long> Towers = new ArrayList<Long>(); int n, m; Scanner sc = new Scanner(System.in); n = sc.nextInt(); m = sc.nextInt(); for(int i = 0; i<n; i++){ Cities.add(sc.nextLong()); } for(int i = 0; i<m; i++){ Towers.add(sc.nextLong()); } ComputeMin(Cities, Towers, n , m); sc.close(); } }
Java
["3 2\n-2 2 4\n-3 0", "5 3\n1 5 10 14 17\n4 11 15"]
3 seconds
["4", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation" ]
9fd8e75cb441dc809b1b2c48c4012c76
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
1,500
Print minimal r so that each city will be covered by cellular network.
standard output
PASSED
796f5544c50fc2afced75c89fce72b74
train_002.jsonl
1469804400
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.Stack; import java.util.Vector; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Arthur Gazizov - Kazan FU #4.3 [2oo7] */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int m = in.nextInt(); long[] a = IOUtils.readLongArray(in, n); long[] b = IOUtils.readLongArray(in, m); TaskC.Temp[] temps = new TaskC.Temp[n + m + 2]; int pos = 0; for (int i = 0; i < n; i++, pos++) { temps[pos] = new TaskC.Temp(a[i], true); } for (int i = 0; i < m; i++, pos++) { temps[pos] = new TaskC.Temp(b[i], false); } temps[pos] = new TaskC.Temp(-200000000001l, false); pos++; temps[pos] = new TaskC.Temp(200000000001l, false); Arrays.sort(temps, (l, r) -> { int cmp = Long.compare(l.position, r.position); if (cmp == 0) { cmp = Boolean.compare(l.isVillage, r.isVillage); } return cmp; }); long ans = 0; Stack<TaskC.Temp> stack = new Stack<>(); TaskC.Temp start = null, end = null; for (int i = 0; i < temps.length; i++) { if (temps[i].isVillage) { stack.push(temps[i]); } else { if (start == null) { start = temps[i]; } else { end = temps[i]; if (!stack.isEmpty()) { while (!stack.isEmpty()) { ans = Math.max(ans, Math.min(Math.abs(stack.peek().position - start.position), Math.abs(stack.peek().position - end.position))); stack.pop(); } } start = end; } } } out.print(ans); } static class Temp { public long position; boolean isVillage; public Temp(long position, boolean isVillage) { this.position = position; this.isVillage = isVillage; } } } 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 print(long i) { writer.print(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 int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class IOUtils { public static long[] readLongArray(InputReader in, int size) { long[] array = new long[size]; for (int i = 0; i < size; i++) { array[i] = in.nextLong(); } return array; } } }
Java
["3 2\n-2 2 4\n-3 0", "5 3\n1 5 10 14 17\n4 11 15"]
3 seconds
["4", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation" ]
9fd8e75cb441dc809b1b2c48c4012c76
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
1,500
Print minimal r so that each city will be covered by cellular network.
standard output
PASSED
26adc13a46ab973abe48d89f95afc568
train_002.jsonl
1469804400
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * Created by Valeriy Belaventsev on 30.07.2016. */ public class ProblemC { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(in.readLine()); int pNum = Integer.parseInt(st.nextToken()); int tNum = Integer.parseInt(st.nextToken()); st = new StringTokenizer(in.readLine()); long INF = (long) Math.pow(10, 11); long[] peoples = new long[pNum]; long[] towers = new long[tNum + 2]; towers[0] = -INF; towers[tNum + 1] = INF; for (int i = 0; i < pNum; i++) { peoples[i] = Long.parseLong(st.nextToken()); } st = new StringTokenizer(in.readLine()); for (int i = 1; i < tNum + 1; i++) { towers[i] = Long.parseLong(st.nextToken()); } long answer = -1; int pos = 0; for (int i = 0; i < tNum + 1; i++) { while (pos < pNum && peoples[pos] <= towers[i + 1]) { answer = Math.max(answer, Math.min(towers[i + 1] - peoples[pos], peoples[pos] - towers[i])); pos++; } } System.out.println(answer); } }
Java
["3 2\n-2 2 4\n-3 0", "5 3\n1 5 10 14 17\n4 11 15"]
3 seconds
["4", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation" ]
9fd8e75cb441dc809b1b2c48c4012c76
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
1,500
Print minimal r so that each city will be covered by cellular network.
standard output
PASSED
0f5a31ee631f19b4a1af23bf69b36116
train_002.jsonl
1469804400
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { public static InputReader in; public static PrintWriter pw; public static void main(String args[]) { new Thread(null, new Runnable() { public void run() { try{ solve(); } catch(Exception e){ e.printStackTrace(); } } }, "1", 1 << 26).start(); } //static HashSet<Integer> set; static ArrayList<Integer> g[]; static ArrayList<Integer> h[]; //static boolean visited[]; static long edje=0; static boolean vis[]; static int col[]; static boolean[] visited; static int Parent[]; static int Ans=0; static int min=Integer.MAX_VALUE; static boolean vis1[]; static int degree[]; static int f[]; static int size[]; static int n; static int edjes=0; static int start=-1; static int end=-1; static boolean bool=false; static int Total=0; static int nums[]; //static int a[]; static int fr[]; static int min1=Integer.MAX_VALUE; static TreeSet<String> set; static int a[]; static int time1[]; static int time2[]; static int glob=0; static HashSet<Integer>[] s; static StringBuilder tmp=new StringBuilder(); static HashMap<String,String> hm=new HashMap<String,String>(); public static void solve(){ in = new InputReader(System.in); pw = new PrintWriter(System.out); int n=in.nextInt(); int m=in.nextInt(); int a[]=in.nextIntArray(n); int b[]=in.nextIntArray(m); long low=0; long high=(long)1e12; //int tmp=0; while(low<=high) { long mid=(low+high)/2; if(fun(a,b,mid)) { high=mid-1; //tmp=mid; } else { low=mid+1; } } System.out.println(low); } public static boolean fun(int a[],int b[],long mid) { int ind=0; for(int i=0;i<b.length;i++){ long curmin=b[i]-mid; long curmax=b[i]+mid; while(ind<a.length && a[ind]>=curmin && a[ind]<=curmax) ind++; } return ind==a.length; } /* SubTree Checker DFS (TO CHECK IF X IS IN A SUBTREE OF Y) public static void dfs(int curr) { visited[curr]=true; time1[curr]=glob++; for(int x:g[curr]) { if(!visited[x]) dfs(x); } time2[curr]=glob++; } /*NO OF EDJES IN WHOLE CONNECTED COMPONENTS public static void dfs1(int curr) { visited[curr]=true; for(int next:g[curr]) { edje++; if(!visited[next]) dfs1(next); } } /*SUM OF ALL SUBTREE NODE'S VLAUES DFS public static void dfs(int curr,int prev) { val[curr]=1; for(int x:g[curr]) { if(x!=prev) { dfs(x,curr); val[curr]+=val[x]; } } }*/ public static long power(long a,long b) { long result=1; while(b>0) { if(b%2==1) result*=a; a=a*a; b/=2; } return result; } public static long pow(long n,long p,long m) { long result = 1; if(p==0) return 1; if (p==1) return n; while(p!=0) { if(p%2==1) result *= n; if(result>=m) result%=m; p >>=1; n*=n; if(n>=m) n%=m; } return result; } static class Pair implements Comparable<Pair>{ int y; int x; Pair(int mr,int i){ y=mr; x=i; } @Override public int compareTo(Pair o) { // if(o.dis<this.dis) return 1; // else // return -1; } } public static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a%b); } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["3 2\n-2 2 4\n-3 0", "5 3\n1 5 10 14 17\n4 11 15"]
3 seconds
["4", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation" ]
9fd8e75cb441dc809b1b2c48c4012c76
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
1,500
Print minimal r so that each city will be covered by cellular network.
standard output
PASSED
f287f7b351b0f426d96275b51b11b3c6
train_002.jsonl
1469804400
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
256 megabytes
import java.util.*; import java.io.*; /** * * @author Umang Upadhyay */ public class C702 { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n = in.nextInt(); int m = in.nextInt(); int[] a = in.nextIntArray(n); int[] b = in.nextIntArray(m); Arrays.sort(a); Arrays.sort(b); int ans=Integer.MAX_VALUE; int temp=0; int pos=0; for(int i=0;i<m;i++){ if(i==0 && a[pos]<b[i]){ temp=b[i]-a[pos]; while(pos<n && a[pos]<=b[i]) pos++; } else{ if(i<m-1){ while(pos<n && a[pos]<=b[i+1]){ temp=Math.max(temp,Math.min(a[pos]-b[i],b[i+1]-a[pos])); pos++; } } else{ while(pos<n){ temp=Math.max(temp, Math.abs(a[pos]-b[i])); pos++; } } } // w.println(temp+" "+i); } w.println(temp); w.close(); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["3 2\n-2 2 4\n-3 0", "5 3\n1 5 10 14 17\n4 11 15"]
3 seconds
["4", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation" ]
9fd8e75cb441dc809b1b2c48c4012c76
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
1,500
Print minimal r so that each city will be covered by cellular network.
standard output
PASSED
9ce909865c1ce8f765ff2d8ef40929cd
train_002.jsonl
1469804400
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
256 megabytes
/** * * @author sarthak */ import java.util.*; import java.math.*; import java.io.*; public class edurnd15_C { static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public String nextLine() { st = null; try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); return ""; } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } static class P implements Comparable { private int x, y; public P(int x, int y) { this.x = x; this.y = y; } public int hashCode() { return (x * 31) ^ y; } public boolean equals(Object o) { if (o instanceof P) { P other = (P) o; return (x == other.x && y == other.y); } return false; } public int compareTo(Object obj) { P l = (P) obj; if (this.x == l.x) { if (this.y == l.y) { return 0; } return (this.y < l.y) ? -1 : 1; } return (this.x < l.x) ? -1 : 1; } } public static void main(String[] args) { FastScanner s = new FastScanner(System.in); StringBuilder op = new StringBuilder(); int n = s.nextInt(); int m = s.nextInt(); ArrayList<Integer> al=new ArrayList<>(); for(int i=0;i<n;i++)al.add(s.nextInt()); TreeSet<Integer> t=new TreeSet<>(); for(int i=0;i<m;i++) t.add(s.nextInt()); int an=0; for(int c:al){ if(t.ceiling(c)==null)an=Math.max(an,c-t.floor(c)); else if(t.floor(c)==null)an=Math.max(an,t.ceiling(c)-c ); else an=Math.max(an,Math.min(c-t.floor(c),t.ceiling(c)-c)); } System.out.println(an); } }
Java
["3 2\n-2 2 4\n-3 0", "5 3\n1 5 10 14 17\n4 11 15"]
3 seconds
["4", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation" ]
9fd8e75cb441dc809b1b2c48c4012c76
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
1,500
Print minimal r so that each city will be covered by cellular network.
standard output
PASSED
64cf8779bae1883b0a93bea5f2187780
train_002.jsonl
1469804400
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { try (Scanner in = new Scanner(System.in)) { int N = in.nextInt(); int M = in.nextInt(); int[] cities = new int[N]; int[] towers = new int[M]; for (int i = 0; i < N; i++) { cities[i] = in.nextInt(); } for (int i = 0; i < M; i++) { towers[i] = in.nextInt(); } int l = 0, r = 2_000_000_000; int found = -1; while (l <= r){ int m = l + (r - l) / 2; if (isPossible(cities, towers, m)){ found = m; r = m - 1; } else l = m + 1; } System.out.println(found); } } private static boolean isPossible(int[] cities, int[] towers, int radius){ final int N = cities.length; final int M = towers.length; int j = 0; for (int i = 0; i < M; i++) { long x = (long)towers[i] - radius; long y = (long)towers[i] + radius; while (j < N && (x <= cities[j] && cities[j] <= y)) j++; } return j == N; } }
Java
["3 2\n-2 2 4\n-3 0", "5 3\n1 5 10 14 17\n4 11 15"]
3 seconds
["4", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation" ]
9fd8e75cb441dc809b1b2c48c4012c76
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
1,500
Print minimal r so that each city will be covered by cellular network.
standard output
PASSED
a4f0d70a296fe5764e961acc96cee85b
train_002.jsonl
1469804400
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
256 megabytes
import java.io.PrintWriter; import java.util.Scanner; import java.util.Arrays; public class TaskC{ public static void main(String[] args) { TaskC tC = new TaskC(); PrintWriter pw = new PrintWriter(System.out); tC.solve(new Scanner(System.in), pw); pw.close(); } public void solve(Scanner input, PrintWriter output) { int n = input.nextInt(); int m = input.nextInt(); int[] a = new int[n]; int[] b = new int[m]; int high = Integer.MIN_VALUE; int low = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { a[i] = input.nextInt(); high = Math.max(high, a[i]); low = Math.min(low, a[i]); } for (int i = 0; i < m; i++) { b[i] = input.nextInt(); high = Math.max(high, b[i]); low = Math.min(low, b[i]); } Arrays.sort(a); Arrays.sort(b); int l = 0; int r = high - low; // System.out.println("high = " + high + " low = " + low); int result = -1; while (l <= r) { int mid = l/2 + r/2; if (l % 2 == 1 && r % 2 == 1) mid++; // output.println(l + " " + mid + " " + r); if (canCover(a, b, mid)) { result = mid; r = mid - 1; // output.println(result); } else { l = mid + 1; } } output.println(result); } private boolean canCover(int[] a, int[] b, int range) { for (int i = 0; i < a.length; i++) { int l = 0; int r = b.length - 1; int result = -1; while (l <= r) { int mid = (l + r) / 2; if (b[mid] <= a[i]) { result = mid; l = mid + 1; } else { r = mid - 1; } } int closest = Integer.MAX_VALUE; if (result == -1) closest = b[0] - a[i]; else { closest = a[i] - b[result]; if (result < b.length - 1) closest = Math.min(closest, b[result + 1] - a[i]); // System.out.println(" closest = " + closest); } // System.out.println(" i = " + i + " closest = " + closest + " range = " + range); if (closest > range) return false; } return true; } }
Java
["3 2\n-2 2 4\n-3 0", "5 3\n1 5 10 14 17\n4 11 15"]
3 seconds
["4", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation" ]
9fd8e75cb441dc809b1b2c48c4012c76
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
1,500
Print minimal r so that each city will be covered by cellular network.
standard output
PASSED
968f14a79cd1d204a62379604f40a070
train_002.jsonl
1469804400
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashSet; import java.util.StringTokenizer; public class C { static boolean bs1(int[] b, int sz, int target, int x, int status) { int lo = 0; int hi = sz - 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (status == 0) { if (b[mid] >= target && b[mid] <= x) return true; else if (b[mid] > target) hi = mid - 1; else lo = mid + 1; } if (status == 1) { if (b[mid] <= target && b[mid] >= x) return true; else if (b[mid] > target) hi = mid - 1; else lo = mid + 1; } } return false; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int M = sc.nextInt(); HashSet<Integer> set = new HashSet<Integer>(); int[] a = new int[N]; int[] b = new int[M]; int sz_a = 0; int sz_b = 0; int k = 0; for (int i = 0; i < N; i++) { int x = sc.nextInt(); if (!set.contains(x)) { a[k++] = x; sz_a++; set.add(x); } } set.clear(); k = 0; for (int i = 0; i < M; i++) { int x = sc.nextInt(); if (!set.contains(x)) { b[k++] = x; sz_b++; set.add(x); } } int lo = 0; int hi = (2 * (int) (1e9)); int answer = -1; while (lo <= hi) { int r = lo + (hi - lo) / 2; boolean ok = true; for (int i = 0; i < sz_a; i++) { ok &= (bs1(b, sz_b, a[i] - r, a[i], 0) || bs1(b, sz_b, a[i] + r, a[i], 1)); } if (ok) { answer = r; hi = r - 1; } else lo = r + 1; } System.out.println(answer); } 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 { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["3 2\n-2 2 4\n-3 0", "5 3\n1 5 10 14 17\n4 11 15"]
3 seconds
["4", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation" ]
9fd8e75cb441dc809b1b2c48c4012c76
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
1,500
Print minimal r so that each city will be covered by cellular network.
standard output
PASSED
ba4eccdd430627e4a0bc7bd7ded1cb75
train_002.jsonl
1469804400
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class CellularNetwork { public static int binary_search(int b[], int key) { int lo = 0; int hi = b.length - 1; int nearest = Integer.MAX_VALUE; while (lo <= hi) { // Key is in a[lo..hi] or not present. int mid = lo + (hi - lo) / 2; if(key < b[mid]){ hi = mid - 1; nearest = Math.min(nearest, Math.abs(b[mid]-key)); } else if (key > b[mid]){ lo = mid + 1; nearest = Math.min(nearest, Math.abs(b[mid]-key)); } else return 0; } return nearest; } public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int a[] = new int[n]; int b[] = new int[m]; sc.nextLine(); for(int i=0; i<n; i++) a[i] = sc.nextInt(); sc.nextLine(); for(int i=0; i<m; i++) { b[i] = sc.nextInt(); //System.out.print(b[i] +" "); } //System.out.println(); int ret = 0; for(int i=0; i<n; i++) { int nearest = binary_search(b, a[i]); ret = Math.max(ret, nearest); } System.out.println(ret); //Arrays.binarySearch(intArr,searchVal); } }
Java
["3 2\n-2 2 4\n-3 0", "5 3\n1 5 10 14 17\n4 11 15"]
3 seconds
["4", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation" ]
9fd8e75cb441dc809b1b2c48c4012c76
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
1,500
Print minimal r so that each city will be covered by cellular network.
standard output
PASSED
f71ee1b3e4edb0323b2f878f4ee1b11a
train_002.jsonl
1469804400
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
256 megabytes
import java.io.IOException; import java.io.InputStreamReader; import java.io.BufferedReader; public class C { public static void main(String[]args)throws IOException,NumberFormatException{ BufferedReader bf =new BufferedReader(new InputStreamReader(System.in)); String s=bf.readLine(); String[]sa=s.split(" "); int n=Integer.parseInt(sa[0]); int m=Integer.parseInt(sa[1]); s=bf.readLine(); sa=s.split(" "); long []a=new long[n]; for(int i=0;i<n;i++){ a[i]=Long.parseLong(sa[i]); } s=bf.readLine(); sa=s.split(" "); long []b=new long[m]; for(int i=0;i<m;i++){ b[i]=Long.parseLong(sa[i]); } int j=0; long max=0; for(int i=0;i<n;i++){ long d=Long.MAX_VALUE; while(j<m && Math.abs(a[i]-b[j])<=d){ d=Math.abs(a[i]-b[j]); j++; } j--; if(d>max) max=d; } System.out.println(max); } }
Java
["3 2\n-2 2 4\n-3 0", "5 3\n1 5 10 14 17\n4 11 15"]
3 seconds
["4", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation" ]
9fd8e75cb441dc809b1b2c48c4012c76
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
1,500
Print minimal r so that each city will be covered by cellular network.
standard output
PASSED
0e22d809e39679f3ec9e19b3d2f80f2e
train_002.jsonl
1469804400
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author dmytro.prytula prituladima@gmail.com */ 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); HSotovayaSvyaz solver = new HSotovayaSvyaz(); solver.solve(1, in, out); out.close(); } static class HSotovayaSvyaz { int n; int m; int[] a; int[] b; public void solve(int testNumber, InputReader in, OutputWriter out) { n = in.nextInt(); m = in.nextInt(); a = in.nextIntArray(n); b = in.nextIntArray(m); int r = (int) 2e9 + 1; int L = 0; int R = (int) 2e9 + 1; while (L <= R) { int mid = (L + R) >>> 1; if (fine(mid)) { r = mid; R = mid - 1; } else { L = mid + 1; } } out.printLine(r); } private boolean fine(int r) { boolean ok = true; for (int i = 0; i < n; i++) { int city = a[i]; ok &= r >= Math.abs(city - findClosest(b, m, city)); if (!ok) return false; } return true; } private int findClosest(int arr[], int n, int target) { // Corner cases if (target <= arr[0]) return arr[0]; if (target >= arr[n - 1]) return arr[n - 1]; // Doing binary search int i = 0, j = n, mid = 0; while (i < j) { mid = (i + j) / 2; if (arr[mid] == target) return arr[mid]; /* If target is less than array element, then search in left */ if (target < arr[mid]) { // If target is greater than previous // to mid, return closest of two if (mid > 0 && target > arr[mid - 1]) return getClosest(arr[mid - 1], arr[mid], target); /* Repeat for left half */ j = mid; } // If target is greater than mid else { if (mid < n - 1 && target < arr[mid + 1]) return getClosest(arr[mid], arr[mid + 1], target); // update i i = mid + 1; } } // Only single element left after search return arr[mid]; } private int getClosest(int val1, int val2, int target) { if (target - val1 >= val2 - target) return val2; else return val1; } } 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 OutputWriter printLine(int i) { writer.println(i); return this; } } 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[] nextIntArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = nextInt(); } return array; } 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++]; } 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; } private boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } private static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["3 2\n-2 2 4\n-3 0", "5 3\n1 5 10 14 17\n4 11 15"]
3 seconds
["4", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation" ]
9fd8e75cb441dc809b1b2c48c4012c76
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
1,500
Print minimal r so that each city will be covered by cellular network.
standard output
PASSED
dcc3afb7e832bce959f9952b05f6b3fc
train_002.jsonl
1469804400
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
256 megabytes
import java.util.*; public class TaskC { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int[] houses = new int[n]; int[] towers = new int[m]; for (int i = 0; i < n; i++) { houses[i] = in.nextInt(); } for (int i = 0; i < m; i++) { towers[i] = in.nextInt(); } int r = Math.max(towers[0] - houses[0], houses[n-1] - towers[m-1]); r = Math.max(r, 0); for (int i = 0, j = 1; i < n && j < m;) { if (houses[i] < towers[j - 1]) { i++; } else if (houses[i] > towers[j]) { j++; } else { int maybe_r = Math.min(houses[i] - towers[j-1], towers[j]-houses[i]); r = Math.max(r, maybe_r); i++; } } System.out.println(r); } }
Java
["3 2\n-2 2 4\n-3 0", "5 3\n1 5 10 14 17\n4 11 15"]
3 seconds
["4", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation" ]
9fd8e75cb441dc809b1b2c48c4012c76
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
1,500
Print minimal r so that each city will be covered by cellular network.
standard output
PASSED
9dbf11755a9d07e23093793fea655431
train_002.jsonl
1469804400
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
256 megabytes
import java.util.*; public class Main { public static void main(String [] args) { final int N = 100000 + 10; int[] a = new int[N]; int[] b = new int[N]; Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); for(int i = 0; i < n; ++i) a[i] = in.nextInt(); for(int i = 0; i < m; ++i) b[i] = in.nextInt(); long l = 0; long r = 2000000000 + 10; while(l < r) { long mid = (l+r) >> 1; //System.out.println("l = " + l + " r = " + r + " mid = " + mid); boolean ok = true; for(int i = 0; i < n; ++i) { int ub = upper_bound(b, 0, m, a[i]); if(ub == m) { if(a[i] - b[ub-1] > mid) ok = false; } else if(ub == 0) { if(b[ub] - a[i] > mid) ok = false; } else { if(a[i] - b[ub-1] > mid && b[ub] - a[i] > mid) ok = false; } } //int x = in.nextInt(); if(!ok) l = mid+1; else r = mid; } System.out.println(r); } public static int lower_bound(int a[], int l, int r, int val) { while(l < r) { int m = (l+r) >> 1; if(a[m] < val) l = m+1; else r = m; } return r; } public static int upper_bound(int a[], int l, int r, int val) { while(l < r) { int m = (l+r) >> 1; if(a[m] <= val) l = m+1; else r = m; } return r; } }
Java
["3 2\n-2 2 4\n-3 0", "5 3\n1 5 10 14 17\n4 11 15"]
3 seconds
["4", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation" ]
9fd8e75cb441dc809b1b2c48c4012c76
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
1,500
Print minimal r so that each city will be covered by cellular network.
standard output
PASSED
7fe02a740b2a17fd78abf8f85fdf4082
train_002.jsonl
1469804400
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
256 megabytes
import java.util.*; public class Solution702C { public static void main(String[] args) { Solution702C ss = new Solution702C(); ss.run(); } void run() { Scanner sc = new Scanner(System.in); int n = sc.nextInt(), m = sc.nextInt(); int[] city = new int[n], net = new int[m]; for (int i = 0; i < n; i++) city[i] = sc.nextInt(); for (int i = 0; i < m; i++) net[i] = sc.nextInt(); int[] d = new int[m + 1]; int ic = 0, in = 0; while (ic < n) { if (in == m || city[ic] < net[in]) d[in]++; else { while (in < m && city[ic] >= net[in]) in++; d[in] = 1; } ic++; } int r = 0; if (d[0] != 0) r = net[0] - city[0]; ic = d[0]; for (int i = 1; i < m; i++) while (d[i] > 0) { r = Math.max(r, Math.min(city[ic] - net[i - 1], net[i] - city[ic])); ic++; d[i]--; } if (d[m] != 0) r = Math.max(r, city[n - 1] - net[m - 1]); System.out.println(r); } }
Java
["3 2\n-2 2 4\n-3 0", "5 3\n1 5 10 14 17\n4 11 15"]
3 seconds
["4", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation" ]
9fd8e75cb441dc809b1b2c48c4012c76
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
1,500
Print minimal r so that each city will be covered by cellular network.
standard output
PASSED
a0ec55f6df81efd152c19a3dd653d8f8
train_002.jsonl
1469804400
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class BasicJava { public BasicJava() { } public InputReader in = new InputReader(System.in); public PrintWriter out = new PrintWriter(System.out); public int n = in.nextInt(); public int m = in.nextInt(); public int[] a = new int [100010]; public int[] b = new int [100010]; public boolean ok(long x) { int nr = 1; for (int i = 1; i <= m && nr <= n; i++) while (nr <= n && b[i] - x <= a[nr] && a[nr] <= b[i] + x) nr++; return (nr > n); } public void run() { for (int i = 1; i <= n; i++) a[i] = in.nextInt(); for (int i = 1; i <= m; i++) b[i] = in.nextInt(); long st = 1, dr = (long)2e9; long sol = 0; if (ok(0)) { out.println(0); out.close(); System.exit(0); } while (st <= dr) { long mm = (st+dr) / 2; if (ok(mm)) { sol = mm; dr = mm - 1; } else st = mm+1; } out.println(sol); out.close(); } public static void main(String[] args) { new BasicJava().run(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3 2\n-2 2 4\n-3 0", "5 3\n1 5 10 14 17\n4 11 15"]
3 seconds
["4", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation" ]
9fd8e75cb441dc809b1b2c48c4012c76
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
1,500
Print minimal r so that each city will be covered by cellular network.
standard output
PASSED
2788f1bce2593f868474e3af92c8c3a5
train_002.jsonl
1469804400
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.TreeSet; public class C { static TreeSet<Long> post; static final long INF = Long.MAX_VALUE / 2L; static long lower(long key) { if (post.contains(key)) return key; Long low; return (low = post.lower(key)) != null ? low : INF; } static long higher(long key) { if (post.contains(key)) return key; Long high; return (high = post.higher(key)) != null ? high : INF; } public static void main(String[] args) throws IOException { File inputFile = new File("entradaC"); if (inputFile.exists()) System.setIn(new FileInputStream(inputFile)); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder out = new StringBuilder(); String line = ""; while ((line = in.readLine()) != null) { int[] nm = readInts(line); int n = nm[0], m = nm[1]; int[] a = readInts(in.readLine()); int[] b = readInts(in.readLine()); post = new TreeSet<>(); for (int i = 0; i < m; i++) post.add(b[i]*1L); long ans = 0, cur; for (int i = 0; i < n; i++) { cur = Math.min(Math.abs(lower(a[i]) - a[i]), Math.abs(higher(a[i]) - a[i])); ans = Math.max(ans, cur); } out.append(ans + "\n"); } System.out.print(out); } static int[] readInts(String line) { StringTokenizer st = new StringTokenizer(line.trim()); int a[] = new int[st.countTokens()], index = 0; while (st.hasMoreTokens()) a[index++] = Integer.parseInt(st.nextToken()); return a; } static long[] readLongs(String line) { StringTokenizer st = new StringTokenizer(line.trim()); long a[] = new long[st.countTokens()]; int index = 0; while (st.hasMoreTokens()) a[index++] = Long.parseLong(st.nextToken()); return a; } static double[] readDoubles(String line) { StringTokenizer st = new StringTokenizer(line.trim()); double a[] = new double[st.countTokens()]; int index = 0; while (st.hasMoreTokens()) a[index++] = Double.parseDouble(st.nextToken()); return a; } }
Java
["3 2\n-2 2 4\n-3 0", "5 3\n1 5 10 14 17\n4 11 15"]
3 seconds
["4", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation" ]
9fd8e75cb441dc809b1b2c48c4012c76
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
1,500
Print minimal r so that each city will be covered by cellular network.
standard output
PASSED
699da5e6a8125771977d1dfe272f9e1f
train_002.jsonl
1469804400
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
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.Comparator; import java.util.Map; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.util.TreeMap; import javax.swing.text.StyledEditorKit.ForegroundAction; public class Main2 { static FastReader input = new FastReader(); static PrintWriter out = new PrintWriter(System.out); static int n, m; static int[] a, b; static void shuffle(int[] a) { int n = a.length; for(int i = 0; i < n; i++) { int r = i + (int)(Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } static boolean p(long r) { int j = 0; for (int i = 0; i < m; i++) { while (j < n && (a[j] >= b[i] - r && a[j] <= b[i] + r)) { j++; } } return j == n; } public static void main(String[] args) throws IOException { n = input.nextInt(); m = input.nextInt(); a = new int[n]; b = new int[m]; for (int i = 0; i < n; i++) { a[i] = input.nextInt(); } for (int i = 0; i < m; i++) { b[i] = input.nextInt(); } shuffle(a); Arrays.sort(a); shuffle(b); Arrays.sort(b); long l = 0 ; long r = (long)1e15; while (l < r) { long mid = l + (r - l) / 2; if (p(mid)) r = mid; else l = mid + 1; } System.out.println(l); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws IOException { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } String nextLine() throws IOException { String str = ""; str = br.readLine(); return str; } } }
Java
["3 2\n-2 2 4\n-3 0", "5 3\n1 5 10 14 17\n4 11 15"]
3 seconds
["4", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation" ]
9fd8e75cb441dc809b1b2c48c4012c76
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
1,500
Print minimal r so that each city will be covered by cellular network.
standard output
PASSED
06320210136123b3f57edc48647ff261
train_002.jsonl
1469804400
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class C702 { public static boolean valid(int[] country, int[] tower, long mid){ boolean[] covered = new boolean[country.length]; for (int i = 0, j = 0; i < covered.length && j<tower.length;) { int t = tower[j]; int c = country[i]; Circle tow = new Circle(new Point(t, 0), mid); Point p = new Point(c, 0); // System.out.println(tow.inside(p)); if(tow.inside(p) >=0 ){ covered[i] = true; // continue; // System.out.println(t+" "+c); i++; } else j++; } for (int i = 0; i < covered.length; i++) { if(!covered[i]) return false; } return true; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int[] c = new int[n]; int[] t = new int[m]; for (int i = 0; i < c.length; i++) { c[i] = sc.nextInt(); } for (int i = 0; i < t.length; i++) { t[i] = sc.nextInt(); } Arrays.sort(t); Arrays.sort(c); // System.out.println(valid(c, t, 5)); long lo = 0; long hi = (long)2e9; long ans = 0; while(lo<=hi){ long mid = (lo+hi)/2; if(valid(c, t, mid)) { // System.out.println("hi"); // ans = mid; // System.out.println(mid); ans = mid; // if(valid(c,t,mid-1)) hi = mid-1; // else // break; } else { lo = mid+1; } } System.out.println(ans); } static class Point implements Comparable<Point>{ static final double EPS = 1e-11; double x, y; Point(double a, double b) { x = a; y = b; } public int compareTo(Point p) { if(Math.abs(x - p.x) > EPS) return x > p.x ? 1 : -1; if(Math.abs(y - p.y) > EPS) return y > p.y ? 1 : -1; return 0; } public double dist(Point p) { return Math.sqrt(sq(x - p.x) + sq(y - p.y)); } static double sq(double x) { return x * x; } Point rotate(double angle) { double c = Math.cos(angle), s = Math.sin(angle); return new Point(x * c - y * s, x * s + y * c); } // for integer points and rotation by 90 (counterclockwise) : swap x and y, negate x Point rotate(double theta, Point p) //rotate around p { Vector v = new Vector(p, new Point(0, 0)); return translate(v).rotate(theta).translate(v.reverse()); } Point translate(Vector v) { return new Point(x + v.x , y + v.y); } // // Point reflectionPoint(Line l) //reflection point of p on line l // { // Point p = l.closestPoint(this); // Vector v = new Vector(this, p); // return this.translate(v).translate(v); // } boolean between(Point p, Point q) { return x < Math.max(p.x, q.x) + EPS && x + EPS > Math.min(p.x, q.x) && y < Math.max(p.y, q.y) + EPS && y + EPS > Math.min(p.y, q.y); } //returns true if it is on the line defined by a and b boolean onLine(Point a, Point b) { if(a.compareTo(b) == 0) return compareTo(a) == 0; return Math.abs(new Vector(a, b).cross(new Vector(a, this))) < EPS; } boolean onSegment(Point a, Point b) { if(a.compareTo(b) == 0) return compareTo(a) == 0; return onRay(a, b) && onRay(b, a); } //returns true if it is on the ray whose start point is a and passes through b boolean onRay(Point a, Point b) { if(a.compareTo(b) == 0) return compareTo(a) == 0; return new Vector(a, b).normalize().equals(new Vector(a, this).normalize()); //implement equals() } // returns true if it is on the left side of Line pq // add EPS to LHS if on-line points are accepted static boolean ccw(Point p, Point q, Point r) { return new Vector(p, q).cross(new Vector(p, r)) > 0; } static boolean collinear(Point p, Point q, Point r) { return Math.abs(new Vector(p, q).cross(new Vector(p, r))) < EPS; } static double angle(Point a, Point o, Point b) // angle AOB { Vector oa = new Vector(o, a), ob = new Vector(o, b); return Math.acos(oa.dot(ob) / Math.sqrt(oa.norm2() * ob.norm2())); } static double distToLine(Point p, Point a, Point b) //distance between point p and a line defined by points a, b (a != b) { if(a.compareTo(b) == 0) p.dist(a); // formula: c = a + u * ab Vector ap = new Vector(a, p), ab = new Vector(a, b); double u = ap.dot(ab) / ab.norm2(); Point c = a.translate(ab.scale(u)); return p.dist(c); } // Another way: find closest point and calculate the distance between it and p static double distToLineSegment(Point p, Point a, Point b) { Vector ap = new Vector(a, p), ab = new Vector(a, b); double u = ap.dot(ab) / ab.norm2(); if (u < 0.0) return p.dist(a); if (u > 1.0) return p.dist(b); return distToLine(p, a, b); } // Another way: find closest point and calculate the distance between it and p } static public class Circle { //equation: (x-c.x)^2 + (y-c.y)^2 = r^2 static final double EPS = 1e-11; Point c; double r; Circle(Point p, double k) { c = p; r = k; } int inside(Point p) //1 for inside, 0 for border, -1 for outside { double d = p.dist(c); return d + EPS < r ? 1 : Math.abs(d - r) < EPS ? 0 : -1; } double circum() { return 2 * Math.PI * r; } double area() { return Math.PI * r * r; } double arcLength(double deg) { return deg / 360.0 * circum(); } //major and minor chords exist // double chordLength(double deg) // { // return 2 * r * Math.sin(Geometry.degToRad(deg) / 2.0); // } double sectorArea(double deg) { return deg / 360.0 * area(); } // double segmentArea(double deg) // { // return sectorArea(deg) - r * r * Math.sin(Geometry.degToRad(deg)) / 2.0; // } boolean intersect(Circle cir) { return c.dist(cir.c) <= r + cir.r + EPS && c.dist(cir.c) + EPS >= Math.abs(r - cir.r); } //returns true if the circle intersects with the line segment defined by p and q at one or two points // boolean intersect(Point p, Point q) // { // Line l = new Line(p, q); // if(Math.abs(l.b) < EPS) // { // if(l.c * l.c > r * r + EPS) // return false; // // double y1 = Math.sqrt(Math.abs(r * r - l.c * l.c)), y2 = -y1; // return new Point(-l.c, y1).between(p, q) && new Point(-l.c, y2).between(p, q); // } // double a = l.a * l.a + 1, b = 2 * l.a * l.c, c = l.c * l.c - r * r; // if(b * b - 4 * a * c + EPS < 0) // return false; // // double dis = b * b - 4 * a * c; // // double x1 = (-b + Math.sqrt(dis)) / (2.0 * a), x2 = (-b - Math.sqrt(dis)) / (2.0 * a); // // return new Point(x1, - l.a * x1 - l.c).between(p, q) || new Point(x2, - l.a * x2 - l.c).between(p, q); // } static Point findCenter(Point p, Point q, double r) //for the other center, swap p and q { double d2 = (p.x - q.x) * (p.x - q.x) + (p.y - q.y) * (p.y - q.y); double det = r * r / d2 - 0.25; if(Math.abs(det) < EPS) det = 0.0; if(det < 0.0) return null; double h = Math.sqrt(det); return new Point((p.x + q.x) / 2.0 + (p.y - q.y) * h, (p.y + q.y) / 2.0 + (q.x - p.x) * h); } } static public class Vector { double x, y; Vector(double a, double b) { x = a; y = b; } Vector(Point a, Point b) { this(b.x - a.x, b.y - a.y); } Vector scale(double s) { return new Vector(x * s, y * s); } //s is a non-negative value double dot(Vector v) { return (x * v.x + y * v.y); } double cross(Vector v) { return x * v.y - y * v.x; } double norm2() { return x * x + y * y; } Vector reverse() { return new Vector(-x, -y); } Vector normalize() { double d = Math.sqrt(norm2()); return scale(1 / d); } } }
Java
["3 2\n-2 2 4\n-3 0", "5 3\n1 5 10 14 17\n4 11 15"]
3 seconds
["4", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation" ]
9fd8e75cb441dc809b1b2c48c4012c76
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
1,500
Print minimal r so that each city will be covered by cellular network.
standard output